blob: 275d89ae7a82865e1d51709059b8fc22f8bb656b [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,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000204 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 if (IsOnePastTheEnd)
206 return true;
207 if (MostDerivedArraySize &&
208 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209 return true;
210 return false;
211 }
212
213 /// Check that this refers to a valid subobject.
214 bool isValidSubobject() const {
215 if (Invalid)
216 return false;
217 return !isOnePastTheEnd();
218 }
219 /// Check that this refers to a valid subobject, and if not, produce a
220 /// relevant diagnostic and set the designator as invalid.
221 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222
223 /// Update this designator to refer to the first element within this array.
224 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000225 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000227 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000228
229 // This is a most-derived object.
230 MostDerivedType = CAT->getElementType();
231 MostDerivedArraySize = CAT->getSize().getZExtValue();
232 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000233 }
234 /// Update this designator to refer to the given base or member of this
235 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000237 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000238 APValue::BaseOrMemberType Value(D, Virtual);
239 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000240 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000241
242 // If this isn't a base class, it's a new most-derived object.
243 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244 MostDerivedType = FD->getType();
245 MostDerivedArraySize = 0;
246 MostDerivedPathLength = Entries.size();
247 }
Richard Smith96e0c102011-11-04 02:25:55 +0000248 }
Richard Smith66c96992012-02-18 22:04:06 +0000249 /// Update this designator to refer to the given complex component.
250 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 PathEntry Entry;
252 Entry.ArrayIndex = Imag;
253 Entries.push_back(Entry);
254
255 // This is technically a most-derived object, though in practice this
256 // is unlikely to matter.
257 MostDerivedType = EltTy;
258 MostDerivedArraySize = 2;
259 MostDerivedPathLength = Entries.size();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000264 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000266 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269 setInvalid();
270 }
Richard Smith96e0c102011-11-04 02:25:55 +0000271 return;
272 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000273 // [expr.add]p4: For the purposes of these operators, a pointer to a
274 // nonarray object behaves the same as a pointer to the first element of
275 // an array of length one with the type of the object as its element type.
276 if (IsOnePastTheEnd && N == (uint64_t)-1)
277 IsOnePastTheEnd = false;
278 else if (!IsOnePastTheEnd && N == 1)
279 IsOnePastTheEnd = true;
280 else if (N != 0) {
281 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000282 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000283 }
Richard Smith96e0c102011-11-04 02:25:55 +0000284 }
285 };
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// A stack frame in the constexpr call stack.
288 struct CallStackFrame {
289 EvalInfo &Info;
290
291 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000292 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000293
Richard Smithf6f003a2011-12-16 19:06:07 +0000294 /// CallLoc - The location of the call expression for this call.
295 SourceLocation CallLoc;
296
297 /// Callee - The function which was called.
298 const FunctionDecl *Callee;
299
Richard Smithb228a862012-02-15 02:18:13 +0000300 /// Index - The call index of this call.
301 unsigned Index;
302
Richard Smithd62306a2011-11-10 06:34:14 +0000303 /// This - The binding for the this pointer in this call, if any.
304 const LValue *This;
305
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000306 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000308 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000309
Eli Friedman4830ec82012-06-25 21:21:08 +0000310 // Note that we intentionally use std::map here so that references to
311 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000312 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 typedef MapTy::const_iterator temp_iterator;
314 /// Temporaries - Temporary lvalues materialized within this stack frame.
315 MapTy Temporaries;
316
Richard Smithf6f003a2011-12-16 19:06:07 +0000317 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000319 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000320 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000321
322 APValue *getTemporary(const void *Key) {
323 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000324 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000325 }
326 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000327 };
328
Richard Smith852c9db2013-04-20 22:23:05 +0000329 /// Temporarily override 'this'.
330 class ThisOverrideRAII {
331 public:
332 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333 : Frame(Frame), OldThis(Frame.This) {
334 if (Enable)
335 Frame.This = NewThis;
336 }
337 ~ThisOverrideRAII() {
338 Frame.This = OldThis;
339 }
340 private:
341 CallStackFrame &Frame;
342 const LValue *OldThis;
343 };
344
Richard Smith92b1ce02011-12-12 09:28:41 +0000345 /// A partial diagnostic which we might know in advance that we are not going
346 /// to emit.
347 class OptionalDiagnostic {
348 PartialDiagnostic *Diag;
349
350 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000351 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000353
354 template<typename T>
355 OptionalDiagnostic &operator<<(const T &v) {
356 if (Diag)
357 *Diag << v;
358 return *this;
359 }
Richard Smithfe800032012-01-31 04:08:20 +0000360
361 OptionalDiagnostic &operator<<(const APSInt &I) {
362 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000363 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000364 I.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
369
370 OptionalDiagnostic &operator<<(const APFloat &F) {
371 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000372 // FIXME: Force the precision of the source value down so we don't
373 // print digits which are usually useless (we don't really care here if
374 // we truncate a digit by accident in edge cases). Ideally,
375 // APFloat::toString would automatically print the shortest
376 // representation which rounds to the correct value, but it's a bit
377 // tricky to implement.
378 unsigned precision =
379 llvm::APFloat::semanticsPrecision(F.getSemantics());
380 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000381 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000382 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000383 *Diag << StringRef(Buffer.data(), Buffer.size());
384 }
385 return *this;
386 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 };
388
Richard Smith08d6a2c2013-07-24 07:11:57 +0000389 /// A cleanup, and a flag indicating whether it is lifetime-extended.
390 class Cleanup {
391 llvm::PointerIntPair<APValue*, 1, bool> Value;
392
393 public:
394 Cleanup(APValue *Val, bool IsLifetimeExtended)
395 : Value(Val, IsLifetimeExtended) {}
396
397 bool isLifetimeExtended() const { return Value.getInt(); }
398 void endLifetime() {
399 *Value.getPointer() = APValue();
400 }
401 };
402
Richard Smithb228a862012-02-15 02:18:13 +0000403 /// EvalInfo - This is a private struct used by the evaluator to capture
404 /// information about a subexpression as it is folded. It retains information
405 /// about the AST context, but also maintains information about the folded
406 /// expression.
407 ///
408 /// If an expression could be evaluated, it is still possible it is not a C
409 /// "integer constant expression" or constant expression. If not, this struct
410 /// captures information about how and why not.
411 ///
412 /// One bit of information passed *into* the request for constant folding
413 /// indicates whether the subexpression is "evaluated" or not according to C
414 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415 /// evaluate the expression regardless of what the RHS is, but C only allows
416 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000417 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000418 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000419
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420 /// EvalStatus - Contains information about the evaluation.
421 Expr::EvalStatus &EvalStatus;
422
423 /// CurrentCall - The top of the constexpr call stack.
424 CallStackFrame *CurrentCall;
425
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000426 /// CallStackDepth - The number of calls in the call stack right now.
427 unsigned CallStackDepth;
428
Richard Smithb228a862012-02-15 02:18:13 +0000429 /// NextCallIndex - The next call index to assign.
430 unsigned NextCallIndex;
431
Richard Smitha3d3bd22013-05-08 02:12:03 +0000432 /// StepsLeft - The remaining number of evaluation steps we're permitted
433 /// to perform. This is essentially a limit for the number of statements
434 /// we will evaluate.
435 unsigned StepsLeft;
436
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000438 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 CallStackFrame BottomFrame;
440
Richard Smith08d6a2c2013-07-24 07:11:57 +0000441 /// A stack of values whose lifetimes end at the end of some surrounding
442 /// evaluation frame.
443 llvm::SmallVector<Cleanup, 16> CleanupStack;
444
Richard Smithd62306a2011-11-10 06:34:14 +0000445 /// EvaluatingDecl - This is the declaration whose initializer is being
446 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000447 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000448
449 /// EvaluatingDeclValue - This is the value being constructed for the
450 /// declaration whose initializer is being evaluated, if any.
451 APValue *EvaluatingDeclValue;
452
Richard Smith357362d2011-12-13 06:39:58 +0000453 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454 /// notes attached to it will also be stored, otherwise they will not be.
455 bool HasActiveDiagnostic;
456
Richard Smith6d4c6582013-11-05 22:18:15 +0000457 enum EvaluationMode {
458 /// Evaluate as a constant expression. Stop if we find that the expression
459 /// is not a constant expression.
460 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461
Richard Smith6d4c6582013-11-05 22:18:15 +0000462 /// Evaluate as a potential constant expression. Keep going if we hit a
463 /// construct that we can't evaluate yet (because we don't yet know the
464 /// value of something) but stop if we hit something that could never be
465 /// a constant expression.
466 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000467
Richard Smith6d4c6582013-11-05 22:18:15 +0000468 /// Fold the expression to a constant. Stop if we hit a side-effect that
469 /// we can't model.
470 EM_ConstantFold,
471
472 /// Evaluate the expression looking for integer overflow and similar
473 /// issues. Don't worry about side-effects, and try to visit all
474 /// subexpressions.
475 EM_EvaluateForOverflow,
476
477 /// Evaluate in any way we know how. Don't worry about side-effects that
478 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000479 EM_IgnoreSideEffects,
480
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression. Some expressions can be retried in the
483 /// optimizer if we don't constant fold them here, but in an unevaluated
484 /// context we try to fold them immediately since the optimizer never
485 /// gets a chance to look at it.
486 EM_ConstantExpressionUnevaluated,
487
488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression. Some expressions can be retried in the
492 /// optimizer if we don't constant fold them here, but in an unevaluated
493 /// context we try to fold them immediately since the optimizer never
494 /// gets a chance to look at it.
495 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000496 } EvalMode;
497
498 /// Are we checking whether the expression is a potential constant
499 /// expression?
500 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000501 return EvalMode == EM_PotentialConstantExpression ||
502 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000503 }
504
505 /// Are we checking an expression for overflow?
506 // FIXME: We should check for any kind of undefined or suspicious behavior
507 // in such constructs, not just overflow.
508 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509
510 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000511 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000512 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000513 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000514 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515 EvaluatingDecl((const ValueDecl *)nullptr),
516 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000518
Richard Smith7525ff62013-05-09 07:14:00 +0000519 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000521 EvaluatingDeclValue = &Value;
522 }
523
David Blaikiebbafb8a2012-03-11 07:00:24 +0000524 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000525
Richard Smith357362d2011-12-13 06:39:58 +0000526 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000527 // Don't perform any constexpr calls (other than the call we're checking)
528 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000529 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000530 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000531 if (NextCallIndex == 0) {
532 // NextCallIndex has wrapped around.
533 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534 return false;
535 }
Richard Smith357362d2011-12-13 06:39:58 +0000536 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537 return true;
538 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539 << getLangOpts().ConstexprCallDepth;
540 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000541 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000542
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackFrame *getCallFrame(unsigned CallIndex) {
544 assert(CallIndex && "no call index in getCallFrame");
545 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546 // be null in this loop.
547 CallStackFrame *Frame = CurrentCall;
548 while (Frame->Index > CallIndex)
549 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000551 }
552
Richard Smitha3d3bd22013-05-08 02:12:03 +0000553 bool nextStep(const Stmt *S) {
554 if (!StepsLeft) {
555 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556 return false;
557 }
558 --StepsLeft;
559 return true;
560 }
561
Richard Smith357362d2011-12-13 06:39:58 +0000562 private:
563 /// Add a diagnostic to the diagnostics list.
564 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567 return EvalStatus.Diag->back().second;
568 }
569
Richard Smithf6f003a2011-12-16 19:06:07 +0000570 /// Add notes containing a call stack to the current point of evaluation.
571 void addCallStack(unsigned Limit);
572
Richard Smith357362d2011-12-13 06:39:58 +0000573 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000575 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000577 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 // If we have a prior diagnostic, it will be noting that the expression
580 // isn't a constant expression. This diagnostic is more important,
581 // unless we require this evaluation to produce a constant expression.
582 //
583 // FIXME: We might want to show both diagnostics to the user in
584 // EM_ConstantFold mode.
585 if (!EvalStatus.Diag->empty()) {
586 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000587 case EM_ConstantFold:
588 case EM_IgnoreSideEffects:
589 case EM_EvaluateForOverflow:
590 if (!EvalStatus.HasSideEffects)
591 break;
592 // We've had side-effects; we want the diagnostic from them, not
593 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000594 case EM_ConstantExpression:
595 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000596 case EM_ConstantExpressionUnevaluated:
597 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 HasActiveDiagnostic = false;
599 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000600 }
601 }
602
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 unsigned CallStackNotes = CallStackDepth - 1;
604 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605 if (Limit)
606 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000607 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000608 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000609
Richard Smith357362d2011-12-13 06:39:58 +0000610 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000611 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000612 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000614 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000615 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000617 }
Richard Smith357362d2011-12-13 06:39:58 +0000618 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000619 return OptionalDiagnostic();
620 }
621
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623 = diag::note_invalid_subexpr_in_const_expr,
624 unsigned ExtraNotes = 0) {
625 if (EvalStatus.Diag)
626 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627 HasActiveDiagnostic = false;
628 return OptionalDiagnostic();
629 }
630
Richard Smith92b1ce02011-12-12 09:28:41 +0000631 /// Diagnose that the evaluation does not produce a C++11 core constant
632 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000633 ///
634 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000636 template<typename LocArg>
637 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000638 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000639 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000640 // Don't override a previous diagnostic. Don't bother collecting
641 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000642 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000643 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 return Diag(Loc, DiagId, ExtraNotes);
647 }
648
649 /// Add a note to a prior diagnostic.
650 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651 if (!HasActiveDiagnostic)
652 return OptionalDiagnostic();
653 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000654 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000655
656 /// Add a stack of notes to a prior diagnostic.
657 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658 if (HasActiveDiagnostic) {
659 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660 Diags.begin(), Diags.end());
661 }
662 }
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Should we continue evaluation after encountering a side-effect that we
665 /// couldn't model?
666 bool keepEvaluatingAfterSideEffect() {
667 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000668 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000669 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000670 case EM_EvaluateForOverflow:
671 case EM_IgnoreSideEffects:
672 return true;
673
Richard Smith6d4c6582013-11-05 22:18:15 +0000674 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 case EM_ConstantFold:
677 return false;
678 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000679 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000680 }
681
682 /// Note that we have had a side-effect, and determine whether we should
683 /// keep evaluating.
684 bool noteSideEffect() {
685 EvalStatus.HasSideEffects = true;
686 return keepEvaluatingAfterSideEffect();
687 }
688
Richard Smith253c2a32012-01-27 01:14:48 +0000689 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000691 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 if (!StepsLeft)
693 return false;
694
695 switch (EvalMode) {
696 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 return true;
700
701 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_ConstantFold:
704 case EM_IgnoreSideEffects:
705 return false;
706 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000707 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000708 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000709 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000710
711 /// Object used to treat all foldable expressions as constant expressions.
712 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000714 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 bool HadNoPriorDiags;
716 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000717
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 explicit FoldConstant(EvalInfo &Info, bool Enabled)
719 : Info(Info),
720 Enabled(Enabled),
721 HadNoPriorDiags(Info.EvalStatus.Diag &&
722 Info.EvalStatus.Diag->empty() &&
723 !Info.EvalStatus.HasSideEffects),
724 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000725 if (Enabled &&
726 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000729 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 void keepDiagnostics() { Enabled = false; }
731 ~FoldConstant() {
732 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000733 !Info.EvalStatus.HasSideEffects)
734 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000736 }
737 };
Richard Smith17100ba2012-02-16 02:46:34 +0000738
739 /// RAII object used to suppress diagnostics and side-effects from a
740 /// speculative evaluation.
741 class SpeculativeEvaluationRAII {
742 EvalInfo &Info;
743 Expr::EvalStatus Old;
744
745 public:
746 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000747 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000748 : Info(Info), Old(Info.EvalStatus) {
749 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 // If we're speculatively evaluating, we may have skipped over some
751 // evaluations and missed out a side effect.
752 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000753 }
754 ~SpeculativeEvaluationRAII() {
755 Info.EvalStatus = Old;
756 }
757 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000758
759 /// RAII object wrapping a full-expression or block scope, and handling
760 /// the ending of the lifetime of temporaries created within it.
761 template<bool IsFullExpression>
762 class ScopeRAII {
763 EvalInfo &Info;
764 unsigned OldStackSize;
765 public:
766 ScopeRAII(EvalInfo &Info)
767 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768 ~ScopeRAII() {
769 // Body moved to a static method to encourage the compiler to inline away
770 // instances of this class.
771 cleanup(Info, OldStackSize);
772 }
773 private:
774 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775 unsigned NewEnd = OldStackSize;
776 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777 I != N; ++I) {
778 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779 // Full-expression cleanup of a lifetime-extended temporary: nothing
780 // to do, just move this cleanup to the right place in the stack.
781 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782 ++NewEnd;
783 } else {
784 // End the lifetime of the object.
785 Info.CleanupStack[I].endLifetime();
786 }
787 }
788 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789 Info.CleanupStack.end());
790 }
791 };
792 typedef ScopeRAII<false> BlockScopeRAII;
793 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000794}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000795
Richard Smitha8105bc2012-01-06 16:39:00 +0000796bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797 CheckSubobjectKind CSK) {
798 if (Invalid)
799 return false;
800 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000801 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000802 << CSK;
803 setInvalid();
804 return false;
805 }
806 return true;
807}
808
809void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810 const Expr *E, uint64_t N) {
811 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000812 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000813 << static_cast<int>(N) << /*array*/ 0
814 << static_cast<unsigned>(MostDerivedArraySize);
815 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000816 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000817 << static_cast<int>(N) << /*non-array*/ 1;
818 setInvalid();
819}
820
Richard Smithf6f003a2011-12-16 19:06:07 +0000821CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000823 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000824 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000825 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000826 Info.CurrentCall = this;
827 ++Info.CallStackDepth;
828}
829
830CallStackFrame::~CallStackFrame() {
831 assert(Info.CurrentCall == this && "calls retired out of order");
832 --Info.CallStackDepth;
833 Info.CurrentCall = Caller;
834}
835
Richard Smith08d6a2c2013-07-24 07:11:57 +0000836APValue &CallStackFrame::createTemporary(const void *Key,
837 bool IsLifetimeExtended) {
838 APValue &Result = Temporaries[Key];
839 assert(Result.isUninit() && "temporary created multiple times");
840 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841 return Result;
842}
843
Richard Smith84401042013-06-03 05:03:02 +0000844static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000845
846void EvalInfo::addCallStack(unsigned Limit) {
847 // Determine which calls to skip, if any.
848 unsigned ActiveCalls = CallStackDepth - 1;
849 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850 if (Limit && Limit < ActiveCalls) {
851 SkipStart = Limit / 2 + Limit % 2;
852 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000853 }
854
Richard Smithf6f003a2011-12-16 19:06:07 +0000855 // Walk the call stack and add the diagnostics.
856 unsigned CallIdx = 0;
857 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858 Frame = Frame->Caller, ++CallIdx) {
859 // Skip this call?
860 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861 if (CallIdx == SkipStart) {
862 // Note that we're skipping calls.
863 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864 << unsigned(ActiveCalls - Limit);
865 }
866 continue;
867 }
868
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000869 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 llvm::raw_svector_ostream Out(Buffer);
871 describeCall(Frame, Out);
872 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873 }
874}
875
876namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000877 struct ComplexValue {
878 private:
879 bool IsInt;
880
881 public:
882 APSInt IntReal, IntImag;
883 APFloat FloatReal, FloatImag;
884
885 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886
887 void makeComplexFloat() { IsInt = false; }
888 bool isComplexFloat() const { return !IsInt; }
889 APFloat &getComplexFloatReal() { return FloatReal; }
890 APFloat &getComplexFloatImag() { return FloatImag; }
891
892 void makeComplexInt() { IsInt = true; }
893 bool isComplexInt() const { return IsInt; }
894 APSInt &getComplexIntReal() { return IntReal; }
895 APSInt &getComplexIntImag() { return IntImag; }
896
Richard Smith2e312c82012-03-03 22:46:17 +0000897 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000898 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000899 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000900 else
Richard Smith2e312c82012-03-03 22:46:17 +0000901 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000902 }
Richard Smith2e312c82012-03-03 22:46:17 +0000903 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000904 assert(v.isComplexFloat() || v.isComplexInt());
905 if (v.isComplexFloat()) {
906 makeComplexFloat();
907 FloatReal = v.getComplexFloatReal();
908 FloatImag = v.getComplexFloatImag();
909 } else {
910 makeComplexInt();
911 IntReal = v.getComplexIntReal();
912 IntImag = v.getComplexIntImag();
913 }
914 }
John McCall93d91dc2010-05-07 17:22:02 +0000915 };
John McCall45d55e42010-05-07 21:00:08 +0000916
917 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000918 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000919 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000920 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000921 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000922
Richard Smithce40ad62011-11-12 22:28:03 +0000923 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000925 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000926 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000927 SubobjectDesignator &getLValueDesignator() { return Designator; }
928 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000929
Richard Smith2e312c82012-03-03 22:46:17 +0000930 void moveInto(APValue &V) const {
931 if (Designator.Invalid)
932 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933 else
934 V = APValue(Base, Offset, Designator.Entries,
935 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000936 }
Richard Smith2e312c82012-03-03 22:46:17 +0000937 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000938 assert(V.isLValue());
939 Base = V.getLValueBase();
940 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000941 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000942 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000943 }
944
Richard Smithb228a862012-02-15 02:18:13 +0000945 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000946 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000947 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000948 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000949 Designator = SubobjectDesignator(getType(B));
950 }
951
952 // Check that this LValue is not based on a null pointer. If it is, produce
953 // a diagnostic and mark the designator as invalid.
954 bool checkNullPointer(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Designator.Invalid)
957 return false;
958 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 Designator.setInvalid();
962 return false;
963 }
964 return true;
965 }
966
967 // Check this LValue refers to an object. If not, set the designator to be
968 // invalid and emit a diagnostic.
969 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 // Outside C++11, do not build a designator referring to a subobject of
971 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000972 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000973 Designator.setInvalid();
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000974 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 Designator.checkSubobject(Info, E, CSK);
976 }
977
978 void addDecl(EvalInfo &Info, const Expr *E,
979 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000982 }
983 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000984 if (checkSubobject(Info, E, CSK_ArrayToPointer))
985 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000986 }
Richard Smith66c96992012-02-18 22:04:06 +0000987 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000988 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000990 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000991 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000992 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +0000993 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000994 }
John McCall45d55e42010-05-07 21:00:08 +0000995 };
Richard Smith027bf112011-11-17 22:56:20 +0000996
997 struct MemberPtr {
998 MemberPtr() {}
999 explicit MemberPtr(const ValueDecl *Decl) :
1000 DeclAndIsDerivedMember(Decl, false), Path() {}
1001
1002 /// The member or (direct or indirect) field referred to by this member
1003 /// pointer, or 0 if this is a null member pointer.
1004 const ValueDecl *getDecl() const {
1005 return DeclAndIsDerivedMember.getPointer();
1006 }
1007 /// Is this actually a member of some type derived from the relevant class?
1008 bool isDerivedMember() const {
1009 return DeclAndIsDerivedMember.getInt();
1010 }
1011 /// Get the class which the declaration actually lives in.
1012 const CXXRecordDecl *getContainingRecord() const {
1013 return cast<CXXRecordDecl>(
1014 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1015 }
1016
Richard Smith2e312c82012-03-03 22:46:17 +00001017 void moveInto(APValue &V) const {
1018 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001019 }
Richard Smith2e312c82012-03-03 22:46:17 +00001020 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001021 assert(V.isMemberPointer());
1022 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024 Path.clear();
1025 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1026 Path.insert(Path.end(), P.begin(), P.end());
1027 }
1028
1029 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030 /// whether the member is a member of some class derived from the class type
1031 /// of the member pointer.
1032 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033 /// Path - The path of base/derived classes from the member declaration's
1034 /// class (exclusive) to the class type of the member pointer (inclusive).
1035 SmallVector<const CXXRecordDecl*, 4> Path;
1036
1037 /// Perform a cast towards the class of the Decl (either up or down the
1038 /// hierarchy).
1039 bool castBack(const CXXRecordDecl *Class) {
1040 assert(!Path.empty());
1041 const CXXRecordDecl *Expected;
1042 if (Path.size() >= 2)
1043 Expected = Path[Path.size() - 2];
1044 else
1045 Expected = getContainingRecord();
1046 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048 // if B does not contain the original member and is not a base or
1049 // derived class of the class containing the original member, the result
1050 // of the cast is undefined.
1051 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052 // (D::*). We consider that to be a language defect.
1053 return false;
1054 }
1055 Path.pop_back();
1056 return true;
1057 }
1058 /// Perform a base-to-derived member pointer cast.
1059 bool castToDerived(const CXXRecordDecl *Derived) {
1060 if (!getDecl())
1061 return true;
1062 if (!isDerivedMember()) {
1063 Path.push_back(Derived);
1064 return true;
1065 }
1066 if (!castBack(Derived))
1067 return false;
1068 if (Path.empty())
1069 DeclAndIsDerivedMember.setInt(false);
1070 return true;
1071 }
1072 /// Perform a derived-to-base member pointer cast.
1073 bool castToBase(const CXXRecordDecl *Base) {
1074 if (!getDecl())
1075 return true;
1076 if (Path.empty())
1077 DeclAndIsDerivedMember.setInt(true);
1078 if (isDerivedMember()) {
1079 Path.push_back(Base);
1080 return true;
1081 }
1082 return castBack(Base);
1083 }
1084 };
Richard Smith357362d2011-12-13 06:39:58 +00001085
Richard Smith7bb00672012-02-01 01:42:44 +00001086 /// Compare two member pointers, which are assumed to be of the same type.
1087 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088 if (!LHS.getDecl() || !RHS.getDecl())
1089 return !LHS.getDecl() && !RHS.getDecl();
1090 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091 return false;
1092 return LHS.Path == RHS.Path;
1093 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001094}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001095
Richard Smith2e312c82012-03-03 22:46:17 +00001096static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001097static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001099 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001100static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001102static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103 EvalInfo &Info);
1104static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001105static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001106static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001107 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001108static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001109static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001110static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001111
1112//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001113// Misc utilities
1114//===----------------------------------------------------------------------===//
1115
Richard Smith84401042013-06-03 05:03:02 +00001116/// Produce a string describing the given constexpr call.
1117static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118 unsigned ArgIndex = 0;
1119 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120 !isa<CXXConstructorDecl>(Frame->Callee) &&
1121 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1122
1123 if (!IsMemberCall)
1124 Out << *Frame->Callee << '(';
1125
1126 if (Frame->This && IsMemberCall) {
1127 APValue Val;
1128 Frame->This->moveInto(Val);
1129 Val.printPretty(Out, Frame->Info.Ctx,
1130 Frame->This->Designator.MostDerivedType);
1131 // FIXME: Add parens around Val if needed.
1132 Out << "->" << *Frame->Callee << '(';
1133 IsMemberCall = false;
1134 }
1135
1136 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138 if (ArgIndex > (unsigned)IsMemberCall)
1139 Out << ", ";
1140
1141 const ParmVarDecl *Param = *I;
1142 const APValue &Arg = Frame->Arguments[ArgIndex];
1143 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144
1145 if (ArgIndex == 0 && IsMemberCall)
1146 Out << "->" << *Frame->Callee << '(';
1147 }
1148
1149 Out << ')';
1150}
1151
Richard Smithd9f663b2013-04-22 15:31:51 +00001152/// Evaluate an expression to see if it had side-effects, and discard its
1153/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001154/// \return \c true if the caller should keep evaluating.
1155static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001156 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001157 if (!Evaluate(Scratch, Info, E))
1158 // We don't need the value, but we might have skipped a side effect here.
1159 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001160 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001161}
1162
Richard Smith861b5b52013-05-07 23:34:45 +00001163/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164/// return its existing value.
1165static int64_t getExtValue(const APSInt &Value) {
1166 return Value.isSigned() ? Value.getSExtValue()
1167 : static_cast<int64_t>(Value.getZExtValue());
1168}
1169
Richard Smithd62306a2011-11-10 06:34:14 +00001170/// Should this call expression be treated as a string literal?
1171static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001172 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001173 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1175}
1176
Richard Smithce40ad62011-11-12 22:28:03 +00001177static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001178 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179 // constant expression of pointer type that evaluates to...
1180
1181 // ... a null pointer value, or a prvalue core constant expression of type
1182 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001183 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001184
Richard Smithce40ad62011-11-12 22:28:03 +00001185 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186 // ... the address of an object with static storage duration,
1187 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188 return VD->hasGlobalStorage();
1189 // ... the address of a function,
1190 return isa<FunctionDecl>(D);
1191 }
1192
1193 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001194 switch (E->getStmtClass()) {
1195 default:
1196 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001197 case Expr::CompoundLiteralExprClass: {
1198 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199 return CLE->isFileScope() && CLE->isLValue();
1200 }
Richard Smithe6c01442013-06-05 00:46:14 +00001201 case Expr::MaterializeTemporaryExprClass:
1202 // A materialized temporary might have been lifetime-extended to static
1203 // storage duration.
1204 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001205 // A string literal has static storage duration.
1206 case Expr::StringLiteralClass:
1207 case Expr::PredefinedExprClass:
1208 case Expr::ObjCStringLiteralClass:
1209 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001210 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001211 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001212 return true;
1213 case Expr::CallExprClass:
1214 return IsStringLiteralCall(cast<CallExpr>(E));
1215 // For GCC compatibility, &&label has static storage duration.
1216 case Expr::AddrLabelExprClass:
1217 return true;
1218 // A Block literal expression may be used as the initialization value for
1219 // Block variables at global or local static scope.
1220 case Expr::BlockExprClass:
1221 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001222 case Expr::ImplicitValueInitExprClass:
1223 // FIXME:
1224 // We can never form an lvalue with an implicit value initialization as its
1225 // base through expression evaluation, so these only appear in one case: the
1226 // implicit variable declaration we invent when checking whether a constexpr
1227 // constructor can produce a constant expression. We must assume that such
1228 // an expression might be a global lvalue.
1229 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001230 }
John McCall95007602010-05-10 23:27:23 +00001231}
1232
Richard Smithb228a862012-02-15 02:18:13 +00001233static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234 assert(Base && "no location for a null lvalue");
1235 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236 if (VD)
1237 Info.Note(VD->getLocation(), diag::note_declared_at);
1238 else
Ted Kremenek28831752012-08-23 20:46:57 +00001239 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001240 diag::note_constexpr_temporary_here);
1241}
1242
Richard Smith80815602011-11-07 05:07:52 +00001243/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001244/// value for an address or reference constant expression. Return true if we
1245/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001246static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247 QualType Type, const LValue &LVal) {
1248 bool IsReferenceType = Type->isReferenceType();
1249
Richard Smith357362d2011-12-13 06:39:58 +00001250 APValue::LValueBase Base = LVal.getLValueBase();
1251 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252
Richard Smith0dea49e2012-02-18 04:58:18 +00001253 // Check that the object is a global. Note that the fake 'this' object we
1254 // manufacture when checking potential constant expressions is conservatively
1255 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001256 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001257 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001258 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001259 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260 << IsReferenceType << !Designator.Entries.empty()
1261 << !!VD << VD;
1262 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001263 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001264 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001265 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001266 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001268 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001269 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001270 LVal.getLValueCallIndex() == 0) &&
1271 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001272
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001273 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001275 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001276 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001277 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001278
Hans Wennborg82dd8772014-06-25 22:19:48 +00001279 // A dllimport variable never acts like a constant.
1280 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001281 return false;
1282 }
1283 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284 // __declspec(dllimport) must be handled very carefully:
1285 // We must never initialize an expression with the thunk in C++.
1286 // Doing otherwise would allow the same id-expression to yield
1287 // different addresses for the same function in different translation
1288 // units. However, this means that we must dynamically initialize the
1289 // expression with the contents of the import address table at runtime.
1290 //
1291 // The C language has no notion of ODR; furthermore, it has no notion of
1292 // dynamic initialization. This means that we are permitted to
1293 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001294 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001295 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001296 }
1297 }
1298
Richard Smitha8105bc2012-01-06 16:39:00 +00001299 // Allow address constant expressions to be past-the-end pointers. This is
1300 // an extension: the standard requires them to point to an object.
1301 if (!IsReferenceType)
1302 return true;
1303
1304 // A reference constant expression must refer to an object.
1305 if (!Base) {
1306 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001307 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001308 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 }
1310
Richard Smith357362d2011-12-13 06:39:58 +00001311 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001312 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001313 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001314 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001315 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001316 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001317 }
1318
Richard Smith80815602011-11-07 05:07:52 +00001319 return true;
1320}
1321
Richard Smithfddd3842011-12-30 21:15:51 +00001322/// Check that this core constant expression is of literal type, and if not,
1323/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001324static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001325 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001326 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001327 return true;
1328
Richard Smith7525ff62013-05-09 07:14:00 +00001329 // C++1y: A constant initializer for an object o [...] may also invoke
1330 // constexpr constructors for o and its subobjects even if those objects
1331 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001332 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001333 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001334 return true;
1335
Richard Smithfddd3842011-12-30 21:15:51 +00001336 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001338 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001339 << E->getType();
1340 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001341 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001342 return false;
1343}
1344
Richard Smith0b0a0b62011-10-29 20:57:55 +00001345/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001346/// constant expression. If not, report an appropriate diagnostic. Does not
1347/// check that the expression is of literal type.
1348static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001350 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001351 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1352 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001353 return false;
1354 }
1355
Richard Smith77be48a2014-07-31 06:31:19 +00001356 // We allow _Atomic(T) to be initialized from anything that T can be
1357 // initialized from.
1358 if (const AtomicType *AT = Type->getAs<AtomicType>())
1359 Type = AT->getValueType();
1360
Richard Smithb228a862012-02-15 02:18:13 +00001361 // Core issue 1454: For a literal constant expression of array or class type,
1362 // each subobject of its value shall have been initialized by a constant
1363 // expression.
1364 if (Value.isArray()) {
1365 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368 Value.getArrayInitializedElt(I)))
1369 return false;
1370 }
1371 if (!Value.hasArrayFiller())
1372 return true;
1373 return CheckConstantExpression(Info, DiagLoc, EltTy,
1374 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001375 }
Richard Smithb228a862012-02-15 02:18:13 +00001376 if (Value.isUnion() && Value.getUnionField()) {
1377 return CheckConstantExpression(Info, DiagLoc,
1378 Value.getUnionField()->getType(),
1379 Value.getUnionValue());
1380 }
1381 if (Value.isStruct()) {
1382 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384 unsigned BaseIndex = 0;
1385 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388 Value.getStructBase(BaseIndex)))
1389 return false;
1390 }
1391 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001392 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001393 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001395 return false;
1396 }
1397 }
1398
1399 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001400 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001401 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001402 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1403 }
1404
1405 // Everything else is fine.
1406 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001407}
1408
Benjamin Kramer8407df72015-03-09 16:47:52 +00001409static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001410 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001411}
1412
1413static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001414 if (Value.CallIndex)
1415 return false;
1416 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001418}
1419
Richard Smithcecf1842011-11-01 21:06:14 +00001420static bool IsWeakLValue(const LValue &Value) {
1421 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001422 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001423}
1424
David Majnemerb5116032014-12-09 23:32:34 +00001425static bool isZeroSized(const LValue &Value) {
1426 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001427 if (Decl && isa<VarDecl>(Decl)) {
1428 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001429 if (Ty->isArrayType())
1430 return Ty->isIncompleteType() ||
1431 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001432 }
1433 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001434}
1435
Richard Smith2e312c82012-03-03 22:46:17 +00001436static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001437 // A null base expression indicates a null pointer. These are always
1438 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001439 if (!Value.getLValueBase()) {
1440 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001441 return true;
1442 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001443
Richard Smith027bf112011-11-17 22:56:20 +00001444 // We have a non-null base. These are generally known to be true, but if it's
1445 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001446 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001447 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001448 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001449}
1450
Richard Smith2e312c82012-03-03 22:46:17 +00001451static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001452 switch (Val.getKind()) {
1453 case APValue::Uninitialized:
1454 return false;
1455 case APValue::Int:
1456 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001457 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001458 case APValue::Float:
1459 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001460 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001461 case APValue::ComplexInt:
1462 Result = Val.getComplexIntReal().getBoolValue() ||
1463 Val.getComplexIntImag().getBoolValue();
1464 return true;
1465 case APValue::ComplexFloat:
1466 Result = !Val.getComplexFloatReal().isZero() ||
1467 !Val.getComplexFloatImag().isZero();
1468 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001469 case APValue::LValue:
1470 return EvalPointerValueAsBool(Val, Result);
1471 case APValue::MemberPointer:
1472 Result = Val.getMemberPointerDecl();
1473 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001474 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001475 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001476 case APValue::Struct:
1477 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001478 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001479 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001480 }
1481
Richard Smith11562c52011-10-28 17:51:58 +00001482 llvm_unreachable("unknown APValue kind");
1483}
1484
1485static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1486 EvalInfo &Info) {
1487 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001488 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001489 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001490 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001491 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001492}
1493
Richard Smith357362d2011-12-13 06:39:58 +00001494template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001495static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001496 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001497 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001498 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001499}
1500
1501static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1502 QualType SrcType, const APFloat &Value,
1503 QualType DestType, APSInt &Result) {
1504 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001505 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001506 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001507
Richard Smith357362d2011-12-13 06:39:58 +00001508 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001509 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001510 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1511 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001512 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001513 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001514}
1515
Richard Smith357362d2011-12-13 06:39:58 +00001516static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1517 QualType SrcType, QualType DestType,
1518 APFloat &Result) {
1519 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001520 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001521 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1522 APFloat::rmNearestTiesToEven, &ignored)
1523 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001524 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001525 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001526}
1527
Richard Smith911e1422012-01-30 22:27:01 +00001528static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1529 QualType DestType, QualType SrcType,
1530 APSInt &Value) {
1531 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001532 APSInt Result = Value;
1533 // Figure out if this is a truncate, extend or noop cast.
1534 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001535 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001536 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001537 return Result;
1538}
1539
Richard Smith357362d2011-12-13 06:39:58 +00001540static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1541 QualType SrcType, const APSInt &Value,
1542 QualType DestType, APFloat &Result) {
1543 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1544 if (Result.convertFromAPInt(Value, Value.isSigned(),
1545 APFloat::rmNearestTiesToEven)
1546 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001547 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001548 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001549}
1550
Richard Smith49ca8aa2013-08-06 07:09:20 +00001551static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1552 APValue &Value, const FieldDecl *FD) {
1553 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1554
1555 if (!Value.isInt()) {
1556 // Trying to store a pointer-cast-to-integer into a bitfield.
1557 // FIXME: In this case, we should provide the diagnostic for casting
1558 // a pointer to an integer.
1559 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1560 Info.Diag(E);
1561 return false;
1562 }
1563
1564 APSInt &Int = Value.getInt();
1565 unsigned OldBitWidth = Int.getBitWidth();
1566 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1567 if (NewBitWidth < OldBitWidth)
1568 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1569 return true;
1570}
1571
Eli Friedman803acb32011-12-22 03:51:45 +00001572static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1573 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001574 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001575 if (!Evaluate(SVal, Info, E))
1576 return false;
1577 if (SVal.isInt()) {
1578 Res = SVal.getInt();
1579 return true;
1580 }
1581 if (SVal.isFloat()) {
1582 Res = SVal.getFloat().bitcastToAPInt();
1583 return true;
1584 }
1585 if (SVal.isVector()) {
1586 QualType VecTy = E->getType();
1587 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1588 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1589 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1590 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1591 Res = llvm::APInt::getNullValue(VecSize);
1592 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1593 APValue &Elt = SVal.getVectorElt(i);
1594 llvm::APInt EltAsInt;
1595 if (Elt.isInt()) {
1596 EltAsInt = Elt.getInt();
1597 } else if (Elt.isFloat()) {
1598 EltAsInt = Elt.getFloat().bitcastToAPInt();
1599 } else {
1600 // Don't try to handle vectors of anything other than int or float
1601 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001602 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001603 return false;
1604 }
1605 unsigned BaseEltSize = EltAsInt.getBitWidth();
1606 if (BigEndian)
1607 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1608 else
1609 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1610 }
1611 return true;
1612 }
1613 // Give up if the input isn't an int, float, or vector. For example, we
1614 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001615 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001616 return false;
1617}
1618
Richard Smith43e77732013-05-07 04:50:00 +00001619/// Perform the given integer operation, which is known to need at most BitWidth
1620/// bits, and check for overflow in the original type (if that type was not an
1621/// unsigned type).
1622template<typename Operation>
1623static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1624 const APSInt &LHS, const APSInt &RHS,
1625 unsigned BitWidth, Operation Op) {
1626 if (LHS.isUnsigned())
1627 return Op(LHS, RHS);
1628
1629 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1630 APSInt Result = Value.trunc(LHS.getBitWidth());
1631 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001632 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001633 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1634 diag::warn_integer_constant_overflow)
1635 << Result.toString(10) << E->getType();
1636 else
1637 HandleOverflow(Info, E, Value, E->getType());
1638 }
1639 return Result;
1640}
1641
1642/// Perform the given binary integer operation.
1643static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1644 BinaryOperatorKind Opcode, APSInt RHS,
1645 APSInt &Result) {
1646 switch (Opcode) {
1647 default:
1648 Info.Diag(E);
1649 return false;
1650 case BO_Mul:
1651 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1652 std::multiplies<APSInt>());
1653 return true;
1654 case BO_Add:
1655 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1656 std::plus<APSInt>());
1657 return true;
1658 case BO_Sub:
1659 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1660 std::minus<APSInt>());
1661 return true;
1662 case BO_And: Result = LHS & RHS; return true;
1663 case BO_Xor: Result = LHS ^ RHS; return true;
1664 case BO_Or: Result = LHS | RHS; return true;
1665 case BO_Div:
1666 case BO_Rem:
1667 if (RHS == 0) {
1668 Info.Diag(E, diag::note_expr_divide_by_zero);
1669 return false;
1670 }
1671 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1672 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1673 LHS.isSigned() && LHS.isMinSignedValue())
1674 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1675 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1676 return true;
1677 case BO_Shl: {
1678 if (Info.getLangOpts().OpenCL)
1679 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1680 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1681 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1682 RHS.isUnsigned());
1683 else if (RHS.isSigned() && RHS.isNegative()) {
1684 // During constant-folding, a negative shift is an opposite shift. Such
1685 // a shift is not a constant expression.
1686 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1687 RHS = -RHS;
1688 goto shift_right;
1689 }
1690 shift_left:
1691 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1692 // the shifted type.
1693 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1694 if (SA != RHS) {
1695 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1696 << RHS << E->getType() << LHS.getBitWidth();
1697 } else if (LHS.isSigned()) {
1698 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1699 // operand, and must not overflow the corresponding unsigned type.
1700 if (LHS.isNegative())
1701 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1702 else if (LHS.countLeadingZeros() < SA)
1703 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1704 }
1705 Result = LHS << SA;
1706 return true;
1707 }
1708 case BO_Shr: {
1709 if (Info.getLangOpts().OpenCL)
1710 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1711 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1712 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1713 RHS.isUnsigned());
1714 else if (RHS.isSigned() && RHS.isNegative()) {
1715 // During constant-folding, a negative shift is an opposite shift. Such a
1716 // shift is not a constant expression.
1717 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1718 RHS = -RHS;
1719 goto shift_left;
1720 }
1721 shift_right:
1722 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1723 // shifted type.
1724 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1725 if (SA != RHS)
1726 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1727 << RHS << E->getType() << LHS.getBitWidth();
1728 Result = LHS >> SA;
1729 return true;
1730 }
1731
1732 case BO_LT: Result = LHS < RHS; return true;
1733 case BO_GT: Result = LHS > RHS; return true;
1734 case BO_LE: Result = LHS <= RHS; return true;
1735 case BO_GE: Result = LHS >= RHS; return true;
1736 case BO_EQ: Result = LHS == RHS; return true;
1737 case BO_NE: Result = LHS != RHS; return true;
1738 }
1739}
1740
Richard Smith861b5b52013-05-07 23:34:45 +00001741/// Perform the given binary floating-point operation, in-place, on LHS.
1742static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1743 APFloat &LHS, BinaryOperatorKind Opcode,
1744 const APFloat &RHS) {
1745 switch (Opcode) {
1746 default:
1747 Info.Diag(E);
1748 return false;
1749 case BO_Mul:
1750 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1751 break;
1752 case BO_Add:
1753 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1754 break;
1755 case BO_Sub:
1756 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1757 break;
1758 case BO_Div:
1759 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1760 break;
1761 }
1762
1763 if (LHS.isInfinity() || LHS.isNaN())
1764 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1765 return true;
1766}
1767
Richard Smitha8105bc2012-01-06 16:39:00 +00001768/// Cast an lvalue referring to a base subobject to a derived class, by
1769/// truncating the lvalue's path to the given length.
1770static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1771 const RecordDecl *TruncatedType,
1772 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001773 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001774
1775 // Check we actually point to a derived class object.
1776 if (TruncatedElements == D.Entries.size())
1777 return true;
1778 assert(TruncatedElements >= D.MostDerivedPathLength &&
1779 "not casting to a derived class");
1780 if (!Result.checkSubobject(Info, E, CSK_Derived))
1781 return false;
1782
1783 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001784 const RecordDecl *RD = TruncatedType;
1785 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001786 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001787 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1788 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001789 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001790 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001791 else
Richard Smithd62306a2011-11-10 06:34:14 +00001792 Result.Offset -= Layout.getBaseClassOffset(Base);
1793 RD = Base;
1794 }
Richard Smith027bf112011-11-17 22:56:20 +00001795 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001796 return true;
1797}
1798
John McCalld7bca762012-05-01 00:38:49 +00001799static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001800 const CXXRecordDecl *Derived,
1801 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001802 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001803 if (!RL) {
1804 if (Derived->isInvalidDecl()) return false;
1805 RL = &Info.Ctx.getASTRecordLayout(Derived);
1806 }
1807
Richard Smithd62306a2011-11-10 06:34:14 +00001808 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001809 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001810 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001811}
1812
Richard Smitha8105bc2012-01-06 16:39:00 +00001813static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001814 const CXXRecordDecl *DerivedDecl,
1815 const CXXBaseSpecifier *Base) {
1816 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1817
John McCalld7bca762012-05-01 00:38:49 +00001818 if (!Base->isVirtual())
1819 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001820
Richard Smitha8105bc2012-01-06 16:39:00 +00001821 SubobjectDesignator &D = Obj.Designator;
1822 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001823 return false;
1824
Richard Smitha8105bc2012-01-06 16:39:00 +00001825 // Extract most-derived object and corresponding type.
1826 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1827 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1828 return false;
1829
1830 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001831 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1833 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001834 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001835 return true;
1836}
1837
Richard Smith84401042013-06-03 05:03:02 +00001838static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1839 QualType Type, LValue &Result) {
1840 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1841 PathE = E->path_end();
1842 PathI != PathE; ++PathI) {
1843 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1844 *PathI))
1845 return false;
1846 Type = (*PathI)->getType();
1847 }
1848 return true;
1849}
1850
Richard Smithd62306a2011-11-10 06:34:14 +00001851/// Update LVal to refer to the given field, which must be a member of the type
1852/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001853static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001854 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001855 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001856 if (!RL) {
1857 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001858 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001859 }
Richard Smithd62306a2011-11-10 06:34:14 +00001860
1861 unsigned I = FD->getFieldIndex();
1862 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001863 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001864 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001865}
1866
Richard Smith1b78b3d2012-01-25 22:15:11 +00001867/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001868static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001869 LValue &LVal,
1870 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001871 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001872 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001873 return false;
1874 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001875}
1876
Richard Smithd62306a2011-11-10 06:34:14 +00001877/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001878static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1879 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001880 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1881 // extension.
1882 if (Type->isVoidType() || Type->isFunctionType()) {
1883 Size = CharUnits::One();
1884 return true;
1885 }
1886
1887 if (!Type->isConstantSizeType()) {
1888 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001889 // FIXME: Better diagnostic.
1890 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001891 return false;
1892 }
1893
1894 Size = Info.Ctx.getTypeSizeInChars(Type);
1895 return true;
1896}
1897
1898/// Update a pointer value to model pointer arithmetic.
1899/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001900/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001901/// \param LVal - The pointer value to be updated.
1902/// \param EltTy - The pointee type represented by LVal.
1903/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001904static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1905 LValue &LVal, QualType EltTy,
1906 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001907 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001908 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001909 return false;
1910
1911 // Compute the new offset in the appropriate width.
1912 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001913 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001914 return true;
1915}
1916
Richard Smith66c96992012-02-18 22:04:06 +00001917/// Update an lvalue to refer to a component of a complex number.
1918/// \param Info - Information about the ongoing evaluation.
1919/// \param LVal - The lvalue to be updated.
1920/// \param EltTy - The complex number's component type.
1921/// \param Imag - False for the real component, true for the imaginary.
1922static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1923 LValue &LVal, QualType EltTy,
1924 bool Imag) {
1925 if (Imag) {
1926 CharUnits SizeOfComponent;
1927 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1928 return false;
1929 LVal.Offset += SizeOfComponent;
1930 }
1931 LVal.addComplex(Info, E, EltTy, Imag);
1932 return true;
1933}
1934
Richard Smith27908702011-10-24 17:54:18 +00001935/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001936///
1937/// \param Info Information about the ongoing evaluation.
1938/// \param E An expression to be used when printing diagnostics.
1939/// \param VD The variable whose initializer should be obtained.
1940/// \param Frame The frame in which the variable was created. Must be null
1941/// if this variable is not local to the evaluation.
1942/// \param Result Filled in with a pointer to the value of the variable.
1943static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1944 const VarDecl *VD, CallStackFrame *Frame,
1945 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001946 // If this is a parameter to an active constexpr function call, perform
1947 // argument substitution.
1948 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001949 // Assume arguments of a potential constant expression are unknown
1950 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001951 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001952 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001954 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001955 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001956 }
Richard Smith3229b742013-05-05 21:17:10 +00001957 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001958 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001959 }
Richard Smith27908702011-10-24 17:54:18 +00001960
Richard Smithd9f663b2013-04-22 15:31:51 +00001961 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001962 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001963 Result = Frame->getTemporary(VD);
1964 assert(Result && "missing value for local variable");
1965 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001966 }
1967
Richard Smithd0b4dd62011-12-19 06:19:21 +00001968 // Dig out the initializer, and use the declaration which it's attached to.
1969 const Expr *Init = VD->getAnyInitializer(VD);
1970 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001971 // If we're checking a potential constant expression, the variable could be
1972 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001973 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001974 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001975 return false;
1976 }
1977
Richard Smithd62306a2011-11-10 06:34:14 +00001978 // If we're currently evaluating the initializer of this declaration, use that
1979 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001980 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001981 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001982 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001983 }
1984
Richard Smithcecf1842011-11-01 21:06:14 +00001985 // Never evaluate the initializer of a weak variable. We can't be sure that
1986 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001987 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001988 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001989 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001990 }
Richard Smithcecf1842011-11-01 21:06:14 +00001991
Richard Smithd0b4dd62011-12-19 06:19:21 +00001992 // Check that we can fold the initializer. In C++, we will have already done
1993 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001994 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001995 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001996 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001997 Notes.size() + 1) << VD;
1998 Info.Note(VD->getLocation(), diag::note_declared_at);
1999 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002000 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002001 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002002 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002003 Notes.size() + 1) << VD;
2004 Info.Note(VD->getLocation(), diag::note_declared_at);
2005 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002006 }
Richard Smith27908702011-10-24 17:54:18 +00002007
Richard Smith3229b742013-05-05 21:17:10 +00002008 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002009 return true;
Richard Smith27908702011-10-24 17:54:18 +00002010}
2011
Richard Smith11562c52011-10-28 17:51:58 +00002012static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002013 Qualifiers Quals = T.getQualifiers();
2014 return Quals.hasConst() && !Quals.hasVolatile();
2015}
2016
Richard Smithe97cbd72011-11-11 04:05:33 +00002017/// Get the base index of the given base class within an APValue representing
2018/// the given derived class.
2019static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2020 const CXXRecordDecl *Base) {
2021 Base = Base->getCanonicalDecl();
2022 unsigned Index = 0;
2023 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2024 E = Derived->bases_end(); I != E; ++I, ++Index) {
2025 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2026 return Index;
2027 }
2028
2029 llvm_unreachable("base class missing from derived class's bases list");
2030}
2031
Richard Smith3da88fa2013-04-26 14:36:30 +00002032/// Extract the value of a character from a string literal.
2033static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2034 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002035 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2036 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2037 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002038 const StringLiteral *S = cast<StringLiteral>(Lit);
2039 const ConstantArrayType *CAT =
2040 Info.Ctx.getAsConstantArrayType(S->getType());
2041 assert(CAT && "string literal isn't an array");
2042 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002043 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002044
2045 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002046 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002047 if (Index < S->getLength())
2048 Value = S->getCodeUnit(Index);
2049 return Value;
2050}
2051
Richard Smith3da88fa2013-04-26 14:36:30 +00002052// Expand a string literal into an array of characters.
2053static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2054 APValue &Result) {
2055 const StringLiteral *S = cast<StringLiteral>(Lit);
2056 const ConstantArrayType *CAT =
2057 Info.Ctx.getAsConstantArrayType(S->getType());
2058 assert(CAT && "string literal isn't an array");
2059 QualType CharType = CAT->getElementType();
2060 assert(CharType->isIntegerType() && "unexpected character type");
2061
2062 unsigned Elts = CAT->getSize().getZExtValue();
2063 Result = APValue(APValue::UninitArray(),
2064 std::min(S->getLength(), Elts), Elts);
2065 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2066 CharType->isUnsignedIntegerType());
2067 if (Result.hasArrayFiller())
2068 Result.getArrayFiller() = APValue(Value);
2069 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2070 Value = S->getCodeUnit(I);
2071 Result.getArrayInitializedElt(I) = APValue(Value);
2072 }
2073}
2074
2075// Expand an array so that it has more than Index filled elements.
2076static void expandArray(APValue &Array, unsigned Index) {
2077 unsigned Size = Array.getArraySize();
2078 assert(Index < Size);
2079
2080 // Always at least double the number of elements for which we store a value.
2081 unsigned OldElts = Array.getArrayInitializedElts();
2082 unsigned NewElts = std::max(Index+1, OldElts * 2);
2083 NewElts = std::min(Size, std::max(NewElts, 8u));
2084
2085 // Copy the data across.
2086 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2087 for (unsigned I = 0; I != OldElts; ++I)
2088 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2089 for (unsigned I = OldElts; I != NewElts; ++I)
2090 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2091 if (NewValue.hasArrayFiller())
2092 NewValue.getArrayFiller() = Array.getArrayFiller();
2093 Array.swap(NewValue);
2094}
2095
Richard Smithb01fe402014-09-16 01:24:02 +00002096/// Determine whether a type would actually be read by an lvalue-to-rvalue
2097/// conversion. If it's of class type, we may assume that the copy operation
2098/// is trivial. Note that this is never true for a union type with fields
2099/// (because the copy always "reads" the active member) and always true for
2100/// a non-class type.
2101static bool isReadByLvalueToRvalueConversion(QualType T) {
2102 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2103 if (!RD || (RD->isUnion() && !RD->field_empty()))
2104 return true;
2105 if (RD->isEmpty())
2106 return false;
2107
2108 for (auto *Field : RD->fields())
2109 if (isReadByLvalueToRvalueConversion(Field->getType()))
2110 return true;
2111
2112 for (auto &BaseSpec : RD->bases())
2113 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2114 return true;
2115
2116 return false;
2117}
2118
2119/// Diagnose an attempt to read from any unreadable field within the specified
2120/// type, which might be a class type.
2121static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2122 QualType T) {
2123 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2124 if (!RD)
2125 return false;
2126
2127 if (!RD->hasMutableFields())
2128 return false;
2129
2130 for (auto *Field : RD->fields()) {
2131 // If we're actually going to read this field in some way, then it can't
2132 // be mutable. If we're in a union, then assigning to a mutable field
2133 // (even an empty one) can change the active member, so that's not OK.
2134 // FIXME: Add core issue number for the union case.
2135 if (Field->isMutable() &&
2136 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2137 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2138 Info.Note(Field->getLocation(), diag::note_declared_at);
2139 return true;
2140 }
2141
2142 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2143 return true;
2144 }
2145
2146 for (auto &BaseSpec : RD->bases())
2147 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2148 return true;
2149
2150 // All mutable fields were empty, and thus not actually read.
2151 return false;
2152}
2153
Richard Smith861b5b52013-05-07 23:34:45 +00002154/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002155enum AccessKinds {
2156 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002157 AK_Assign,
2158 AK_Increment,
2159 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002160};
2161
Richard Smith3229b742013-05-05 21:17:10 +00002162/// A handle to a complete object (an object that is not a subobject of
2163/// another object).
2164struct CompleteObject {
2165 /// The value of the complete object.
2166 APValue *Value;
2167 /// The type of the complete object.
2168 QualType Type;
2169
Craig Topper36250ad2014-05-12 05:36:57 +00002170 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002171 CompleteObject(APValue *Value, QualType Type)
2172 : Value(Value), Type(Type) {
2173 assert(Value && "missing value for complete object");
2174 }
2175
Aaron Ballman67347662015-02-15 22:00:28 +00002176 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002177};
2178
Richard Smith3da88fa2013-04-26 14:36:30 +00002179/// Find the designated sub-object of an rvalue.
2180template<typename SubobjectHandler>
2181typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002182findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002183 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002184 if (Sub.Invalid)
2185 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002186 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002187 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002188 if (Info.getLangOpts().CPlusPlus11)
2189 Info.Diag(E, diag::note_constexpr_access_past_end)
2190 << handler.AccessKind;
2191 else
2192 Info.Diag(E);
2193 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002194 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002195
Richard Smith3229b742013-05-05 21:17:10 +00002196 APValue *O = Obj.Value;
2197 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002198 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002199
Richard Smithd62306a2011-11-10 06:34:14 +00002200 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002201 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2202 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002203 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002204 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2205 return handler.failed();
2206 }
2207
Richard Smith49ca8aa2013-08-06 07:09:20 +00002208 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002209 // If we are reading an object of class type, there may still be more
2210 // things we need to check: if there are any mutable subobjects, we
2211 // cannot perform this read. (This only happens when performing a trivial
2212 // copy or assignment.)
2213 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2214 diagnoseUnreadableFields(Info, E, ObjType))
2215 return handler.failed();
2216
Richard Smith49ca8aa2013-08-06 07:09:20 +00002217 if (!handler.found(*O, ObjType))
2218 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002219
Richard Smith49ca8aa2013-08-06 07:09:20 +00002220 // If we modified a bit-field, truncate it to the right width.
2221 if (handler.AccessKind != AK_Read &&
2222 LastField && LastField->isBitField() &&
2223 !truncateBitfieldValue(Info, E, *O, LastField))
2224 return false;
2225
2226 return true;
2227 }
2228
Craig Topper36250ad2014-05-12 05:36:57 +00002229 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002230 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002231 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002232 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002233 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002234 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002235 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002236 // Note, it should not be possible to form a pointer with a valid
2237 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002238 if (Info.getLangOpts().CPlusPlus11)
2239 Info.Diag(E, diag::note_constexpr_access_past_end)
2240 << handler.AccessKind;
2241 else
2242 Info.Diag(E);
2243 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002244 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002245
2246 ObjType = CAT->getElementType();
2247
Richard Smith14a94132012-02-17 03:35:37 +00002248 // An array object is represented as either an Array APValue or as an
2249 // LValue which refers to a string literal.
2250 if (O->isLValue()) {
2251 assert(I == N - 1 && "extracting subobject of character?");
2252 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002253 if (handler.AccessKind != AK_Read)
2254 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2255 *O);
2256 else
2257 return handler.foundString(*O, ObjType, Index);
2258 }
2259
2260 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002261 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002262 else if (handler.AccessKind != AK_Read) {
2263 expandArray(*O, Index);
2264 O = &O->getArrayInitializedElt(Index);
2265 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002266 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002267 } else if (ObjType->isAnyComplexType()) {
2268 // Next subobject is a complex number.
2269 uint64_t Index = Sub.Entries[I].ArrayIndex;
2270 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002271 if (Info.getLangOpts().CPlusPlus11)
2272 Info.Diag(E, diag::note_constexpr_access_past_end)
2273 << handler.AccessKind;
2274 else
2275 Info.Diag(E);
2276 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002277 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002278
2279 bool WasConstQualified = ObjType.isConstQualified();
2280 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2281 if (WasConstQualified)
2282 ObjType.addConst();
2283
Richard Smith66c96992012-02-18 22:04:06 +00002284 assert(I == N - 1 && "extracting subobject of scalar?");
2285 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002286 return handler.found(Index ? O->getComplexIntImag()
2287 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002288 } else {
2289 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002290 return handler.found(Index ? O->getComplexFloatImag()
2291 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002292 }
Richard Smithd62306a2011-11-10 06:34:14 +00002293 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002294 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002295 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002296 << Field;
2297 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002298 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002299 }
2300
Richard Smithd62306a2011-11-10 06:34:14 +00002301 // Next subobject is a class, struct or union field.
2302 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2303 if (RD->isUnion()) {
2304 const FieldDecl *UnionField = O->getUnionField();
2305 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002306 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002307 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2308 << handler.AccessKind << Field << !UnionField << UnionField;
2309 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002310 }
Richard Smithd62306a2011-11-10 06:34:14 +00002311 O = &O->getUnionValue();
2312 } else
2313 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002314
2315 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002316 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002317 if (WasConstQualified && !Field->isMutable())
2318 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002319
2320 if (ObjType.isVolatileQualified()) {
2321 if (Info.getLangOpts().CPlusPlus) {
2322 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002323 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2324 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002325 Info.Note(Field->getLocation(), diag::note_declared_at);
2326 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002327 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002328 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002329 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002330 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002331
2332 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002333 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002334 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002335 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2336 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2337 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002338
2339 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002340 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002341 if (WasConstQualified)
2342 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002343 }
2344 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002345}
2346
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002347namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002348struct ExtractSubobjectHandler {
2349 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002350 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002351
2352 static const AccessKinds AccessKind = AK_Read;
2353
2354 typedef bool result_type;
2355 bool failed() { return false; }
2356 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002357 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 return true;
2359 }
2360 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002361 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002362 return true;
2363 }
2364 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002365 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002366 return true;
2367 }
2368 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002369 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002370 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2371 return true;
2372 }
2373};
Richard Smith3229b742013-05-05 21:17:10 +00002374} // end anonymous namespace
2375
Richard Smith3da88fa2013-04-26 14:36:30 +00002376const AccessKinds ExtractSubobjectHandler::AccessKind;
2377
2378/// Extract the designated sub-object of an rvalue.
2379static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002380 const CompleteObject &Obj,
2381 const SubobjectDesignator &Sub,
2382 APValue &Result) {
2383 ExtractSubobjectHandler Handler = { Info, Result };
2384 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002385}
2386
Richard Smith3229b742013-05-05 21:17:10 +00002387namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002388struct ModifySubobjectHandler {
2389 EvalInfo &Info;
2390 APValue &NewVal;
2391 const Expr *E;
2392
2393 typedef bool result_type;
2394 static const AccessKinds AccessKind = AK_Assign;
2395
2396 bool checkConst(QualType QT) {
2397 // Assigning to a const object has undefined behavior.
2398 if (QT.isConstQualified()) {
2399 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2400 return false;
2401 }
2402 return true;
2403 }
2404
2405 bool failed() { return false; }
2406 bool found(APValue &Subobj, QualType SubobjType) {
2407 if (!checkConst(SubobjType))
2408 return false;
2409 // We've been given ownership of NewVal, so just swap it in.
2410 Subobj.swap(NewVal);
2411 return true;
2412 }
2413 bool found(APSInt &Value, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2415 return false;
2416 if (!NewVal.isInt()) {
2417 // Maybe trying to write a cast pointer value into a complex?
2418 Info.Diag(E);
2419 return false;
2420 }
2421 Value = NewVal.getInt();
2422 return true;
2423 }
2424 bool found(APFloat &Value, QualType SubobjType) {
2425 if (!checkConst(SubobjType))
2426 return false;
2427 Value = NewVal.getFloat();
2428 return true;
2429 }
2430 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2431 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2432 }
2433};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002434} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002435
Richard Smith3229b742013-05-05 21:17:10 +00002436const AccessKinds ModifySubobjectHandler::AccessKind;
2437
Richard Smith3da88fa2013-04-26 14:36:30 +00002438/// Update the designated sub-object of an rvalue to the given value.
2439static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002440 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002441 const SubobjectDesignator &Sub,
2442 APValue &NewVal) {
2443 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002444 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002445}
2446
Richard Smith84f6dcf2012-02-02 01:16:57 +00002447/// Find the position where two subobject designators diverge, or equivalently
2448/// the length of the common initial subsequence.
2449static unsigned FindDesignatorMismatch(QualType ObjType,
2450 const SubobjectDesignator &A,
2451 const SubobjectDesignator &B,
2452 bool &WasArrayIndex) {
2453 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2454 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002455 if (!ObjType.isNull() &&
2456 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002457 // Next subobject is an array element.
2458 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2459 WasArrayIndex = true;
2460 return I;
2461 }
Richard Smith66c96992012-02-18 22:04:06 +00002462 if (ObjType->isAnyComplexType())
2463 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2464 else
2465 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002466 } else {
2467 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2468 WasArrayIndex = false;
2469 return I;
2470 }
2471 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2472 // Next subobject is a field.
2473 ObjType = FD->getType();
2474 else
2475 // Next subobject is a base class.
2476 ObjType = QualType();
2477 }
2478 }
2479 WasArrayIndex = false;
2480 return I;
2481}
2482
2483/// Determine whether the given subobject designators refer to elements of the
2484/// same array object.
2485static bool AreElementsOfSameArray(QualType ObjType,
2486 const SubobjectDesignator &A,
2487 const SubobjectDesignator &B) {
2488 if (A.Entries.size() != B.Entries.size())
2489 return false;
2490
2491 bool IsArray = A.MostDerivedArraySize != 0;
2492 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2493 // A is a subobject of the array element.
2494 return false;
2495
2496 // If A (and B) designates an array element, the last entry will be the array
2497 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2498 // of length 1' case, and the entire path must match.
2499 bool WasArrayIndex;
2500 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2501 return CommonLength >= A.Entries.size() - IsArray;
2502}
2503
Richard Smith3229b742013-05-05 21:17:10 +00002504/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002505static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2506 AccessKinds AK, const LValue &LVal,
2507 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002508 if (!LVal.Base) {
2509 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2510 return CompleteObject();
2511 }
2512
Craig Topper36250ad2014-05-12 05:36:57 +00002513 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002514 if (LVal.CallIndex) {
2515 Frame = Info.getCallFrame(LVal.CallIndex);
2516 if (!Frame) {
2517 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2518 << AK << LVal.Base.is<const ValueDecl*>();
2519 NoteLValueLocation(Info, LVal.Base);
2520 return CompleteObject();
2521 }
Richard Smith3229b742013-05-05 21:17:10 +00002522 }
2523
2524 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2525 // is not a constant expression (even if the object is non-volatile). We also
2526 // apply this rule to C++98, in order to conform to the expected 'volatile'
2527 // semantics.
2528 if (LValType.isVolatileQualified()) {
2529 if (Info.getLangOpts().CPlusPlus)
2530 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2531 << AK << LValType;
2532 else
2533 Info.Diag(E);
2534 return CompleteObject();
2535 }
2536
2537 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002538 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002539 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002540
2541 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2542 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2543 // In C++11, constexpr, non-volatile variables initialized with constant
2544 // expressions are constant expressions too. Inside constexpr functions,
2545 // parameters are constant expressions even if they're non-const.
2546 // In C++1y, objects local to a constant expression (those with a Frame) are
2547 // both readable and writable inside constant expressions.
2548 // In C, such things can also be folded, although they are not ICEs.
2549 const VarDecl *VD = dyn_cast<VarDecl>(D);
2550 if (VD) {
2551 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2552 VD = VDef;
2553 }
2554 if (!VD || VD->isInvalidDecl()) {
2555 Info.Diag(E);
2556 return CompleteObject();
2557 }
2558
2559 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002560 if (BaseType.isVolatileQualified()) {
2561 if (Info.getLangOpts().CPlusPlus) {
2562 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563 << AK << 1 << VD;
2564 Info.Note(VD->getLocation(), diag::note_declared_at);
2565 } else {
2566 Info.Diag(E);
2567 }
2568 return CompleteObject();
2569 }
2570
2571 // Unless we're looking at a local variable or argument in a constexpr call,
2572 // the variable we're reading must be const.
2573 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002574 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002575 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2576 // OK, we can read and modify an object if we're in the process of
2577 // evaluating its initializer, because its lifetime began in this
2578 // evaluation.
2579 } else if (AK != AK_Read) {
2580 // All the remaining cases only permit reading.
2581 Info.Diag(E, diag::note_constexpr_modify_global);
2582 return CompleteObject();
2583 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002584 // OK, we can read this variable.
2585 } else if (BaseType->isIntegralOrEnumerationType()) {
2586 if (!BaseType.isConstQualified()) {
2587 if (Info.getLangOpts().CPlusPlus) {
2588 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2589 Info.Note(VD->getLocation(), diag::note_declared_at);
2590 } else {
2591 Info.Diag(E);
2592 }
2593 return CompleteObject();
2594 }
2595 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2596 // We support folding of const floating-point types, in order to make
2597 // static const data members of such types (supported as an extension)
2598 // more useful.
2599 if (Info.getLangOpts().CPlusPlus11) {
2600 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2601 Info.Note(VD->getLocation(), diag::note_declared_at);
2602 } else {
2603 Info.CCEDiag(E);
2604 }
2605 } else {
2606 // FIXME: Allow folding of values of any literal type in all languages.
2607 if (Info.getLangOpts().CPlusPlus11) {
2608 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2609 Info.Note(VD->getLocation(), diag::note_declared_at);
2610 } else {
2611 Info.Diag(E);
2612 }
2613 return CompleteObject();
2614 }
2615 }
2616
2617 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2618 return CompleteObject();
2619 } else {
2620 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2621
2622 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002623 if (const MaterializeTemporaryExpr *MTE =
2624 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2625 assert(MTE->getStorageDuration() == SD_Static &&
2626 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002627
Richard Smithe6c01442013-06-05 00:46:14 +00002628 // Per C++1y [expr.const]p2:
2629 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2630 // - a [...] glvalue of integral or enumeration type that refers to
2631 // a non-volatile const object [...]
2632 // [...]
2633 // - a [...] glvalue of literal type that refers to a non-volatile
2634 // object whose lifetime began within the evaluation of e.
2635 //
2636 // C++11 misses the 'began within the evaluation of e' check and
2637 // instead allows all temporaries, including things like:
2638 // int &&r = 1;
2639 // int x = ++r;
2640 // constexpr int k = r;
2641 // Therefore we use the C++1y rules in C++11 too.
2642 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2643 const ValueDecl *ED = MTE->getExtendingDecl();
2644 if (!(BaseType.isConstQualified() &&
2645 BaseType->isIntegralOrEnumerationType()) &&
2646 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2647 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2648 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2649 return CompleteObject();
2650 }
2651
2652 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2653 assert(BaseVal && "got reference to unevaluated temporary");
2654 } else {
2655 Info.Diag(E);
2656 return CompleteObject();
2657 }
2658 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002659 BaseVal = Frame->getTemporary(Base);
2660 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002661 }
Richard Smith3229b742013-05-05 21:17:10 +00002662
2663 // Volatile temporary objects cannot be accessed in constant expressions.
2664 if (BaseType.isVolatileQualified()) {
2665 if (Info.getLangOpts().CPlusPlus) {
2666 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2667 << AK << 0;
2668 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2669 } else {
2670 Info.Diag(E);
2671 }
2672 return CompleteObject();
2673 }
2674 }
2675
Richard Smith7525ff62013-05-09 07:14:00 +00002676 // During the construction of an object, it is not yet 'const'.
2677 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2678 // and this doesn't do quite the right thing for const subobjects of the
2679 // object under construction.
2680 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2681 BaseType = Info.Ctx.getCanonicalType(BaseType);
2682 BaseType.removeLocalConst();
2683 }
2684
Richard Smith6d4c6582013-11-05 22:18:15 +00002685 // In C++1y, we can't safely access any mutable state when we might be
2686 // evaluating after an unmodeled side effect or an evaluation failure.
2687 //
2688 // FIXME: Not all local state is mutable. Allow local constant subobjects
2689 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002690 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002691 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002692 return CompleteObject();
2693
2694 return CompleteObject(BaseVal, BaseType);
2695}
2696
Richard Smith243ef902013-05-05 23:31:59 +00002697/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2698/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2699/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002700///
2701/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002702/// \param Conv - The expression for which we are performing the conversion.
2703/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002704/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2705/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002706/// \param LVal - The glvalue on which we are attempting to perform this action.
2707/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002708static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002709 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002710 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002711 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002712 return false;
2713
Richard Smith3229b742013-05-05 21:17:10 +00002714 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002715 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002716 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2717 !Type.isVolatileQualified()) {
2718 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2719 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2720 // initializer until now for such expressions. Such an expression can't be
2721 // an ICE in C, so this only matters for fold.
2722 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2723 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002724 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002725 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002726 }
Richard Smith3229b742013-05-05 21:17:10 +00002727 APValue Lit;
2728 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2729 return false;
2730 CompleteObject LitObj(&Lit, Base->getType());
2731 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002732 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002733 // We represent a string literal array as an lvalue pointing at the
2734 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002735 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002736 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2737 CompleteObject StrObj(&Str, Base->getType());
2738 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002739 }
Richard Smith11562c52011-10-28 17:51:58 +00002740 }
2741
Richard Smith3229b742013-05-05 21:17:10 +00002742 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2743 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002744}
2745
2746/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002747static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002748 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002749 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002750 return false;
2751
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002752 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002753 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 return false;
2755 }
2756
Richard Smith3229b742013-05-05 21:17:10 +00002757 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2758 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002759}
2760
Richard Smith243ef902013-05-05 23:31:59 +00002761static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2762 return T->isSignedIntegerType() &&
2763 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2764}
2765
2766namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002767struct CompoundAssignSubobjectHandler {
2768 EvalInfo &Info;
2769 const Expr *E;
2770 QualType PromotedLHSType;
2771 BinaryOperatorKind Opcode;
2772 const APValue &RHS;
2773
2774 static const AccessKinds AccessKind = AK_Assign;
2775
2776 typedef bool result_type;
2777
2778 bool checkConst(QualType QT) {
2779 // Assigning to a const object has undefined behavior.
2780 if (QT.isConstQualified()) {
2781 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2782 return false;
2783 }
2784 return true;
2785 }
2786
2787 bool failed() { return false; }
2788 bool found(APValue &Subobj, QualType SubobjType) {
2789 switch (Subobj.getKind()) {
2790 case APValue::Int:
2791 return found(Subobj.getInt(), SubobjType);
2792 case APValue::Float:
2793 return found(Subobj.getFloat(), SubobjType);
2794 case APValue::ComplexInt:
2795 case APValue::ComplexFloat:
2796 // FIXME: Implement complex compound assignment.
2797 Info.Diag(E);
2798 return false;
2799 case APValue::LValue:
2800 return foundPointer(Subobj, SubobjType);
2801 default:
2802 // FIXME: can this happen?
2803 Info.Diag(E);
2804 return false;
2805 }
2806 }
2807 bool found(APSInt &Value, QualType SubobjType) {
2808 if (!checkConst(SubobjType))
2809 return false;
2810
2811 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2812 // We don't support compound assignment on integer-cast-to-pointer
2813 // values.
2814 Info.Diag(E);
2815 return false;
2816 }
2817
2818 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2819 SubobjType, Value);
2820 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2821 return false;
2822 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2823 return true;
2824 }
2825 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002826 return checkConst(SubobjType) &&
2827 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2828 Value) &&
2829 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2830 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002831 }
2832 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2833 if (!checkConst(SubobjType))
2834 return false;
2835
2836 QualType PointeeType;
2837 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2838 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002839
2840 if (PointeeType.isNull() || !RHS.isInt() ||
2841 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002842 Info.Diag(E);
2843 return false;
2844 }
2845
Richard Smith861b5b52013-05-07 23:34:45 +00002846 int64_t Offset = getExtValue(RHS.getInt());
2847 if (Opcode == BO_Sub)
2848 Offset = -Offset;
2849
2850 LValue LVal;
2851 LVal.setFrom(Info.Ctx, Subobj);
2852 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2853 return false;
2854 LVal.moveInto(Subobj);
2855 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002856 }
2857 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2858 llvm_unreachable("shouldn't encounter string elements here");
2859 }
2860};
2861} // end anonymous namespace
2862
2863const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2864
2865/// Perform a compound assignment of LVal <op>= RVal.
2866static bool handleCompoundAssignment(
2867 EvalInfo &Info, const Expr *E,
2868 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2869 BinaryOperatorKind Opcode, const APValue &RVal) {
2870 if (LVal.Designator.Invalid)
2871 return false;
2872
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002873 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002874 Info.Diag(E);
2875 return false;
2876 }
2877
2878 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2879 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2880 RVal };
2881 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2882}
2883
2884namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002885struct IncDecSubobjectHandler {
2886 EvalInfo &Info;
2887 const Expr *E;
2888 AccessKinds AccessKind;
2889 APValue *Old;
2890
2891 typedef bool result_type;
2892
2893 bool checkConst(QualType QT) {
2894 // Assigning to a const object has undefined behavior.
2895 if (QT.isConstQualified()) {
2896 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2897 return false;
2898 }
2899 return true;
2900 }
2901
2902 bool failed() { return false; }
2903 bool found(APValue &Subobj, QualType SubobjType) {
2904 // Stash the old value. Also clear Old, so we don't clobber it later
2905 // if we're post-incrementing a complex.
2906 if (Old) {
2907 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002908 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002909 }
2910
2911 switch (Subobj.getKind()) {
2912 case APValue::Int:
2913 return found(Subobj.getInt(), SubobjType);
2914 case APValue::Float:
2915 return found(Subobj.getFloat(), SubobjType);
2916 case APValue::ComplexInt:
2917 return found(Subobj.getComplexIntReal(),
2918 SubobjType->castAs<ComplexType>()->getElementType()
2919 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2920 case APValue::ComplexFloat:
2921 return found(Subobj.getComplexFloatReal(),
2922 SubobjType->castAs<ComplexType>()->getElementType()
2923 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2924 case APValue::LValue:
2925 return foundPointer(Subobj, SubobjType);
2926 default:
2927 // FIXME: can this happen?
2928 Info.Diag(E);
2929 return false;
2930 }
2931 }
2932 bool found(APSInt &Value, QualType SubobjType) {
2933 if (!checkConst(SubobjType))
2934 return false;
2935
2936 if (!SubobjType->isIntegerType()) {
2937 // We don't support increment / decrement on integer-cast-to-pointer
2938 // values.
2939 Info.Diag(E);
2940 return false;
2941 }
2942
2943 if (Old) *Old = APValue(Value);
2944
2945 // bool arithmetic promotes to int, and the conversion back to bool
2946 // doesn't reduce mod 2^n, so special-case it.
2947 if (SubobjType->isBooleanType()) {
2948 if (AccessKind == AK_Increment)
2949 Value = 1;
2950 else
2951 Value = !Value;
2952 return true;
2953 }
2954
2955 bool WasNegative = Value.isNegative();
2956 if (AccessKind == AK_Increment) {
2957 ++Value;
2958
2959 if (!WasNegative && Value.isNegative() &&
2960 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2961 APSInt ActualValue(Value, /*IsUnsigned*/true);
2962 HandleOverflow(Info, E, ActualValue, SubobjType);
2963 }
2964 } else {
2965 --Value;
2966
2967 if (WasNegative && !Value.isNegative() &&
2968 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2969 unsigned BitWidth = Value.getBitWidth();
2970 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2971 ActualValue.setBit(BitWidth);
2972 HandleOverflow(Info, E, ActualValue, SubobjType);
2973 }
2974 }
2975 return true;
2976 }
2977 bool found(APFloat &Value, QualType SubobjType) {
2978 if (!checkConst(SubobjType))
2979 return false;
2980
2981 if (Old) *Old = APValue(Value);
2982
2983 APFloat One(Value.getSemantics(), 1);
2984 if (AccessKind == AK_Increment)
2985 Value.add(One, APFloat::rmNearestTiesToEven);
2986 else
2987 Value.subtract(One, APFloat::rmNearestTiesToEven);
2988 return true;
2989 }
2990 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2991 if (!checkConst(SubobjType))
2992 return false;
2993
2994 QualType PointeeType;
2995 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2996 PointeeType = PT->getPointeeType();
2997 else {
2998 Info.Diag(E);
2999 return false;
3000 }
3001
3002 LValue LVal;
3003 LVal.setFrom(Info.Ctx, Subobj);
3004 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3005 AccessKind == AK_Increment ? 1 : -1))
3006 return false;
3007 LVal.moveInto(Subobj);
3008 return true;
3009 }
3010 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3011 llvm_unreachable("shouldn't encounter string elements here");
3012 }
3013};
3014} // end anonymous namespace
3015
3016/// Perform an increment or decrement on LVal.
3017static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3018 QualType LValType, bool IsIncrement, APValue *Old) {
3019 if (LVal.Designator.Invalid)
3020 return false;
3021
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003022 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003023 Info.Diag(E);
3024 return false;
3025 }
3026
3027 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3028 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3029 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3030 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3031}
3032
Richard Smithe97cbd72011-11-11 04:05:33 +00003033/// Build an lvalue for the object argument of a member function call.
3034static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3035 LValue &This) {
3036 if (Object->getType()->isPointerType())
3037 return EvaluatePointer(Object, This, Info);
3038
3039 if (Object->isGLValue())
3040 return EvaluateLValue(Object, This, Info);
3041
Richard Smithd9f663b2013-04-22 15:31:51 +00003042 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003043 return EvaluateTemporary(Object, This, Info);
3044
Richard Smith3e79a572014-06-11 19:53:12 +00003045 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003046 return false;
3047}
3048
3049/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3050/// lvalue referring to the result.
3051///
3052/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003053/// \param LV - An lvalue referring to the base of the member pointer.
3054/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003055/// \param IncludeMember - Specifies whether the member itself is included in
3056/// the resulting LValue subobject designator. This is not possible when
3057/// creating a bound member function.
3058/// \return The field or method declaration to which the member pointer refers,
3059/// or 0 if evaluation fails.
3060static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003061 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003062 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003063 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003064 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003065 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003066 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003067 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003068
3069 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3070 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003071 if (!MemPtr.getDecl()) {
3072 // FIXME: Specific diagnostic.
3073 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003074 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003075 }
Richard Smith253c2a32012-01-27 01:14:48 +00003076
Richard Smith027bf112011-11-17 22:56:20 +00003077 if (MemPtr.isDerivedMember()) {
3078 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003079 // The end of the derived-to-base path for the base object must match the
3080 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003081 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003082 LV.Designator.Entries.size()) {
3083 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003084 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003085 }
Richard Smith027bf112011-11-17 22:56:20 +00003086 unsigned PathLengthToMember =
3087 LV.Designator.Entries.size() - MemPtr.Path.size();
3088 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3089 const CXXRecordDecl *LVDecl = getAsBaseClass(
3090 LV.Designator.Entries[PathLengthToMember + I]);
3091 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003092 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3093 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003094 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003095 }
Richard Smith027bf112011-11-17 22:56:20 +00003096 }
3097
3098 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003099 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003100 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003101 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003102 } else if (!MemPtr.Path.empty()) {
3103 // Extend the LValue path with the member pointer's path.
3104 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3105 MemPtr.Path.size() + IncludeMember);
3106
3107 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003108 if (const PointerType *PT = LVType->getAs<PointerType>())
3109 LVType = PT->getPointeeType();
3110 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3111 assert(RD && "member pointer access on non-class-type expression");
3112 // The first class in the path is that of the lvalue.
3113 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3114 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003115 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003116 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003117 RD = Base;
3118 }
3119 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003120 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3121 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003122 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003123 }
3124
3125 // Add the member. Note that we cannot build bound member functions here.
3126 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003127 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003128 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003129 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003130 } else if (const IndirectFieldDecl *IFD =
3131 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003132 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003133 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003134 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003135 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003136 }
Richard Smith027bf112011-11-17 22:56:20 +00003137 }
3138
3139 return MemPtr.getDecl();
3140}
3141
Richard Smith84401042013-06-03 05:03:02 +00003142static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3143 const BinaryOperator *BO,
3144 LValue &LV,
3145 bool IncludeMember = true) {
3146 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3147
3148 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3149 if (Info.keepEvaluatingAfterFailure()) {
3150 MemberPtr MemPtr;
3151 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3152 }
Craig Topper36250ad2014-05-12 05:36:57 +00003153 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003154 }
3155
3156 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3157 BO->getRHS(), IncludeMember);
3158}
3159
Richard Smith027bf112011-11-17 22:56:20 +00003160/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3161/// the provided lvalue, which currently refers to the base object.
3162static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3163 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003164 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003165 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003166 return false;
3167
Richard Smitha8105bc2012-01-06 16:39:00 +00003168 QualType TargetQT = E->getType();
3169 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3170 TargetQT = PT->getPointeeType();
3171
3172 // Check this cast lands within the final derived-to-base subobject path.
3173 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003174 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003175 << D.MostDerivedType << TargetQT;
3176 return false;
3177 }
3178
Richard Smith027bf112011-11-17 22:56:20 +00003179 // Check the type of the final cast. We don't need to check the path,
3180 // since a cast can only be formed if the path is unique.
3181 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003182 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3183 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003184 if (NewEntriesSize == D.MostDerivedPathLength)
3185 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3186 else
Richard Smith027bf112011-11-17 22:56:20 +00003187 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003188 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003189 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003190 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003191 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003192 }
Richard Smith027bf112011-11-17 22:56:20 +00003193
3194 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003195 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003196}
3197
Mike Stump876387b2009-10-27 22:09:17 +00003198namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003199enum EvalStmtResult {
3200 /// Evaluation failed.
3201 ESR_Failed,
3202 /// Hit a 'return' statement.
3203 ESR_Returned,
3204 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003205 ESR_Succeeded,
3206 /// Hit a 'continue' statement.
3207 ESR_Continue,
3208 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003209 ESR_Break,
3210 /// Still scanning for 'case' or 'default' statement.
3211 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003212};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003213}
Richard Smith254a73d2011-10-28 22:34:42 +00003214
Richard Smithd9f663b2013-04-22 15:31:51 +00003215static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3216 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3217 // We don't need to evaluate the initializer for a static local.
3218 if (!VD->hasLocalStorage())
3219 return true;
3220
3221 LValue Result;
3222 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003223 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003224
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003225 const Expr *InitE = VD->getInit();
3226 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003227 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3228 << false << VD->getType();
3229 Val = APValue();
3230 return false;
3231 }
3232
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003233 if (InitE->isValueDependent())
3234 return false;
3235
3236 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003237 // Wipe out any partially-computed value, to allow tracking that this
3238 // evaluation failed.
3239 Val = APValue();
3240 return false;
3241 }
3242 }
3243
3244 return true;
3245}
3246
Richard Smith4e18ca52013-05-06 05:56:11 +00003247/// Evaluate a condition (either a variable declaration or an expression).
3248static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3249 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003250 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003251 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3252 return false;
3253 return EvaluateAsBooleanCondition(Cond, Result, Info);
3254}
3255
3256static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003257 const Stmt *S,
3258 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003259
3260/// Evaluate the body of a loop, and translate the result as appropriate.
3261static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003262 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003263 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003264 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003265 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003266 case ESR_Break:
3267 return ESR_Succeeded;
3268 case ESR_Succeeded:
3269 case ESR_Continue:
3270 return ESR_Continue;
3271 case ESR_Failed:
3272 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003273 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003274 return ESR;
3275 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003276 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003277}
3278
Richard Smith496ddcf2013-05-12 17:32:42 +00003279/// Evaluate a switch statement.
3280static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3281 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003282 BlockScopeRAII Scope(Info);
3283
Richard Smith496ddcf2013-05-12 17:32:42 +00003284 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003285 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003286 {
3287 FullExpressionRAII Scope(Info);
3288 if (SS->getConditionVariable() &&
3289 !EvaluateDecl(Info, SS->getConditionVariable()))
3290 return ESR_Failed;
3291 if (!EvaluateInteger(SS->getCond(), Value, Info))
3292 return ESR_Failed;
3293 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003294
3295 // Find the switch case corresponding to the value of the condition.
3296 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003297 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003298 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3299 SC = SC->getNextSwitchCase()) {
3300 if (isa<DefaultStmt>(SC)) {
3301 Found = SC;
3302 continue;
3303 }
3304
3305 const CaseStmt *CS = cast<CaseStmt>(SC);
3306 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3307 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3308 : LHS;
3309 if (LHS <= Value && Value <= RHS) {
3310 Found = SC;
3311 break;
3312 }
3313 }
3314
3315 if (!Found)
3316 return ESR_Succeeded;
3317
3318 // Search the switch body for the switch case and evaluate it from there.
3319 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3320 case ESR_Break:
3321 return ESR_Succeeded;
3322 case ESR_Succeeded:
3323 case ESR_Continue:
3324 case ESR_Failed:
3325 case ESR_Returned:
3326 return ESR;
3327 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003328 // This can only happen if the switch case is nested within a statement
3329 // expression. We have no intention of supporting that.
3330 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3331 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003332 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003333 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003334}
3335
Richard Smith254a73d2011-10-28 22:34:42 +00003336// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003337static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003338 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003339 if (!Info.nextStep(S))
3340 return ESR_Failed;
3341
Richard Smith496ddcf2013-05-12 17:32:42 +00003342 // If we're hunting down a 'case' or 'default' label, recurse through
3343 // substatements until we hit the label.
3344 if (Case) {
3345 // FIXME: We don't start the lifetime of objects whose initialization we
3346 // jump over. However, such objects must be of class type with a trivial
3347 // default constructor that initialize all subobjects, so must be empty,
3348 // so this almost never matters.
3349 switch (S->getStmtClass()) {
3350 case Stmt::CompoundStmtClass:
3351 // FIXME: Precompute which substatement of a compound statement we
3352 // would jump to, and go straight there rather than performing a
3353 // linear scan each time.
3354 case Stmt::LabelStmtClass:
3355 case Stmt::AttributedStmtClass:
3356 case Stmt::DoStmtClass:
3357 break;
3358
3359 case Stmt::CaseStmtClass:
3360 case Stmt::DefaultStmtClass:
3361 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003362 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003363 break;
3364
3365 case Stmt::IfStmtClass: {
3366 // FIXME: Precompute which side of an 'if' we would jump to, and go
3367 // straight there rather than scanning both sides.
3368 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003369
3370 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3371 // preceded by our switch label.
3372 BlockScopeRAII Scope(Info);
3373
Richard Smith496ddcf2013-05-12 17:32:42 +00003374 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3375 if (ESR != ESR_CaseNotFound || !IS->getElse())
3376 return ESR;
3377 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3378 }
3379
3380 case Stmt::WhileStmtClass: {
3381 EvalStmtResult ESR =
3382 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3383 if (ESR != ESR_Continue)
3384 return ESR;
3385 break;
3386 }
3387
3388 case Stmt::ForStmtClass: {
3389 const ForStmt *FS = cast<ForStmt>(S);
3390 EvalStmtResult ESR =
3391 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3392 if (ESR != ESR_Continue)
3393 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003394 if (FS->getInc()) {
3395 FullExpressionRAII IncScope(Info);
3396 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3397 return ESR_Failed;
3398 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003399 break;
3400 }
3401
3402 case Stmt::DeclStmtClass:
3403 // FIXME: If the variable has initialization that can't be jumped over,
3404 // bail out of any immediately-surrounding compound-statement too.
3405 default:
3406 return ESR_CaseNotFound;
3407 }
3408 }
3409
Richard Smith254a73d2011-10-28 22:34:42 +00003410 switch (S->getStmtClass()) {
3411 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003412 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003413 // Don't bother evaluating beyond an expression-statement which couldn't
3414 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003415 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003416 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003417 return ESR_Failed;
3418 return ESR_Succeeded;
3419 }
3420
3421 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003422 return ESR_Failed;
3423
3424 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003425 return ESR_Succeeded;
3426
Richard Smithd9f663b2013-04-22 15:31:51 +00003427 case Stmt::DeclStmtClass: {
3428 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003429 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003430 // Each declaration initialization is its own full-expression.
3431 // FIXME: This isn't quite right; if we're performing aggregate
3432 // initialization, each braced subexpression is its own full-expression.
3433 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003434 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003435 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003436 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003437 return ESR_Succeeded;
3438 }
3439
Richard Smith357362d2011-12-13 06:39:58 +00003440 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003441 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003442 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003443 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003444 return ESR_Failed;
3445 return ESR_Returned;
3446 }
Richard Smith254a73d2011-10-28 22:34:42 +00003447
3448 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003449 BlockScopeRAII Scope(Info);
3450
Richard Smith254a73d2011-10-28 22:34:42 +00003451 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003452 for (const auto *BI : CS->body()) {
3453 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003454 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003455 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003456 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003457 return ESR;
3458 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003459 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003460 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003461
3462 case Stmt::IfStmtClass: {
3463 const IfStmt *IS = cast<IfStmt>(S);
3464
3465 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003466 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003467 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003468 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003469 return ESR_Failed;
3470
3471 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3472 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3473 if (ESR != ESR_Succeeded)
3474 return ESR;
3475 }
3476 return ESR_Succeeded;
3477 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003478
3479 case Stmt::WhileStmtClass: {
3480 const WhileStmt *WS = cast<WhileStmt>(S);
3481 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003482 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003483 bool Continue;
3484 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3485 Continue))
3486 return ESR_Failed;
3487 if (!Continue)
3488 break;
3489
3490 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3491 if (ESR != ESR_Continue)
3492 return ESR;
3493 }
3494 return ESR_Succeeded;
3495 }
3496
3497 case Stmt::DoStmtClass: {
3498 const DoStmt *DS = cast<DoStmt>(S);
3499 bool Continue;
3500 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003501 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003502 if (ESR != ESR_Continue)
3503 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003504 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003505
Richard Smith08d6a2c2013-07-24 07:11:57 +00003506 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003507 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3508 return ESR_Failed;
3509 } while (Continue);
3510 return ESR_Succeeded;
3511 }
3512
3513 case Stmt::ForStmtClass: {
3514 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003515 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003516 if (FS->getInit()) {
3517 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3518 if (ESR != ESR_Succeeded)
3519 return ESR;
3520 }
3521 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003523 bool Continue = true;
3524 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3525 FS->getCond(), Continue))
3526 return ESR_Failed;
3527 if (!Continue)
3528 break;
3529
3530 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3531 if (ESR != ESR_Continue)
3532 return ESR;
3533
Richard Smith08d6a2c2013-07-24 07:11:57 +00003534 if (FS->getInc()) {
3535 FullExpressionRAII IncScope(Info);
3536 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3537 return ESR_Failed;
3538 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003539 }
3540 return ESR_Succeeded;
3541 }
3542
Richard Smith896e0d72013-05-06 06:51:17 +00003543 case Stmt::CXXForRangeStmtClass: {
3544 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003545 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003546
3547 // Initialize the __range variable.
3548 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3549 if (ESR != ESR_Succeeded)
3550 return ESR;
3551
3552 // Create the __begin and __end iterators.
3553 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3554 if (ESR != ESR_Succeeded)
3555 return ESR;
3556
3557 while (true) {
3558 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003559 {
3560 bool Continue = true;
3561 FullExpressionRAII CondExpr(Info);
3562 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3563 return ESR_Failed;
3564 if (!Continue)
3565 break;
3566 }
Richard Smith896e0d72013-05-06 06:51:17 +00003567
3568 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003569 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003570 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3571 if (ESR != ESR_Succeeded)
3572 return ESR;
3573
3574 // Loop body.
3575 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3576 if (ESR != ESR_Continue)
3577 return ESR;
3578
3579 // Increment: ++__begin
3580 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3581 return ESR_Failed;
3582 }
3583
3584 return ESR_Succeeded;
3585 }
3586
Richard Smith496ddcf2013-05-12 17:32:42 +00003587 case Stmt::SwitchStmtClass:
3588 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3589
Richard Smith4e18ca52013-05-06 05:56:11 +00003590 case Stmt::ContinueStmtClass:
3591 return ESR_Continue;
3592
3593 case Stmt::BreakStmtClass:
3594 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003595
3596 case Stmt::LabelStmtClass:
3597 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3598
3599 case Stmt::AttributedStmtClass:
3600 // As a general principle, C++11 attributes can be ignored without
3601 // any semantic impact.
3602 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3603 Case);
3604
3605 case Stmt::CaseStmtClass:
3606 case Stmt::DefaultStmtClass:
3607 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003608 }
3609}
3610
Richard Smithcc36f692011-12-22 02:22:31 +00003611/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3612/// default constructor. If so, we'll fold it whether or not it's marked as
3613/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3614/// so we need special handling.
3615static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003616 const CXXConstructorDecl *CD,
3617 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003618 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3619 return false;
3620
Richard Smith66e05fe2012-01-18 05:21:49 +00003621 // Value-initialization does not call a trivial default constructor, so such a
3622 // call is a core constant expression whether or not the constructor is
3623 // constexpr.
3624 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003625 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003626 // FIXME: If DiagDecl is an implicitly-declared special member function,
3627 // we should be much more explicit about why it's not constexpr.
3628 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3629 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3630 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003631 } else {
3632 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3633 }
3634 }
3635 return true;
3636}
3637
Richard Smith357362d2011-12-13 06:39:58 +00003638/// CheckConstexprFunction - Check that a function can be called in a constant
3639/// expression.
3640static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3641 const FunctionDecl *Declaration,
3642 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003643 // Potential constant expressions can contain calls to declared, but not yet
3644 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003645 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003646 Declaration->isConstexpr())
3647 return false;
3648
Richard Smith0838f3a2013-05-14 05:18:44 +00003649 // Bail out with no diagnostic if the function declaration itself is invalid.
3650 // We will have produced a relevant diagnostic while parsing it.
3651 if (Declaration->isInvalidDecl())
3652 return false;
3653
Richard Smith357362d2011-12-13 06:39:58 +00003654 // Can we evaluate this function call?
3655 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3656 return true;
3657
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003658 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003659 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003660 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3661 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003662 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3663 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3664 << DiagDecl;
3665 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3666 } else {
3667 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3668 }
3669 return false;
3670}
3671
Richard Smithbe6dd812014-11-19 21:27:17 +00003672/// Determine if a class has any fields that might need to be copied by a
3673/// trivial copy or move operation.
3674static bool hasFields(const CXXRecordDecl *RD) {
3675 if (!RD || RD->isEmpty())
3676 return false;
3677 for (auto *FD : RD->fields()) {
3678 if (FD->isUnnamedBitfield())
3679 continue;
3680 return true;
3681 }
3682 for (auto &Base : RD->bases())
3683 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3684 return true;
3685 return false;
3686}
3687
Richard Smithd62306a2011-11-10 06:34:14 +00003688namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003689typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003690}
3691
3692/// EvaluateArgs - Evaluate the arguments to a function call.
3693static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3694 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003695 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003696 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003697 I != E; ++I) {
3698 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3699 // If we're checking for a potential constant expression, evaluate all
3700 // initializers even if some of them fail.
3701 if (!Info.keepEvaluatingAfterFailure())
3702 return false;
3703 Success = false;
3704 }
3705 }
3706 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003707}
3708
Richard Smith254a73d2011-10-28 22:34:42 +00003709/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003710static bool HandleFunctionCall(SourceLocation CallLoc,
3711 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003712 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003713 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003714 ArgVector ArgValues(Args.size());
3715 if (!EvaluateArgs(Args, ArgValues, Info))
3716 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003717
Richard Smith253c2a32012-01-27 01:14:48 +00003718 if (!Info.CheckCallLimit(CallLoc))
3719 return false;
3720
3721 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003722
3723 // For a trivial copy or move assignment, perform an APValue copy. This is
3724 // essential for unions, where the operations performed by the assignment
3725 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003726 //
3727 // Skip this for non-union classes with no fields; in that case, the defaulted
3728 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003729 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003730 if (MD && MD->isDefaulted() &&
3731 (MD->getParent()->isUnion() ||
3732 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003733 assert(This &&
3734 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3735 LValue RHS;
3736 RHS.setFrom(Info.Ctx, ArgValues[0]);
3737 APValue RHSValue;
3738 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3739 RHS, RHSValue))
3740 return false;
3741 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3742 RHSValue))
3743 return false;
3744 This->moveInto(Result);
3745 return true;
3746 }
3747
Richard Smithd9f663b2013-04-22 15:31:51 +00003748 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003749 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003750 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003751 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003752 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003753 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003754 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003755}
3756
Richard Smithd62306a2011-11-10 06:34:14 +00003757/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003758static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003759 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003760 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003761 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003762 ArgVector ArgValues(Args.size());
3763 if (!EvaluateArgs(Args, ArgValues, Info))
3764 return false;
3765
Richard Smith253c2a32012-01-27 01:14:48 +00003766 if (!Info.CheckCallLimit(CallLoc))
3767 return false;
3768
Richard Smith3607ffe2012-02-13 03:54:03 +00003769 const CXXRecordDecl *RD = Definition->getParent();
3770 if (RD->getNumVBases()) {
3771 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3772 return false;
3773 }
3774
Richard Smith253c2a32012-01-27 01:14:48 +00003775 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003776
3777 // If it's a delegating constructor, just delegate.
3778 if (Definition->isDelegatingConstructor()) {
3779 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003780 {
3781 FullExpressionRAII InitScope(Info);
3782 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3783 return false;
3784 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003785 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003786 }
3787
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003788 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003789 // essential for unions (or classes with anonymous union members), where the
3790 // operations performed by the constructor cannot be represented by
3791 // ctor-initializers.
3792 //
3793 // Skip this for empty non-union classes; we should not perform an
3794 // lvalue-to-rvalue conversion on them because their copy constructor does not
3795 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003796 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003797 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003798 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003799 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003800 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003801 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003802 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003803 }
3804
3805 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003806 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003807 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003808 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003809
John McCalld7bca762012-05-01 00:38:49 +00003810 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003811 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3812
Richard Smith08d6a2c2013-07-24 07:11:57 +00003813 // A scope for temporaries lifetime-extended by reference members.
3814 BlockScopeRAII LifetimeExtendedScope(Info);
3815
Richard Smith253c2a32012-01-27 01:14:48 +00003816 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003817 unsigned BasesSeen = 0;
3818#ifndef NDEBUG
3819 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3820#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003821 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003822 LValue Subobject = This;
3823 APValue *Value = &Result;
3824
3825 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003826 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003827 if (I->isBaseInitializer()) {
3828 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003829#ifndef NDEBUG
3830 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003831 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003832 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3833 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3834 "base class initializers not in expected order");
3835 ++BaseIt;
3836#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003837 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003838 BaseType->getAsCXXRecordDecl(), &Layout))
3839 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003840 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003841 } else if ((FD = I->getMember())) {
3842 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003843 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003844 if (RD->isUnion()) {
3845 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003846 Value = &Result.getUnionValue();
3847 } else {
3848 Value = &Result.getStructField(FD->getFieldIndex());
3849 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003850 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003851 // Walk the indirect field decl's chain to find the object to initialize,
3852 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003853 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003854 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003855 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3856 // Switch the union field if it differs. This happens if we had
3857 // preceding zero-initialization, and we're now initializing a union
3858 // subobject other than the first.
3859 // FIXME: In this case, the values of the other subobjects are
3860 // specified, since zero-initialization sets all padding bits to zero.
3861 if (Value->isUninit() ||
3862 (Value->isUnion() && Value->getUnionField() != FD)) {
3863 if (CD->isUnion())
3864 *Value = APValue(FD);
3865 else
3866 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003867 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003868 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003869 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003870 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003871 if (CD->isUnion())
3872 Value = &Value->getUnionValue();
3873 else
3874 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003875 }
Richard Smithd62306a2011-11-10 06:34:14 +00003876 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003877 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003878 }
Richard Smith253c2a32012-01-27 01:14:48 +00003879
Richard Smith08d6a2c2013-07-24 07:11:57 +00003880 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003881 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3882 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003883 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003884 // If we're checking for a potential constant expression, evaluate all
3885 // initializers even if some of them fail.
3886 if (!Info.keepEvaluatingAfterFailure())
3887 return false;
3888 Success = false;
3889 }
Richard Smithd62306a2011-11-10 06:34:14 +00003890 }
3891
Richard Smithd9f663b2013-04-22 15:31:51 +00003892 return Success &&
3893 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003894}
3895
Eli Friedman9a156e52008-11-12 09:44:48 +00003896//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003897// Generic Evaluation
3898//===----------------------------------------------------------------------===//
3899namespace {
3900
Aaron Ballman68af21c2014-01-03 19:26:43 +00003901template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003902class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003903 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003904private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003905 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003906 return static_cast<Derived*>(this)->Success(V, E);
3907 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003908 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003909 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003910 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003911
Richard Smith17100ba2012-02-16 02:46:34 +00003912 // Check whether a conditional operator with a non-constant condition is a
3913 // potential constant expression. If neither arm is a potential constant
3914 // expression, then the conditional operator is not either.
3915 template<typename ConditionalOperator>
3916 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003917 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003918
3919 // Speculatively evaluate both arms.
3920 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003921 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003922 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3923
3924 StmtVisitorTy::Visit(E->getFalseExpr());
3925 if (Diag.empty())
3926 return;
3927
3928 Diag.clear();
3929 StmtVisitorTy::Visit(E->getTrueExpr());
3930 if (Diag.empty())
3931 return;
3932 }
3933
3934 Error(E, diag::note_constexpr_conditional_never_const);
3935 }
3936
3937
3938 template<typename ConditionalOperator>
3939 bool HandleConditionalOperator(const ConditionalOperator *E) {
3940 bool BoolResult;
3941 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003942 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003943 CheckPotentialConstantConditional(E);
3944 return false;
3945 }
3946
3947 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3948 return StmtVisitorTy::Visit(EvalExpr);
3949 }
3950
Peter Collingbournee9200682011-05-13 03:29:01 +00003951protected:
3952 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003953 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003954 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3955
Richard Smith92b1ce02011-12-12 09:28:41 +00003956 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003957 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003958 }
3959
Aaron Ballman68af21c2014-01-03 19:26:43 +00003960 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003961
3962public:
3963 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3964
3965 EvalInfo &getEvalInfo() { return Info; }
3966
Richard Smithf57d8cb2011-12-09 22:58:01 +00003967 /// Report an evaluation error. This should only be called when an error is
3968 /// first discovered. When propagating an error, just return false.
3969 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003970 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003971 return false;
3972 }
3973 bool Error(const Expr *E) {
3974 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3975 }
3976
Aaron Ballman68af21c2014-01-03 19:26:43 +00003977 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003978 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003979 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003980 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003981 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003982 }
3983
Aaron Ballman68af21c2014-01-03 19:26:43 +00003984 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003985 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003986 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003987 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003988 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003989 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003990 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003991 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003992 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003993 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003994 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003995 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003996 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003997 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003998 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003999 // The initializer may not have been parsed yet, or might be erroneous.
4000 if (!E->getExpr())
4001 return Error(E);
4002 return StmtVisitorTy::Visit(E->getExpr());
4003 }
Richard Smith5894a912011-12-19 22:12:41 +00004004 // We cannot create any objects for which cleanups are required, so there is
4005 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004006 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004007 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004008
Aaron Ballman68af21c2014-01-03 19:26:43 +00004009 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004010 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4011 return static_cast<Derived*>(this)->VisitCastExpr(E);
4012 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004013 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004014 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4015 return static_cast<Derived*>(this)->VisitCastExpr(E);
4016 }
4017
Aaron Ballman68af21c2014-01-03 19:26:43 +00004018 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004019 switch (E->getOpcode()) {
4020 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004021 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004022
4023 case BO_Comma:
4024 VisitIgnoredValue(E->getLHS());
4025 return StmtVisitorTy::Visit(E->getRHS());
4026
4027 case BO_PtrMemD:
4028 case BO_PtrMemI: {
4029 LValue Obj;
4030 if (!HandleMemberPointerAccess(Info, E, Obj))
4031 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004032 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004033 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004034 return false;
4035 return DerivedSuccess(Result, E);
4036 }
4037 }
4038 }
4039
Aaron Ballman68af21c2014-01-03 19:26:43 +00004040 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004041 // Evaluate and cache the common expression. We treat it as a temporary,
4042 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004044 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004045 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004046
Richard Smith17100ba2012-02-16 02:46:34 +00004047 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004048 }
4049
Aaron Ballman68af21c2014-01-03 19:26:43 +00004050 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004051 bool IsBcpCall = false;
4052 // If the condition (ignoring parens) is a __builtin_constant_p call,
4053 // the result is a constant expression if it can be folded without
4054 // side-effects. This is an important GNU extension. See GCC PR38377
4055 // for discussion.
4056 if (const CallExpr *CallCE =
4057 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004058 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004059 IsBcpCall = true;
4060
4061 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4062 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004063 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004064 return false;
4065
Richard Smith6d4c6582013-11-05 22:18:15 +00004066 FoldConstant Fold(Info, IsBcpCall);
4067 if (!HandleConditionalOperator(E)) {
4068 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004069 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004070 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004071
4072 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004073 }
4074
Aaron Ballman68af21c2014-01-03 19:26:43 +00004075 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004076 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4077 return DerivedSuccess(*Value, E);
4078
4079 const Expr *Source = E->getSourceExpr();
4080 if (!Source)
4081 return Error(E);
4082 if (Source == E) { // sanity checking.
4083 assert(0 && "OpaqueValueExpr recursively refers to itself");
4084 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004085 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004086 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004087 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004088
Aaron Ballman68af21c2014-01-03 19:26:43 +00004089 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004090 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004091 QualType CalleeType = Callee->getType();
4092
Craig Topper36250ad2014-05-12 05:36:57 +00004093 const FunctionDecl *FD = nullptr;
4094 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004095 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004096 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004097
Richard Smithe97cbd72011-11-11 04:05:33 +00004098 // Extract function decl and 'this' pointer from the callee.
4099 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004100 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004101 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4102 // Explicit bound member calls, such as x.f() or p->g();
4103 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004104 return false;
4105 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004106 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004107 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004108 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4109 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004110 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4111 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004112 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004113 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004114 return Error(Callee);
4115
4116 FD = dyn_cast<FunctionDecl>(Member);
4117 if (!FD)
4118 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004119 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004120 LValue Call;
4121 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004122 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004123
Richard Smitha8105bc2012-01-06 16:39:00 +00004124 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004125 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004126 FD = dyn_cast_or_null<FunctionDecl>(
4127 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004128 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004129 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004130
4131 // Overloaded operator calls to member functions are represented as normal
4132 // calls with '*this' as the first argument.
4133 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4134 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004135 // FIXME: When selecting an implicit conversion for an overloaded
4136 // operator delete, we sometimes try to evaluate calls to conversion
4137 // operators without a 'this' parameter!
4138 if (Args.empty())
4139 return Error(E);
4140
Richard Smithe97cbd72011-11-11 04:05:33 +00004141 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4142 return false;
4143 This = &ThisVal;
4144 Args = Args.slice(1);
4145 }
4146
4147 // Don't call function pointers which have been cast to some other type.
4148 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004149 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004150 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004151 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004152
Richard Smith47b34932012-02-01 02:39:43 +00004153 if (This && !This->checkSubobject(Info, E, CSK_This))
4154 return false;
4155
Richard Smith3607ffe2012-02-13 03:54:03 +00004156 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4157 // calls to such functions in constant expressions.
4158 if (This && !HasQualifier &&
4159 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4160 return Error(E, diag::note_constexpr_virtual_call);
4161
Craig Topper36250ad2014-05-12 05:36:57 +00004162 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004163 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004164 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004165
Richard Smith357362d2011-12-13 06:39:58 +00004166 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004167 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4168 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004169 return false;
4170
Richard Smithb228a862012-02-15 02:18:13 +00004171 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004172 }
4173
Aaron Ballman68af21c2014-01-03 19:26:43 +00004174 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004175 return StmtVisitorTy::Visit(E->getInitializer());
4176 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004177 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004178 if (E->getNumInits() == 0)
4179 return DerivedZeroInitialization(E);
4180 if (E->getNumInits() == 1)
4181 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004182 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004183 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004184 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004185 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004186 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004187 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004188 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004189 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004190 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004191 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004192 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004193
Richard Smithd62306a2011-11-10 06:34:14 +00004194 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004195 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004196 assert(!E->isArrow() && "missing call to bound member function?");
4197
Richard Smith2e312c82012-03-03 22:46:17 +00004198 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004199 if (!Evaluate(Val, Info, E->getBase()))
4200 return false;
4201
4202 QualType BaseTy = E->getBase()->getType();
4203
4204 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004205 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004206 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004207 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004208 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4209
Richard Smith3229b742013-05-05 21:17:10 +00004210 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004211 SubobjectDesignator Designator(BaseTy);
4212 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004213
Richard Smith3229b742013-05-05 21:17:10 +00004214 APValue Result;
4215 return extractSubobject(Info, E, Obj, Designator, Result) &&
4216 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004217 }
4218
Aaron Ballman68af21c2014-01-03 19:26:43 +00004219 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004220 switch (E->getCastKind()) {
4221 default:
4222 break;
4223
Richard Smitha23ab512013-05-23 00:30:41 +00004224 case CK_AtomicToNonAtomic: {
4225 APValue AtomicVal;
4226 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4227 return false;
4228 return DerivedSuccess(AtomicVal, E);
4229 }
4230
Richard Smith11562c52011-10-28 17:51:58 +00004231 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004232 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004233 return StmtVisitorTy::Visit(E->getSubExpr());
4234
4235 case CK_LValueToRValue: {
4236 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004237 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4238 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004239 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004240 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004241 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004242 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004243 return false;
4244 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004245 }
4246 }
4247
Richard Smithf57d8cb2011-12-09 22:58:01 +00004248 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004249 }
4250
Aaron Ballman68af21c2014-01-03 19:26:43 +00004251 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004252 return VisitUnaryPostIncDec(UO);
4253 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004254 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004255 return VisitUnaryPostIncDec(UO);
4256 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004257 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004258 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004259 return Error(UO);
4260
4261 LValue LVal;
4262 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4263 return false;
4264 APValue RVal;
4265 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4266 UO->isIncrementOp(), &RVal))
4267 return false;
4268 return DerivedSuccess(RVal, UO);
4269 }
4270
Aaron Ballman68af21c2014-01-03 19:26:43 +00004271 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004272 // We will have checked the full-expressions inside the statement expression
4273 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004274 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004275 return Error(E);
4276
Richard Smith08d6a2c2013-07-24 07:11:57 +00004277 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004278 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004279 if (CS->body_empty())
4280 return true;
4281
Richard Smith51f03172013-06-20 03:00:05 +00004282 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4283 BE = CS->body_end();
4284 /**/; ++BI) {
4285 if (BI + 1 == BE) {
4286 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4287 if (!FinalExpr) {
4288 Info.Diag((*BI)->getLocStart(),
4289 diag::note_constexpr_stmt_expr_unsupported);
4290 return false;
4291 }
4292 return this->Visit(FinalExpr);
4293 }
4294
4295 APValue ReturnValue;
4296 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4297 if (ESR != ESR_Succeeded) {
4298 // FIXME: If the statement-expression terminated due to 'return',
4299 // 'break', or 'continue', it would be nice to propagate that to
4300 // the outer statement evaluation rather than bailing out.
4301 if (ESR != ESR_Failed)
4302 Info.Diag((*BI)->getLocStart(),
4303 diag::note_constexpr_stmt_expr_unsupported);
4304 return false;
4305 }
4306 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004307
4308 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004309 }
4310
Richard Smith4a678122011-10-24 18:44:57 +00004311 /// Visit a value which is evaluated, but whose value is ignored.
4312 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004313 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004314 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004315};
4316
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004317}
Peter Collingbournee9200682011-05-13 03:29:01 +00004318
4319//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004320// Common base class for lvalue and temporary evaluation.
4321//===----------------------------------------------------------------------===//
4322namespace {
4323template<class Derived>
4324class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004325 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004326protected:
4327 LValue &Result;
4328 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004329 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004330
4331 bool Success(APValue::LValueBase B) {
4332 Result.set(B);
4333 return true;
4334 }
4335
4336public:
4337 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4338 ExprEvaluatorBaseTy(Info), Result(Result) {}
4339
Richard Smith2e312c82012-03-03 22:46:17 +00004340 bool Success(const APValue &V, const Expr *E) {
4341 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004342 return true;
4343 }
Richard Smith027bf112011-11-17 22:56:20 +00004344
Richard Smith027bf112011-11-17 22:56:20 +00004345 bool VisitMemberExpr(const MemberExpr *E) {
4346 // Handle non-static data members.
4347 QualType BaseTy;
4348 if (E->isArrow()) {
4349 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4350 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004351 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004352 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004353 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004354 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4355 return false;
4356 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004357 } else {
4358 if (!this->Visit(E->getBase()))
4359 return false;
4360 BaseTy = E->getBase()->getType();
4361 }
Richard Smith027bf112011-11-17 22:56:20 +00004362
Richard Smith1b78b3d2012-01-25 22:15:11 +00004363 const ValueDecl *MD = E->getMemberDecl();
4364 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4365 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4366 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4367 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004368 if (!HandleLValueMember(this->Info, E, Result, FD))
4369 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004370 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004371 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4372 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004373 } else
4374 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004375
Richard Smith1b78b3d2012-01-25 22:15:11 +00004376 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004377 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004378 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004379 RefValue))
4380 return false;
4381 return Success(RefValue, E);
4382 }
4383 return true;
4384 }
4385
4386 bool VisitBinaryOperator(const BinaryOperator *E) {
4387 switch (E->getOpcode()) {
4388 default:
4389 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4390
4391 case BO_PtrMemD:
4392 case BO_PtrMemI:
4393 return HandleMemberPointerAccess(this->Info, E, Result);
4394 }
4395 }
4396
4397 bool VisitCastExpr(const CastExpr *E) {
4398 switch (E->getCastKind()) {
4399 default:
4400 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4401
4402 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004403 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004404 if (!this->Visit(E->getSubExpr()))
4405 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004406
4407 // Now figure out the necessary offset to add to the base LV to get from
4408 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004409 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4410 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004411 }
4412 }
4413};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004414}
Richard Smith027bf112011-11-17 22:56:20 +00004415
4416//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004417// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004418//
4419// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4420// function designators (in C), decl references to void objects (in C), and
4421// temporaries (if building with -Wno-address-of-temporary).
4422//
4423// LValue evaluation produces values comprising a base expression of one of the
4424// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004425// - Declarations
4426// * VarDecl
4427// * FunctionDecl
4428// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004429// * CompoundLiteralExpr in C
4430// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004431// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004432// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004433// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004434// * ObjCEncodeExpr
4435// * AddrLabelExpr
4436// * BlockExpr
4437// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004438// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004439// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004440// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004441// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4442// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004443// * A MaterializeTemporaryExpr that has static storage duration, with no
4444// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004445// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004446//===----------------------------------------------------------------------===//
4447namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004448class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004449 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004450public:
Richard Smith027bf112011-11-17 22:56:20 +00004451 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4452 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004453
Richard Smith11562c52011-10-28 17:51:58 +00004454 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004455 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004456
Peter Collingbournee9200682011-05-13 03:29:01 +00004457 bool VisitDeclRefExpr(const DeclRefExpr *E);
4458 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004459 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004460 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4461 bool VisitMemberExpr(const MemberExpr *E);
4462 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4463 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004464 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004465 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004466 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4467 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004468 bool VisitUnaryReal(const UnaryOperator *E);
4469 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004470 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4471 return VisitUnaryPreIncDec(UO);
4472 }
4473 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4474 return VisitUnaryPreIncDec(UO);
4475 }
Richard Smith3229b742013-05-05 21:17:10 +00004476 bool VisitBinAssign(const BinaryOperator *BO);
4477 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004478
Peter Collingbournee9200682011-05-13 03:29:01 +00004479 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004480 switch (E->getCastKind()) {
4481 default:
Richard Smith027bf112011-11-17 22:56:20 +00004482 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004483
Eli Friedmance3e02a2011-10-11 00:13:24 +00004484 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004485 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004486 if (!Visit(E->getSubExpr()))
4487 return false;
4488 Result.Designator.setInvalid();
4489 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004490
Richard Smith027bf112011-11-17 22:56:20 +00004491 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004492 if (!Visit(E->getSubExpr()))
4493 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004494 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004495 }
4496 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004497};
4498} // end anonymous namespace
4499
Richard Smith11562c52011-10-28 17:51:58 +00004500/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004501/// expressions which are not glvalues, in two cases:
4502/// * function designators in C, and
4503/// * "extern void" objects
4504static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4505 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4506 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004507 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004508}
4509
Peter Collingbournee9200682011-05-13 03:29:01 +00004510bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004511 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004512 return Success(FD);
4513 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004514 return VisitVarDecl(E, VD);
4515 return Error(E);
4516}
Richard Smith733237d2011-10-24 23:14:33 +00004517
Richard Smith11562c52011-10-28 17:51:58 +00004518bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004519 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004520 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4521 Frame = Info.CurrentCall;
4522
Richard Smithfec09922011-11-01 16:57:24 +00004523 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004524 if (Frame) {
4525 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004526 return true;
4527 }
Richard Smithce40ad62011-11-12 22:28:03 +00004528 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004529 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004530
Richard Smith3229b742013-05-05 21:17:10 +00004531 APValue *V;
4532 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004533 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004534 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004535 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004536 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4537 return false;
4538 }
Richard Smith3229b742013-05-05 21:17:10 +00004539 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004540}
4541
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004542bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4543 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004544 // Walk through the expression to find the materialized temporary itself.
4545 SmallVector<const Expr *, 2> CommaLHSs;
4546 SmallVector<SubobjectAdjustment, 2> Adjustments;
4547 const Expr *Inner = E->GetTemporaryExpr()->
4548 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004549
Richard Smith84401042013-06-03 05:03:02 +00004550 // If we passed any comma operators, evaluate their LHSs.
4551 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4552 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4553 return false;
4554
Richard Smithe6c01442013-06-05 00:46:14 +00004555 // A materialized temporary with static storage duration can appear within the
4556 // result of a constant expression evaluation, so we need to preserve its
4557 // value for use outside this evaluation.
4558 APValue *Value;
4559 if (E->getStorageDuration() == SD_Static) {
4560 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004561 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004562 Result.set(E);
4563 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004564 Value = &Info.CurrentCall->
4565 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004566 Result.set(E, Info.CurrentCall->Index);
4567 }
4568
Richard Smithea4ad5d2013-06-06 08:19:16 +00004569 QualType Type = Inner->getType();
4570
Richard Smith84401042013-06-03 05:03:02 +00004571 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004572 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4573 (E->getStorageDuration() == SD_Static &&
4574 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4575 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004576 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004577 }
Richard Smith84401042013-06-03 05:03:02 +00004578
4579 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004580 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4581 --I;
4582 switch (Adjustments[I].Kind) {
4583 case SubobjectAdjustment::DerivedToBaseAdjustment:
4584 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4585 Type, Result))
4586 return false;
4587 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4588 break;
4589
4590 case SubobjectAdjustment::FieldAdjustment:
4591 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4592 return false;
4593 Type = Adjustments[I].Field->getType();
4594 break;
4595
4596 case SubobjectAdjustment::MemberPointerAdjustment:
4597 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4598 Adjustments[I].Ptr.RHS))
4599 return false;
4600 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4601 break;
4602 }
4603 }
4604
4605 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004606}
4607
Peter Collingbournee9200682011-05-13 03:29:01 +00004608bool
4609LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004610 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4611 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4612 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004613 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004614}
4615
Richard Smith6e525142011-12-27 12:18:28 +00004616bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004617 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004618 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004619
4620 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4621 << E->getExprOperand()->getType()
4622 << E->getExprOperand()->getSourceRange();
4623 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004624}
4625
Francois Pichet0066db92012-04-16 04:08:35 +00004626bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4627 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004628}
Francois Pichet0066db92012-04-16 04:08:35 +00004629
Peter Collingbournee9200682011-05-13 03:29:01 +00004630bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004631 // Handle static data members.
4632 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4633 VisitIgnoredValue(E->getBase());
4634 return VisitVarDecl(E, VD);
4635 }
4636
Richard Smith254a73d2011-10-28 22:34:42 +00004637 // Handle static member functions.
4638 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4639 if (MD->isStatic()) {
4640 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004641 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004642 }
4643 }
4644
Richard Smithd62306a2011-11-10 06:34:14 +00004645 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004646 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004647}
4648
Peter Collingbournee9200682011-05-13 03:29:01 +00004649bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004650 // FIXME: Deal with vectors as array subscript bases.
4651 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004653
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004654 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004655 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004656
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004657 APSInt Index;
4658 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004659 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004660
Richard Smith861b5b52013-05-07 23:34:45 +00004661 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4662 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004663}
Eli Friedman9a156e52008-11-12 09:44:48 +00004664
Peter Collingbournee9200682011-05-13 03:29:01 +00004665bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004666 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004667}
4668
Richard Smith66c96992012-02-18 22:04:06 +00004669bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4670 if (!Visit(E->getSubExpr()))
4671 return false;
4672 // __real is a no-op on scalar lvalues.
4673 if (E->getSubExpr()->getType()->isAnyComplexType())
4674 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4675 return true;
4676}
4677
4678bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4679 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4680 "lvalue __imag__ on scalar?");
4681 if (!Visit(E->getSubExpr()))
4682 return false;
4683 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4684 return true;
4685}
4686
Richard Smith243ef902013-05-05 23:31:59 +00004687bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004688 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004689 return Error(UO);
4690
4691 if (!this->Visit(UO->getSubExpr()))
4692 return false;
4693
Richard Smith243ef902013-05-05 23:31:59 +00004694 return handleIncDec(
4695 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004696 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004697}
4698
4699bool LValueExprEvaluator::VisitCompoundAssignOperator(
4700 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004701 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004702 return Error(CAO);
4703
Richard Smith3229b742013-05-05 21:17:10 +00004704 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004705
4706 // The overall lvalue result is the result of evaluating the LHS.
4707 if (!this->Visit(CAO->getLHS())) {
4708 if (Info.keepEvaluatingAfterFailure())
4709 Evaluate(RHS, this->Info, CAO->getRHS());
4710 return false;
4711 }
4712
Richard Smith3229b742013-05-05 21:17:10 +00004713 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4714 return false;
4715
Richard Smith43e77732013-05-07 04:50:00 +00004716 return handleCompoundAssignment(
4717 this->Info, CAO,
4718 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4719 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004720}
4721
4722bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004723 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004724 return Error(E);
4725
Richard Smith3229b742013-05-05 21:17:10 +00004726 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004727
4728 if (!this->Visit(E->getLHS())) {
4729 if (Info.keepEvaluatingAfterFailure())
4730 Evaluate(NewVal, this->Info, E->getRHS());
4731 return false;
4732 }
4733
Richard Smith3229b742013-05-05 21:17:10 +00004734 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4735 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004736
4737 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004738 NewVal);
4739}
4740
Eli Friedman9a156e52008-11-12 09:44:48 +00004741//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004742// Pointer Evaluation
4743//===----------------------------------------------------------------------===//
4744
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004745namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004746class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004748 LValue &Result;
4749
Peter Collingbournee9200682011-05-13 03:29:01 +00004750 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004751 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004752 return true;
4753 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004754public:
Mike Stump11289f42009-09-09 15:08:12 +00004755
John McCall45d55e42010-05-07 21:00:08 +00004756 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004757 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004758
Richard Smith2e312c82012-03-03 22:46:17 +00004759 bool Success(const APValue &V, const Expr *E) {
4760 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004761 return true;
4762 }
Richard Smithfddd3842011-12-30 21:15:51 +00004763 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004764 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004765 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004766
John McCall45d55e42010-05-07 21:00:08 +00004767 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004768 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004769 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004770 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004771 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004772 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004773 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004774 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004775 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004776 bool VisitCallExpr(const CallExpr *E);
4777 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004778 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004779 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004780 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004781 }
Richard Smithd62306a2011-11-10 06:34:14 +00004782 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004783 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004784 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004785 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004786 if (!Info.CurrentCall->This) {
4787 if (Info.getLangOpts().CPlusPlus11)
4788 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4789 else
4790 Info.Diag(E);
4791 return false;
4792 }
Richard Smithd62306a2011-11-10 06:34:14 +00004793 Result = *Info.CurrentCall->This;
4794 return true;
4795 }
John McCallc07a0c72011-02-17 10:25:35 +00004796
Eli Friedman449fe542009-03-23 04:56:01 +00004797 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004798};
Chris Lattner05706e882008-07-11 18:11:29 +00004799} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004800
John McCall45d55e42010-05-07 21:00:08 +00004801static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004802 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004803 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004804}
4805
John McCall45d55e42010-05-07 21:00:08 +00004806bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004807 if (E->getOpcode() != BO_Add &&
4808 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004809 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004810
Chris Lattner05706e882008-07-11 18:11:29 +00004811 const Expr *PExp = E->getLHS();
4812 const Expr *IExp = E->getRHS();
4813 if (IExp->getType()->isPointerType())
4814 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004815
Richard Smith253c2a32012-01-27 01:14:48 +00004816 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4817 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004818 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004819
John McCall45d55e42010-05-07 21:00:08 +00004820 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004821 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004822 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004823
4824 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004825 if (E->getOpcode() == BO_Sub)
4826 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004827
Ted Kremenek28831752012-08-23 20:46:57 +00004828 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004829 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4830 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004831}
Eli Friedman9a156e52008-11-12 09:44:48 +00004832
John McCall45d55e42010-05-07 21:00:08 +00004833bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4834 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004835}
Mike Stump11289f42009-09-09 15:08:12 +00004836
Peter Collingbournee9200682011-05-13 03:29:01 +00004837bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4838 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004839
Eli Friedman847a2bc2009-12-27 05:43:15 +00004840 switch (E->getCastKind()) {
4841 default:
4842 break;
4843
John McCalle3027922010-08-25 11:45:40 +00004844 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004845 case CK_CPointerToObjCPointerCast:
4846 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004847 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004848 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004849 if (!Visit(SubExpr))
4850 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004851 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4852 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4853 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004854 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004855 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004856 if (SubExpr->getType()->isVoidPointerType())
4857 CCEDiag(E, diag::note_constexpr_invalid_cast)
4858 << 3 << SubExpr->getType();
4859 else
4860 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4861 }
Richard Smith96e0c102011-11-04 02:25:55 +00004862 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004863
Anders Carlsson18275092010-10-31 20:41:46 +00004864 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004865 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004866 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004867 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004868 if (!Result.Base && Result.Offset.isZero())
4869 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004870
Richard Smithd62306a2011-11-10 06:34:14 +00004871 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004872 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004873 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4874 castAs<PointerType>()->getPointeeType(),
4875 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004876
Richard Smith027bf112011-11-17 22:56:20 +00004877 case CK_BaseToDerived:
4878 if (!Visit(E->getSubExpr()))
4879 return false;
4880 if (!Result.Base && Result.Offset.isZero())
4881 return true;
4882 return HandleBaseToDerivedCast(Info, E, Result);
4883
Richard Smith0b0a0b62011-10-29 20:57:55 +00004884 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004885 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004886 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004887
John McCalle3027922010-08-25 11:45:40 +00004888 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004889 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4890
Richard Smith2e312c82012-03-03 22:46:17 +00004891 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004892 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004893 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004894
John McCall45d55e42010-05-07 21:00:08 +00004895 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004896 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4897 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004898 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004899 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004900 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004901 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004902 return true;
4903 } else {
4904 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004905 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004906 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004907 }
4908 }
John McCalle3027922010-08-25 11:45:40 +00004909 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004910 if (SubExpr->isGLValue()) {
4911 if (!EvaluateLValue(SubExpr, Result, Info))
4912 return false;
4913 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004914 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004915 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004916 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004917 return false;
4918 }
Richard Smith96e0c102011-11-04 02:25:55 +00004919 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004920 if (const ConstantArrayType *CAT
4921 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4922 Result.addArray(Info, E, CAT);
4923 else
4924 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004925 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004926
John McCalle3027922010-08-25 11:45:40 +00004927 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004928 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004929 }
4930
Richard Smith11562c52011-10-28 17:51:58 +00004931 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004932}
Chris Lattner05706e882008-07-11 18:11:29 +00004933
Hal Finkel0dd05d42014-10-03 17:18:37 +00004934static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4935 // C++ [expr.alignof]p3:
4936 // When alignof is applied to a reference type, the result is the
4937 // alignment of the referenced type.
4938 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4939 T = Ref->getPointeeType();
4940
4941 // __alignof is defined to return the preferred alignment.
4942 return Info.Ctx.toCharUnitsFromBits(
4943 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4944}
4945
4946static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4947 E = E->IgnoreParens();
4948
4949 // The kinds of expressions that we have special-case logic here for
4950 // should be kept up to date with the special checks for those
4951 // expressions in Sema.
4952
4953 // alignof decl is always accepted, even if it doesn't make sense: we default
4954 // to 1 in those cases.
4955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4956 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4957 /*RefAsPointee*/true);
4958
4959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4960 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4961 /*RefAsPointee*/true);
4962
4963 return GetAlignOfType(Info, E->getType());
4964}
4965
Peter Collingbournee9200682011-05-13 03:29:01 +00004966bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004967 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004968 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004969
Alp Tokera724cff2013-12-28 21:59:02 +00004970 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004971 case Builtin::BI__builtin_addressof:
4972 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00004973 case Builtin::BI__builtin_assume_aligned: {
4974 // We need to be very careful here because: if the pointer does not have the
4975 // asserted alignment, then the behavior is undefined, and undefined
4976 // behavior is non-constant.
4977 if (!EvaluatePointer(E->getArg(0), Result, Info))
4978 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00004979
Hal Finkel0dd05d42014-10-03 17:18:37 +00004980 LValue OffsetResult(Result);
4981 APSInt Alignment;
4982 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4983 return false;
4984 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4985
4986 if (E->getNumArgs() > 2) {
4987 APSInt Offset;
4988 if (!EvaluateInteger(E->getArg(2), Offset, Info))
4989 return false;
4990
4991 int64_t AdditionalOffset = -getExtValue(Offset);
4992 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4993 }
4994
4995 // If there is a base object, then it must have the correct alignment.
4996 if (OffsetResult.Base) {
4997 CharUnits BaseAlignment;
4998 if (const ValueDecl *VD =
4999 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5000 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5001 } else {
5002 BaseAlignment =
5003 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5004 }
5005
5006 if (BaseAlignment < Align) {
5007 Result.Designator.setInvalid();
5008 // FIXME: Quantities here cast to integers because the plural modifier
5009 // does not work on APSInts yet.
5010 CCEDiag(E->getArg(0),
5011 diag::note_constexpr_baa_insufficient_alignment) << 0
5012 << (int) BaseAlignment.getQuantity()
5013 << (unsigned) getExtValue(Alignment);
5014 return false;
5015 }
5016 }
5017
5018 // The offset must also have the correct alignment.
5019 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5020 Result.Designator.setInvalid();
5021 APSInt Offset(64, false);
5022 Offset = OffsetResult.Offset.getQuantity();
5023
5024 if (OffsetResult.Base)
5025 CCEDiag(E->getArg(0),
5026 diag::note_constexpr_baa_insufficient_alignment) << 1
5027 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5028 else
5029 CCEDiag(E->getArg(0),
5030 diag::note_constexpr_baa_value_insufficient_alignment)
5031 << Offset << (unsigned) getExtValue(Alignment);
5032
5033 return false;
5034 }
5035
5036 return true;
5037 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005038 default:
5039 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5040 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005041}
Chris Lattner05706e882008-07-11 18:11:29 +00005042
5043//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005044// Member Pointer Evaluation
5045//===----------------------------------------------------------------------===//
5046
5047namespace {
5048class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005049 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005050 MemberPtr &Result;
5051
5052 bool Success(const ValueDecl *D) {
5053 Result = MemberPtr(D);
5054 return true;
5055 }
5056public:
5057
5058 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5059 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5060
Richard Smith2e312c82012-03-03 22:46:17 +00005061 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005062 Result.setFrom(V);
5063 return true;
5064 }
Richard Smithfddd3842011-12-30 21:15:51 +00005065 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005066 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005067 }
5068
5069 bool VisitCastExpr(const CastExpr *E);
5070 bool VisitUnaryAddrOf(const UnaryOperator *E);
5071};
5072} // end anonymous namespace
5073
5074static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5075 EvalInfo &Info) {
5076 assert(E->isRValue() && E->getType()->isMemberPointerType());
5077 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5078}
5079
5080bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5081 switch (E->getCastKind()) {
5082 default:
5083 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5084
5085 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005086 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005087 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005088
5089 case CK_BaseToDerivedMemberPointer: {
5090 if (!Visit(E->getSubExpr()))
5091 return false;
5092 if (E->path_empty())
5093 return true;
5094 // Base-to-derived member pointer casts store the path in derived-to-base
5095 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5096 // the wrong end of the derived->base arc, so stagger the path by one class.
5097 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5098 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5099 PathI != PathE; ++PathI) {
5100 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5101 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5102 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005103 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005104 }
5105 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5106 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005107 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005108 return true;
5109 }
5110
5111 case CK_DerivedToBaseMemberPointer:
5112 if (!Visit(E->getSubExpr()))
5113 return false;
5114 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5115 PathE = E->path_end(); PathI != PathE; ++PathI) {
5116 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5117 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5118 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005119 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005120 }
5121 return true;
5122 }
5123}
5124
5125bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5126 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5127 // member can be formed.
5128 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5129}
5130
5131//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005132// Record Evaluation
5133//===----------------------------------------------------------------------===//
5134
5135namespace {
5136 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005137 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005138 const LValue &This;
5139 APValue &Result;
5140 public:
5141
5142 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5143 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5144
Richard Smith2e312c82012-03-03 22:46:17 +00005145 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005146 Result = V;
5147 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005148 }
Richard Smithfddd3842011-12-30 21:15:51 +00005149 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005150
Richard Smithe97cbd72011-11-11 04:05:33 +00005151 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005152 bool VisitInitListExpr(const InitListExpr *E);
5153 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005154 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005155 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005156}
Richard Smithd62306a2011-11-10 06:34:14 +00005157
Richard Smithfddd3842011-12-30 21:15:51 +00005158/// Perform zero-initialization on an object of non-union class type.
5159/// C++11 [dcl.init]p5:
5160/// To zero-initialize an object or reference of type T means:
5161/// [...]
5162/// -- if T is a (possibly cv-qualified) non-union class type,
5163/// each non-static data member and each base-class subobject is
5164/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005165static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5166 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005167 const LValue &This, APValue &Result) {
5168 assert(!RD->isUnion() && "Expected non-union class type");
5169 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5170 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005171 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005172
John McCalld7bca762012-05-01 00:38:49 +00005173 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005174 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5175
5176 if (CD) {
5177 unsigned Index = 0;
5178 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005179 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005180 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5181 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005182 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5183 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005184 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005185 Result.getStructBase(Index)))
5186 return false;
5187 }
5188 }
5189
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005190 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005191 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005192 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005193 continue;
5194
5195 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005196 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005197 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005198
David Blaikie2d7c57e2012-04-30 02:36:29 +00005199 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005200 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005201 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005202 return false;
5203 }
5204
5205 return true;
5206}
5207
5208bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5209 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005210 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005211 if (RD->isUnion()) {
5212 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5213 // object's first non-static named data member is zero-initialized
5214 RecordDecl::field_iterator I = RD->field_begin();
5215 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005216 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005217 return true;
5218 }
5219
5220 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005221 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005222 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005223 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005224 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005225 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005226 }
5227
Richard Smith5d108602012-02-17 00:44:16 +00005228 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005229 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005230 return false;
5231 }
5232
Richard Smitha8105bc2012-01-06 16:39:00 +00005233 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005234}
5235
Richard Smithe97cbd72011-11-11 04:05:33 +00005236bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5237 switch (E->getCastKind()) {
5238 default:
5239 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5240
5241 case CK_ConstructorConversion:
5242 return Visit(E->getSubExpr());
5243
5244 case CK_DerivedToBase:
5245 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005246 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005247 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005248 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005249 if (!DerivedObject.isStruct())
5250 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005251
5252 // Derived-to-base rvalue conversion: just slice off the derived part.
5253 APValue *Value = &DerivedObject;
5254 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5255 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5256 PathE = E->path_end(); PathI != PathE; ++PathI) {
5257 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5258 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5259 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5260 RD = Base;
5261 }
5262 Result = *Value;
5263 return true;
5264 }
5265 }
5266}
5267
Richard Smithd62306a2011-11-10 06:34:14 +00005268bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5269 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005270 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005271 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5272
5273 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005274 const FieldDecl *Field = E->getInitializedFieldInUnion();
5275 Result = APValue(Field);
5276 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005277 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005278
5279 // If the initializer list for a union does not contain any elements, the
5280 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005281 // FIXME: The element should be initialized from an initializer list.
5282 // Is this difference ever observable for initializer lists which
5283 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005284 ImplicitValueInitExpr VIE(Field->getType());
5285 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5286
Richard Smithd62306a2011-11-10 06:34:14 +00005287 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005288 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5289 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005290
5291 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5292 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5293 isa<CXXDefaultInitExpr>(InitExpr));
5294
Richard Smithb228a862012-02-15 02:18:13 +00005295 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005296 }
5297
5298 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5299 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005300 Result = APValue(APValue::UninitStruct(), 0,
5301 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005302 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005303 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005304 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005305 // Anonymous bit-fields are not considered members of the class for
5306 // purposes of aggregate initialization.
5307 if (Field->isUnnamedBitfield())
5308 continue;
5309
5310 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005311
Richard Smith253c2a32012-01-27 01:14:48 +00005312 bool HaveInit = ElementNo < E->getNumInits();
5313
5314 // FIXME: Diagnostics here should point to the end of the initializer
5315 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005316 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005317 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005318 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005319
5320 // Perform an implicit value-initialization for members beyond the end of
5321 // the initializer list.
5322 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005323 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005324
Richard Smith852c9db2013-04-20 22:23:05 +00005325 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5326 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5327 isa<CXXDefaultInitExpr>(Init));
5328
Richard Smith49ca8aa2013-08-06 07:09:20 +00005329 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5330 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5331 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005332 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005333 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005334 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005335 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005336 }
5337 }
5338
Richard Smith253c2a32012-01-27 01:14:48 +00005339 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005340}
5341
5342bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5343 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005344 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5345
Richard Smithfddd3842011-12-30 21:15:51 +00005346 bool ZeroInit = E->requiresZeroInitialization();
5347 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005348 // If we've already performed zero-initialization, we're already done.
5349 if (!Result.isUninit())
5350 return true;
5351
Richard Smithda3f4fd2014-03-05 23:32:50 +00005352 // We can get here in two different ways:
5353 // 1) We're performing value-initialization, and should zero-initialize
5354 // the object, or
5355 // 2) We're performing default-initialization of an object with a trivial
5356 // constexpr default constructor, in which case we should start the
5357 // lifetimes of all the base subobjects (there can be no data member
5358 // subobjects in this case) per [basic.life]p1.
5359 // Either way, ZeroInitialization is appropriate.
5360 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005361 }
5362
Craig Topper36250ad2014-05-12 05:36:57 +00005363 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005364 FD->getBody(Definition);
5365
Richard Smith357362d2011-12-13 06:39:58 +00005366 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5367 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005368
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005369 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005370 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005371 if (const MaterializeTemporaryExpr *ME
5372 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5373 return Visit(ME->GetTemporaryExpr());
5374
Richard Smithfddd3842011-12-30 21:15:51 +00005375 if (ZeroInit && !ZeroInitialization(E))
5376 return false;
5377
Craig Topper5fc8fc22014-08-27 06:28:36 +00005378 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005379 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005380 cast<CXXConstructorDecl>(Definition), Info,
5381 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005382}
5383
Richard Smithcc1b96d2013-06-12 22:31:48 +00005384bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5385 const CXXStdInitializerListExpr *E) {
5386 const ConstantArrayType *ArrayType =
5387 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5388
5389 LValue Array;
5390 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5391 return false;
5392
5393 // Get a pointer to the first element of the array.
5394 Array.addArray(Info, E, ArrayType);
5395
5396 // FIXME: Perform the checks on the field types in SemaInit.
5397 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5398 RecordDecl::field_iterator Field = Record->field_begin();
5399 if (Field == Record->field_end())
5400 return Error(E);
5401
5402 // Start pointer.
5403 if (!Field->getType()->isPointerType() ||
5404 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5405 ArrayType->getElementType()))
5406 return Error(E);
5407
5408 // FIXME: What if the initializer_list type has base classes, etc?
5409 Result = APValue(APValue::UninitStruct(), 0, 2);
5410 Array.moveInto(Result.getStructField(0));
5411
5412 if (++Field == Record->field_end())
5413 return Error(E);
5414
5415 if (Field->getType()->isPointerType() &&
5416 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5417 ArrayType->getElementType())) {
5418 // End pointer.
5419 if (!HandleLValueArrayAdjustment(Info, E, Array,
5420 ArrayType->getElementType(),
5421 ArrayType->getSize().getZExtValue()))
5422 return false;
5423 Array.moveInto(Result.getStructField(1));
5424 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5425 // Length.
5426 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5427 else
5428 return Error(E);
5429
5430 if (++Field != Record->field_end())
5431 return Error(E);
5432
5433 return true;
5434}
5435
Richard Smithd62306a2011-11-10 06:34:14 +00005436static bool EvaluateRecord(const Expr *E, const LValue &This,
5437 APValue &Result, EvalInfo &Info) {
5438 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005439 "can't evaluate expression as a record rvalue");
5440 return RecordExprEvaluator(Info, This, Result).Visit(E);
5441}
5442
5443//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005444// Temporary Evaluation
5445//
5446// Temporaries are represented in the AST as rvalues, but generally behave like
5447// lvalues. The full-object of which the temporary is a subobject is implicitly
5448// materialized so that a reference can bind to it.
5449//===----------------------------------------------------------------------===//
5450namespace {
5451class TemporaryExprEvaluator
5452 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5453public:
5454 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5455 LValueExprEvaluatorBaseTy(Info, Result) {}
5456
5457 /// Visit an expression which constructs the value of this temporary.
5458 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005459 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005460 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5461 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005462 }
5463
5464 bool VisitCastExpr(const CastExpr *E) {
5465 switch (E->getCastKind()) {
5466 default:
5467 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5468
5469 case CK_ConstructorConversion:
5470 return VisitConstructExpr(E->getSubExpr());
5471 }
5472 }
5473 bool VisitInitListExpr(const InitListExpr *E) {
5474 return VisitConstructExpr(E);
5475 }
5476 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5477 return VisitConstructExpr(E);
5478 }
5479 bool VisitCallExpr(const CallExpr *E) {
5480 return VisitConstructExpr(E);
5481 }
Richard Smith513955c2014-12-17 19:24:30 +00005482 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5483 return VisitConstructExpr(E);
5484 }
Richard Smith027bf112011-11-17 22:56:20 +00005485};
5486} // end anonymous namespace
5487
5488/// Evaluate an expression of record type as a temporary.
5489static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005490 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005491 return TemporaryExprEvaluator(Info, Result).Visit(E);
5492}
5493
5494//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005495// Vector Evaluation
5496//===----------------------------------------------------------------------===//
5497
5498namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005499 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005500 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005501 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005502 public:
Mike Stump11289f42009-09-09 15:08:12 +00005503
Richard Smith2d406342011-10-22 21:10:00 +00005504 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5505 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005506
Richard Smith2d406342011-10-22 21:10:00 +00005507 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5508 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5509 // FIXME: remove this APValue copy.
5510 Result = APValue(V.data(), V.size());
5511 return true;
5512 }
Richard Smith2e312c82012-03-03 22:46:17 +00005513 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005514 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005515 Result = V;
5516 return true;
5517 }
Richard Smithfddd3842011-12-30 21:15:51 +00005518 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005519
Richard Smith2d406342011-10-22 21:10:00 +00005520 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005521 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005522 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005523 bool VisitInitListExpr(const InitListExpr *E);
5524 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005525 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005526 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005527 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005528 };
5529} // end anonymous namespace
5530
5531static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005532 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005533 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005534}
5535
Richard Smith2d406342011-10-22 21:10:00 +00005536bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5537 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005538 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005539
Richard Smith161f09a2011-12-06 22:44:34 +00005540 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005541 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005542
Eli Friedmanc757de22011-03-25 00:43:55 +00005543 switch (E->getCastKind()) {
5544 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005545 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005546 if (SETy->isIntegerType()) {
5547 APSInt IntResult;
5548 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005549 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005550 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005551 } else if (SETy->isRealFloatingType()) {
5552 APFloat F(0.0);
5553 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005554 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005555 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005556 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005557 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005558 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005559
5560 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005561 SmallVector<APValue, 4> Elts(NElts, Val);
5562 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005563 }
Eli Friedman803acb32011-12-22 03:51:45 +00005564 case CK_BitCast: {
5565 // Evaluate the operand into an APInt we can extract from.
5566 llvm::APInt SValInt;
5567 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5568 return false;
5569 // Extract the elements
5570 QualType EltTy = VTy->getElementType();
5571 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5572 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5573 SmallVector<APValue, 4> Elts;
5574 if (EltTy->isRealFloatingType()) {
5575 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005576 unsigned FloatEltSize = EltSize;
5577 if (&Sem == &APFloat::x87DoubleExtended)
5578 FloatEltSize = 80;
5579 for (unsigned i = 0; i < NElts; i++) {
5580 llvm::APInt Elt;
5581 if (BigEndian)
5582 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5583 else
5584 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005585 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005586 }
5587 } else if (EltTy->isIntegerType()) {
5588 for (unsigned i = 0; i < NElts; i++) {
5589 llvm::APInt Elt;
5590 if (BigEndian)
5591 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5592 else
5593 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5594 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5595 }
5596 } else {
5597 return Error(E);
5598 }
5599 return Success(Elts, E);
5600 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005601 default:
Richard Smith11562c52011-10-28 17:51:58 +00005602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005603 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005604}
5605
Richard Smith2d406342011-10-22 21:10:00 +00005606bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005607VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005608 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005609 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005610 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005611
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005612 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005613 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005614
Eli Friedmanb9c71292012-01-03 23:24:20 +00005615 // The number of initializers can be less than the number of
5616 // vector elements. For OpenCL, this can be due to nested vector
5617 // initialization. For GCC compatibility, missing trailing elements
5618 // should be initialized with zeroes.
5619 unsigned CountInits = 0, CountElts = 0;
5620 while (CountElts < NumElements) {
5621 // Handle nested vector initialization.
5622 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005623 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005624 APValue v;
5625 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5626 return Error(E);
5627 unsigned vlen = v.getVectorLength();
5628 for (unsigned j = 0; j < vlen; j++)
5629 Elements.push_back(v.getVectorElt(j));
5630 CountElts += vlen;
5631 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005632 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005633 if (CountInits < NumInits) {
5634 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005635 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005636 } else // trailing integer zero.
5637 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5638 Elements.push_back(APValue(sInt));
5639 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005640 } else {
5641 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005642 if (CountInits < NumInits) {
5643 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005644 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005645 } else // trailing float zero.
5646 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5647 Elements.push_back(APValue(f));
5648 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005649 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005650 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005651 }
Richard Smith2d406342011-10-22 21:10:00 +00005652 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005653}
5654
Richard Smith2d406342011-10-22 21:10:00 +00005655bool
Richard Smithfddd3842011-12-30 21:15:51 +00005656VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005657 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005658 QualType EltTy = VT->getElementType();
5659 APValue ZeroElement;
5660 if (EltTy->isIntegerType())
5661 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5662 else
5663 ZeroElement =
5664 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5665
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005666 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005667 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005668}
5669
Richard Smith2d406342011-10-22 21:10:00 +00005670bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005671 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005672 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005673}
5674
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005675//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005676// Array Evaluation
5677//===----------------------------------------------------------------------===//
5678
5679namespace {
5680 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005681 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005682 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005683 APValue &Result;
5684 public:
5685
Richard Smithd62306a2011-11-10 06:34:14 +00005686 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5687 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005688
5689 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005690 assert((V.isArray() || V.isLValue()) &&
5691 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005692 Result = V;
5693 return true;
5694 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005695
Richard Smithfddd3842011-12-30 21:15:51 +00005696 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005697 const ConstantArrayType *CAT =
5698 Info.Ctx.getAsConstantArrayType(E->getType());
5699 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005700 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005701
5702 Result = APValue(APValue::UninitArray(), 0,
5703 CAT->getSize().getZExtValue());
5704 if (!Result.hasArrayFiller()) return true;
5705
Richard Smithfddd3842011-12-30 21:15:51 +00005706 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005707 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005708 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005709 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005710 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005711 }
5712
Richard Smithf3e9e432011-11-07 09:22:26 +00005713 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005714 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005715 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5716 const LValue &Subobject,
5717 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005718 };
5719} // end anonymous namespace
5720
Richard Smithd62306a2011-11-10 06:34:14 +00005721static bool EvaluateArray(const Expr *E, const LValue &This,
5722 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005723 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005724 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005725}
5726
5727bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5728 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5729 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005730 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005731
Richard Smithca2cfbf2011-12-22 01:07:19 +00005732 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5733 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005734 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005735 LValue LV;
5736 if (!EvaluateLValue(E->getInit(0), LV, Info))
5737 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005738 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005739 LV.moveInto(Val);
5740 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005741 }
5742
Richard Smith253c2a32012-01-27 01:14:48 +00005743 bool Success = true;
5744
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005745 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5746 "zero-initialized array shouldn't have any initialized elts");
5747 APValue Filler;
5748 if (Result.isArray() && Result.hasArrayFiller())
5749 Filler = Result.getArrayFiller();
5750
Richard Smith9543c5e2013-04-22 14:44:29 +00005751 unsigned NumEltsToInit = E->getNumInits();
5752 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005753 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005754
5755 // If the initializer might depend on the array index, run it for each
5756 // array element. For now, just whitelist non-class value-initialization.
5757 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5758 NumEltsToInit = NumElts;
5759
5760 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005761
5762 // If the array was previously zero-initialized, preserve the
5763 // zero-initialized values.
5764 if (!Filler.isUninit()) {
5765 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5766 Result.getArrayInitializedElt(I) = Filler;
5767 if (Result.hasArrayFiller())
5768 Result.getArrayFiller() = Filler;
5769 }
5770
Richard Smithd62306a2011-11-10 06:34:14 +00005771 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005772 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005773 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5774 const Expr *Init =
5775 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005776 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005777 Info, Subobject, Init) ||
5778 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005779 CAT->getElementType(), 1)) {
5780 if (!Info.keepEvaluatingAfterFailure())
5781 return false;
5782 Success = false;
5783 }
Richard Smithd62306a2011-11-10 06:34:14 +00005784 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005785
Richard Smith9543c5e2013-04-22 14:44:29 +00005786 if (!Result.hasArrayFiller())
5787 return Success;
5788
5789 // If we get here, we have a trivial filler, which we can just evaluate
5790 // once and splat over the rest of the array elements.
5791 assert(FillerExpr && "no array filler for incomplete init list");
5792 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5793 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005794}
5795
Richard Smith027bf112011-11-17 22:56:20 +00005796bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005797 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5798}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005799
Richard Smith9543c5e2013-04-22 14:44:29 +00005800bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5801 const LValue &Subobject,
5802 APValue *Value,
5803 QualType Type) {
5804 bool HadZeroInit = !Value->isUninit();
5805
5806 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5807 unsigned N = CAT->getSize().getZExtValue();
5808
5809 // Preserve the array filler if we had prior zero-initialization.
5810 APValue Filler =
5811 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5812 : APValue();
5813
5814 *Value = APValue(APValue::UninitArray(), N, N);
5815
5816 if (HadZeroInit)
5817 for (unsigned I = 0; I != N; ++I)
5818 Value->getArrayInitializedElt(I) = Filler;
5819
5820 // Initialize the elements.
5821 LValue ArrayElt = Subobject;
5822 ArrayElt.addArray(Info, E, CAT);
5823 for (unsigned I = 0; I != N; ++I)
5824 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5825 CAT->getElementType()) ||
5826 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5827 CAT->getElementType(), 1))
5828 return false;
5829
5830 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005831 }
Richard Smith027bf112011-11-17 22:56:20 +00005832
Richard Smith9543c5e2013-04-22 14:44:29 +00005833 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005834 return Error(E);
5835
Richard Smith027bf112011-11-17 22:56:20 +00005836 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005837
Richard Smithfddd3842011-12-30 21:15:51 +00005838 bool ZeroInit = E->requiresZeroInitialization();
5839 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005840 if (HadZeroInit)
5841 return true;
5842
Richard Smithda3f4fd2014-03-05 23:32:50 +00005843 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5844 ImplicitValueInitExpr VIE(Type);
5845 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005846 }
5847
Craig Topper36250ad2014-05-12 05:36:57 +00005848 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005849 FD->getBody(Definition);
5850
Richard Smith357362d2011-12-13 06:39:58 +00005851 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5852 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005853
Richard Smith9eae7232012-01-12 18:54:33 +00005854 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005855 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005856 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005857 return false;
5858 }
5859
Craig Topper5fc8fc22014-08-27 06:28:36 +00005860 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005861 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005862 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005863 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005864}
5865
Richard Smithf3e9e432011-11-07 09:22:26 +00005866//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005867// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005868//
5869// As a GNU extension, we support casting pointers to sufficiently-wide integer
5870// types and back in constant folding. Integer values are thus represented
5871// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005872//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005873
5874namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005875class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005876 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005877 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005878public:
Richard Smith2e312c82012-03-03 22:46:17 +00005879 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005880 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005881
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005882 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005883 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005884 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005885 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005886 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005887 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005888 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005889 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005890 return true;
5891 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005892 bool Success(const llvm::APSInt &SI, const Expr *E) {
5893 return Success(SI, E, Result);
5894 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005895
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005896 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005897 assert(E->getType()->isIntegralOrEnumerationType() &&
5898 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005899 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005900 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005901 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005902 Result.getInt().setIsUnsigned(
5903 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005904 return true;
5905 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005906 bool Success(const llvm::APInt &I, const Expr *E) {
5907 return Success(I, E, Result);
5908 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005909
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005910 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005911 assert(E->getType()->isIntegralOrEnumerationType() &&
5912 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005913 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005914 return true;
5915 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005916 bool Success(uint64_t Value, const Expr *E) {
5917 return Success(Value, E, Result);
5918 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005919
Ken Dyckdbc01912011-03-11 02:13:43 +00005920 bool Success(CharUnits Size, const Expr *E) {
5921 return Success(Size.getQuantity(), E);
5922 }
5923
Richard Smith2e312c82012-03-03 22:46:17 +00005924 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005925 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005926 Result = V;
5927 return true;
5928 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005929 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005930 }
Mike Stump11289f42009-09-09 15:08:12 +00005931
Richard Smithfddd3842011-12-30 21:15:51 +00005932 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005933
Peter Collingbournee9200682011-05-13 03:29:01 +00005934 //===--------------------------------------------------------------------===//
5935 // Visitor Methods
5936 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005937
Chris Lattner7174bf32008-07-12 00:38:25 +00005938 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005939 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005940 }
5941 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005942 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005943 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005944
5945 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5946 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005947 if (CheckReferencedDecl(E, E->getDecl()))
5948 return true;
5949
5950 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005951 }
5952 bool VisitMemberExpr(const MemberExpr *E) {
5953 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005954 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005955 return true;
5956 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005957
5958 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005959 }
5960
Peter Collingbournee9200682011-05-13 03:29:01 +00005961 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005962 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005963 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005964 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005965
Peter Collingbournee9200682011-05-13 03:29:01 +00005966 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005967 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005968
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005969 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005970 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005971 }
Mike Stump11289f42009-09-09 15:08:12 +00005972
Ted Kremeneke65b0862012-03-06 20:05:56 +00005973 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5974 return Success(E->getValue(), E);
5975 }
5976
Richard Smith4ce706a2011-10-11 21:43:33 +00005977 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005978 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005979 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005980 }
5981
Douglas Gregor29c42f22012-02-24 07:38:34 +00005982 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5983 return Success(E->getValue(), E);
5984 }
5985
John Wiegley6242b6a2011-04-28 00:16:57 +00005986 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5987 return Success(E->getValue(), E);
5988 }
5989
John Wiegleyf9f65842011-04-25 06:54:41 +00005990 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5991 return Success(E->getValue(), E);
5992 }
5993
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005994 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005995 bool VisitUnaryImag(const UnaryOperator *E);
5996
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005997 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005998 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005999
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006000private:
Richard Smithce40ad62011-11-12 22:28:03 +00006001 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00006002 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006003 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006004};
Chris Lattner05706e882008-07-11 18:11:29 +00006005} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006006
Richard Smith11562c52011-10-28 17:51:58 +00006007/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6008/// produce either the integer value or a pointer.
6009///
6010/// GCC has a heinous extension which folds casts between pointer types and
6011/// pointer-sized integral types. We support this by allowing the evaluation of
6012/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6013/// Some simple arithmetic on such values is supported (they are treated much
6014/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006015static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006016 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006017 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006018 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006019}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006020
Richard Smithf57d8cb2011-12-09 22:58:01 +00006021static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006022 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006023 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006024 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006025 if (!Val.isInt()) {
6026 // FIXME: It would be better to produce the diagnostic for casting
6027 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006028 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006029 return false;
6030 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006031 Result = Val.getInt();
6032 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006033}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006034
Richard Smithf57d8cb2011-12-09 22:58:01 +00006035/// Check whether the given declaration can be directly converted to an integral
6036/// rvalue. If not, no diagnostic is produced; there are other things we can
6037/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006038bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006039 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006040 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006041 // Check for signedness/width mismatches between E type and ECD value.
6042 bool SameSign = (ECD->getInitVal().isSigned()
6043 == E->getType()->isSignedIntegerOrEnumerationType());
6044 bool SameWidth = (ECD->getInitVal().getBitWidth()
6045 == Info.Ctx.getIntWidth(E->getType()));
6046 if (SameSign && SameWidth)
6047 return Success(ECD->getInitVal(), E);
6048 else {
6049 // Get rid of mismatch (otherwise Success assertions will fail)
6050 // by computing a new value matching the type of E.
6051 llvm::APSInt Val = ECD->getInitVal();
6052 if (!SameSign)
6053 Val.setIsSigned(!ECD->getInitVal().isSigned());
6054 if (!SameWidth)
6055 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6056 return Success(Val, E);
6057 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006058 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006059 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006060}
6061
Chris Lattner86ee2862008-10-06 06:40:35 +00006062/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6063/// as GCC.
6064static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6065 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006066 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006067 enum gcc_type_class {
6068 no_type_class = -1,
6069 void_type_class, integer_type_class, char_type_class,
6070 enumeral_type_class, boolean_type_class,
6071 pointer_type_class, reference_type_class, offset_type_class,
6072 real_type_class, complex_type_class,
6073 function_type_class, method_type_class,
6074 record_type_class, union_type_class,
6075 array_type_class, string_type_class,
6076 lang_type_class
6077 };
Mike Stump11289f42009-09-09 15:08:12 +00006078
6079 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006080 // ideal, however it is what gcc does.
6081 if (E->getNumArgs() == 0)
6082 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006083
Chris Lattner86ee2862008-10-06 06:40:35 +00006084 QualType ArgTy = E->getArg(0)->getType();
6085 if (ArgTy->isVoidType())
6086 return void_type_class;
6087 else if (ArgTy->isEnumeralType())
6088 return enumeral_type_class;
6089 else if (ArgTy->isBooleanType())
6090 return boolean_type_class;
6091 else if (ArgTy->isCharType())
6092 return string_type_class; // gcc doesn't appear to use char_type_class
6093 else if (ArgTy->isIntegerType())
6094 return integer_type_class;
6095 else if (ArgTy->isPointerType())
6096 return pointer_type_class;
6097 else if (ArgTy->isReferenceType())
6098 return reference_type_class;
6099 else if (ArgTy->isRealType())
6100 return real_type_class;
6101 else if (ArgTy->isComplexType())
6102 return complex_type_class;
6103 else if (ArgTy->isFunctionType())
6104 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006105 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006106 return record_type_class;
6107 else if (ArgTy->isUnionType())
6108 return union_type_class;
6109 else if (ArgTy->isArrayType())
6110 return array_type_class;
6111 else if (ArgTy->isUnionType())
6112 return union_type_class;
6113 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006114 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006115}
6116
Richard Smith5fab0c92011-12-28 19:48:30 +00006117/// EvaluateBuiltinConstantPForLValue - Determine the result of
6118/// __builtin_constant_p when applied to the given lvalue.
6119///
6120/// An lvalue is only "constant" if it is a pointer or reference to the first
6121/// character of a string literal.
6122template<typename LValue>
6123static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006124 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006125 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6126}
6127
6128/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6129/// GCC as we can manage.
6130static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6131 QualType ArgType = Arg->getType();
6132
6133 // __builtin_constant_p always has one operand. The rules which gcc follows
6134 // are not precisely documented, but are as follows:
6135 //
6136 // - If the operand is of integral, floating, complex or enumeration type,
6137 // and can be folded to a known value of that type, it returns 1.
6138 // - If the operand and can be folded to a pointer to the first character
6139 // of a string literal (or such a pointer cast to an integral type), it
6140 // returns 1.
6141 //
6142 // Otherwise, it returns 0.
6143 //
6144 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6145 // its support for this does not currently work.
6146 if (ArgType->isIntegralOrEnumerationType()) {
6147 Expr::EvalResult Result;
6148 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6149 return false;
6150
6151 APValue &V = Result.Val;
6152 if (V.getKind() == APValue::Int)
6153 return true;
6154
6155 return EvaluateBuiltinConstantPForLValue(V);
6156 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6157 return Arg->isEvaluatable(Ctx);
6158 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6159 LValue LV;
6160 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006161 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006162 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6163 : EvaluatePointer(Arg, LV, Info)) &&
6164 !Status.HasSideEffects)
6165 return EvaluateBuiltinConstantPForLValue(LV);
6166 }
6167
6168 // Anything else isn't considered to be sufficiently constant.
6169 return false;
6170}
6171
John McCall95007602010-05-10 23:27:23 +00006172/// Retrieves the "underlying object type" of the given expression,
6173/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00006174QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6175 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6176 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006177 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006178 } else if (const Expr *E = B.get<const Expr*>()) {
6179 if (isa<CompoundLiteralExpr>(E))
6180 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006181 }
6182
6183 return QualType();
6184}
6185
Peter Collingbournee9200682011-05-13 03:29:01 +00006186bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00006187 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006188
6189 {
6190 // The operand of __builtin_object_size is never evaluated for side-effects.
6191 // If there are any, but we can determine the pointed-to object anyway, then
6192 // ignore the side-effects.
6193 SpeculativeEvaluationRAII SpeculativeEval(Info);
6194 if (!EvaluatePointer(E->getArg(0), Base, Info))
6195 return false;
6196 }
John McCall95007602010-05-10 23:27:23 +00006197
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006198 if (!Base.getLValueBase()) {
6199 // It is not possible to determine which objects ptr points to at compile time,
6200 // __builtin_object_size should return (size_t) -1 for type 0 or 1
6201 // and (size_t) 0 for type 2 or 3.
6202 llvm::APSInt TypeIntVaue;
6203 const Expr *ExprType = E->getArg(1);
6204 if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6205 return false;
6206 if (TypeIntVaue == 0 || TypeIntVaue == 1)
6207 return Success(-1, E);
6208 if (TypeIntVaue == 2 || TypeIntVaue == 3)
6209 return Success(0, E);
6210 return Error(E);
6211 }
John McCall95007602010-05-10 23:27:23 +00006212
Richard Smithce40ad62011-11-12 22:28:03 +00006213 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00006214 if (T.isNull() ||
6215 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00006216 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00006217 T->isVariablyModifiedType() ||
6218 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006219 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006220
6221 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6222 CharUnits Offset = Base.getLValueOffset();
6223
6224 if (!Offset.isNegative() && Offset <= Size)
6225 Size -= Offset;
6226 else
6227 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00006228 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00006229}
6230
Peter Collingbournee9200682011-05-13 03:29:01 +00006231bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006232 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006233 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006234 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006235
6236 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006237 if (TryEvaluateBuiltinObjectSize(E))
6238 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006239
Richard Smith0421ce72012-08-07 04:16:51 +00006240 // If evaluating the argument has side-effects, we can't determine the size
6241 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6242 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006243 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006244 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006245 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006246 return Success(0, E);
6247 }
Mike Stump876387b2009-10-27 22:09:17 +00006248
Richard Smith01ade172012-05-23 04:13:20 +00006249 // Expression had no side effects, but we couldn't statically determine the
6250 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006251 switch (Info.EvalMode) {
6252 case EvalInfo::EM_ConstantExpression:
6253 case EvalInfo::EM_PotentialConstantExpression:
6254 case EvalInfo::EM_ConstantFold:
6255 case EvalInfo::EM_EvaluateForOverflow:
6256 case EvalInfo::EM_IgnoreSideEffects:
6257 return Error(E);
6258 case EvalInfo::EM_ConstantExpressionUnevaluated:
6259 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6260 return Success(-1ULL, E);
6261 }
Mike Stump722cedf2009-10-26 18:35:08 +00006262 }
6263
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006264 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006265 case Builtin::BI__builtin_bswap32:
6266 case Builtin::BI__builtin_bswap64: {
6267 APSInt Val;
6268 if (!EvaluateInteger(E->getArg(0), Val, Info))
6269 return false;
6270
6271 return Success(Val.byteSwap(), E);
6272 }
6273
Richard Smith8889a3d2013-06-13 06:26:32 +00006274 case Builtin::BI__builtin_classify_type:
6275 return Success(EvaluateBuiltinClassifyType(E), E);
6276
6277 // FIXME: BI__builtin_clrsb
6278 // FIXME: BI__builtin_clrsbl
6279 // FIXME: BI__builtin_clrsbll
6280
Richard Smith80b3c8e2013-06-13 05:04:16 +00006281 case Builtin::BI__builtin_clz:
6282 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006283 case Builtin::BI__builtin_clzll:
6284 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006285 APSInt Val;
6286 if (!EvaluateInteger(E->getArg(0), Val, Info))
6287 return false;
6288 if (!Val)
6289 return Error(E);
6290
6291 return Success(Val.countLeadingZeros(), E);
6292 }
6293
Richard Smith8889a3d2013-06-13 06:26:32 +00006294 case Builtin::BI__builtin_constant_p:
6295 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6296
Richard Smith80b3c8e2013-06-13 05:04:16 +00006297 case Builtin::BI__builtin_ctz:
6298 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006299 case Builtin::BI__builtin_ctzll:
6300 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006301 APSInt Val;
6302 if (!EvaluateInteger(E->getArg(0), Val, Info))
6303 return false;
6304 if (!Val)
6305 return Error(E);
6306
6307 return Success(Val.countTrailingZeros(), E);
6308 }
6309
Richard Smith8889a3d2013-06-13 06:26:32 +00006310 case Builtin::BI__builtin_eh_return_data_regno: {
6311 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6312 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6313 return Success(Operand, E);
6314 }
6315
6316 case Builtin::BI__builtin_expect:
6317 return Visit(E->getArg(0));
6318
6319 case Builtin::BI__builtin_ffs:
6320 case Builtin::BI__builtin_ffsl:
6321 case Builtin::BI__builtin_ffsll: {
6322 APSInt Val;
6323 if (!EvaluateInteger(E->getArg(0), Val, Info))
6324 return false;
6325
6326 unsigned N = Val.countTrailingZeros();
6327 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6328 }
6329
6330 case Builtin::BI__builtin_fpclassify: {
6331 APFloat Val(0.0);
6332 if (!EvaluateFloat(E->getArg(5), Val, Info))
6333 return false;
6334 unsigned Arg;
6335 switch (Val.getCategory()) {
6336 case APFloat::fcNaN: Arg = 0; break;
6337 case APFloat::fcInfinity: Arg = 1; break;
6338 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6339 case APFloat::fcZero: Arg = 4; break;
6340 }
6341 return Visit(E->getArg(Arg));
6342 }
6343
6344 case Builtin::BI__builtin_isinf_sign: {
6345 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006346 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006347 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6348 }
6349
Richard Smithea3019d2013-10-15 19:07:14 +00006350 case Builtin::BI__builtin_isinf: {
6351 APFloat Val(0.0);
6352 return EvaluateFloat(E->getArg(0), Val, Info) &&
6353 Success(Val.isInfinity() ? 1 : 0, E);
6354 }
6355
6356 case Builtin::BI__builtin_isfinite: {
6357 APFloat Val(0.0);
6358 return EvaluateFloat(E->getArg(0), Val, Info) &&
6359 Success(Val.isFinite() ? 1 : 0, E);
6360 }
6361
6362 case Builtin::BI__builtin_isnan: {
6363 APFloat Val(0.0);
6364 return EvaluateFloat(E->getArg(0), Val, Info) &&
6365 Success(Val.isNaN() ? 1 : 0, E);
6366 }
6367
6368 case Builtin::BI__builtin_isnormal: {
6369 APFloat Val(0.0);
6370 return EvaluateFloat(E->getArg(0), Val, Info) &&
6371 Success(Val.isNormal() ? 1 : 0, E);
6372 }
6373
Richard Smith8889a3d2013-06-13 06:26:32 +00006374 case Builtin::BI__builtin_parity:
6375 case Builtin::BI__builtin_parityl:
6376 case Builtin::BI__builtin_parityll: {
6377 APSInt Val;
6378 if (!EvaluateInteger(E->getArg(0), Val, Info))
6379 return false;
6380
6381 return Success(Val.countPopulation() % 2, E);
6382 }
6383
Richard Smith80b3c8e2013-06-13 05:04:16 +00006384 case Builtin::BI__builtin_popcount:
6385 case Builtin::BI__builtin_popcountl:
6386 case Builtin::BI__builtin_popcountll: {
6387 APSInt Val;
6388 if (!EvaluateInteger(E->getArg(0), Val, Info))
6389 return false;
6390
6391 return Success(Val.countPopulation(), E);
6392 }
6393
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006394 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006395 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006396 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006397 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006398 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6399 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006400 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006401 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006402 case Builtin::BI__builtin_strlen: {
6403 // As an extension, we support __builtin_strlen() as a constant expression,
6404 // and support folding strlen() to a constant.
6405 LValue String;
6406 if (!EvaluatePointer(E->getArg(0), String, Info))
6407 return false;
6408
6409 // Fast path: if it's a string literal, search the string value.
6410 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6411 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006412 // The string literal may have embedded null characters. Find the first
6413 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006414 StringRef Str = S->getBytes();
6415 int64_t Off = String.Offset.getQuantity();
6416 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6417 S->getCharByteWidth() == 1) {
6418 Str = Str.substr(Off);
6419
6420 StringRef::size_type Pos = Str.find(0);
6421 if (Pos != StringRef::npos)
6422 Str = Str.substr(0, Pos);
6423
6424 return Success(Str.size(), E);
6425 }
6426
6427 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006428 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006429
6430 // Slow path: scan the bytes of the string looking for the terminating 0.
6431 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6432 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6433 APValue Char;
6434 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6435 !Char.isInt())
6436 return false;
6437 if (!Char.getInt())
6438 return Success(Strlen, E);
6439 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6440 return false;
6441 }
6442 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006443
Richard Smith01ba47d2012-04-13 00:45:38 +00006444 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006445 case Builtin::BI__atomic_is_lock_free:
6446 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006447 APSInt SizeVal;
6448 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6449 return false;
6450
6451 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6452 // of two less than the maximum inline atomic width, we know it is
6453 // lock-free. If the size isn't a power of two, or greater than the
6454 // maximum alignment where we promote atomics, we know it is not lock-free
6455 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6456 // the answer can only be determined at runtime; for example, 16-byte
6457 // atomics have lock-free implementations on some, but not all,
6458 // x86-64 processors.
6459
6460 // Check power-of-two.
6461 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006462 if (Size.isPowerOfTwo()) {
6463 // Check against inlining width.
6464 unsigned InlineWidthBits =
6465 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6466 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6467 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6468 Size == CharUnits::One() ||
6469 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6470 Expr::NPC_NeverValueDependent))
6471 // OK, we will inline appropriately-aligned operations of this size,
6472 // and _Atomic(T) is appropriately-aligned.
6473 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006474
Richard Smith01ba47d2012-04-13 00:45:38 +00006475 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6476 castAs<PointerType>()->getPointeeType();
6477 if (!PointeeType->isIncompleteType() &&
6478 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6479 // OK, we will inline operations on this object.
6480 return Success(1, E);
6481 }
6482 }
6483 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006484
Richard Smith01ba47d2012-04-13 00:45:38 +00006485 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6486 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006487 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006488 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006489}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006490
Richard Smith8b3497e2011-10-31 01:37:14 +00006491static bool HasSameBase(const LValue &A, const LValue &B) {
6492 if (!A.getLValueBase())
6493 return !B.getLValueBase();
6494 if (!B.getLValueBase())
6495 return false;
6496
Richard Smithce40ad62011-11-12 22:28:03 +00006497 if (A.getLValueBase().getOpaqueValue() !=
6498 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006499 const Decl *ADecl = GetLValueBaseDecl(A);
6500 if (!ADecl)
6501 return false;
6502 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006503 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006504 return false;
6505 }
6506
6507 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006508 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006509}
6510
Richard Smithd20f1e62014-10-21 23:01:04 +00006511/// \brief Determine whether this is a pointer past the end of the complete
6512/// object referred to by the lvalue.
6513static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6514 const LValue &LV) {
6515 // A null pointer can be viewed as being "past the end" but we don't
6516 // choose to look at it that way here.
6517 if (!LV.getLValueBase())
6518 return false;
6519
6520 // If the designator is valid and refers to a subobject, we're not pointing
6521 // past the end.
6522 if (!LV.getLValueDesignator().Invalid &&
6523 !LV.getLValueDesignator().isOnePastTheEnd())
6524 return false;
6525
6526 // We're a past-the-end pointer if we point to the byte after the object,
6527 // no matter what our type or path is.
6528 auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
6529 return LV.getLValueOffset() == Size;
6530}
6531
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006532namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006533
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006534/// \brief Data recursive integer evaluator of certain binary operators.
6535///
6536/// We use a data recursive algorithm for binary operators so that we are able
6537/// to handle extreme cases of chained binary operators without causing stack
6538/// overflow.
6539class DataRecursiveIntBinOpEvaluator {
6540 struct EvalResult {
6541 APValue Val;
6542 bool Failed;
6543
6544 EvalResult() : Failed(false) { }
6545
6546 void swap(EvalResult &RHS) {
6547 Val.swap(RHS.Val);
6548 Failed = RHS.Failed;
6549 RHS.Failed = false;
6550 }
6551 };
6552
6553 struct Job {
6554 const Expr *E;
6555 EvalResult LHSResult; // meaningful only for binary operator expression.
6556 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006557
David Blaikie73726062015-08-12 23:09:24 +00006558 Job() = default;
6559 Job(Job &&J)
6560 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6561 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6562 J.StoredInfo = nullptr;
6563 }
6564
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006565 void startSpeculativeEval(EvalInfo &Info) {
6566 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006567 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006568 StoredInfo = &Info;
6569 }
6570 ~Job() {
6571 if (StoredInfo) {
6572 StoredInfo->EvalStatus = OldEvalStatus;
6573 }
6574 }
6575 private:
David Blaikie73726062015-08-12 23:09:24 +00006576 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006577 Expr::EvalStatus OldEvalStatus;
6578 };
6579
6580 SmallVector<Job, 16> Queue;
6581
6582 IntExprEvaluator &IntEval;
6583 EvalInfo &Info;
6584 APValue &FinalResult;
6585
6586public:
6587 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6588 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6589
6590 /// \brief True if \param E is a binary operator that we are going to handle
6591 /// data recursively.
6592 /// We handle binary operators that are comma, logical, or that have operands
6593 /// with integral or enumeration type.
6594 static bool shouldEnqueue(const BinaryOperator *E) {
6595 return E->getOpcode() == BO_Comma ||
6596 E->isLogicalOp() ||
6597 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6598 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006599 }
6600
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006601 bool Traverse(const BinaryOperator *E) {
6602 enqueue(E);
6603 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006604 while (!Queue.empty())
6605 process(PrevResult);
6606
6607 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006608
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006609 FinalResult.swap(PrevResult.Val);
6610 return true;
6611 }
6612
6613private:
6614 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6615 return IntEval.Success(Value, E, Result);
6616 }
6617 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6618 return IntEval.Success(Value, E, Result);
6619 }
6620 bool Error(const Expr *E) {
6621 return IntEval.Error(E);
6622 }
6623 bool Error(const Expr *E, diag::kind D) {
6624 return IntEval.Error(E, D);
6625 }
6626
6627 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6628 return Info.CCEDiag(E, D);
6629 }
6630
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006631 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6632 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006633 bool &SuppressRHSDiags);
6634
6635 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6636 const BinaryOperator *E, APValue &Result);
6637
6638 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6639 Result.Failed = !Evaluate(Result.Val, Info, E);
6640 if (Result.Failed)
6641 Result.Val = APValue();
6642 }
6643
Richard Trieuba4d0872012-03-21 23:30:30 +00006644 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006645
6646 void enqueue(const Expr *E) {
6647 E = E->IgnoreParens();
6648 Queue.resize(Queue.size()+1);
6649 Queue.back().E = E;
6650 Queue.back().Kind = Job::AnyExprKind;
6651 }
6652};
6653
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006654}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006655
6656bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006657 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006658 bool &SuppressRHSDiags) {
6659 if (E->getOpcode() == BO_Comma) {
6660 // Ignore LHS but note if we could not evaluate it.
6661 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006662 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006663 return true;
6664 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006665
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006666 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006667 bool LHSAsBool;
6668 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006669 // We were able to evaluate the LHS, see if we can get away with not
6670 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006671 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6672 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006673 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006674 }
6675 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006676 LHSResult.Failed = true;
6677
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006678 // Since we weren't able to evaluate the left hand side, it
6679 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006680 if (!Info.noteSideEffect())
6681 return false;
6682
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006683 // We can't evaluate the LHS; however, sometimes the result
6684 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6685 // Don't ignore RHS and suppress diagnostics from this arm.
6686 SuppressRHSDiags = true;
6687 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006688
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006689 return true;
6690 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006691
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006692 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6693 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006694
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006695 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006696 return false; // Ignore RHS;
6697
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006698 return true;
6699}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006700
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006701bool DataRecursiveIntBinOpEvaluator::
6702 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6703 const BinaryOperator *E, APValue &Result) {
6704 if (E->getOpcode() == BO_Comma) {
6705 if (RHSResult.Failed)
6706 return false;
6707 Result = RHSResult.Val;
6708 return true;
6709 }
6710
6711 if (E->isLogicalOp()) {
6712 bool lhsResult, rhsResult;
6713 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6714 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6715
6716 if (LHSIsOK) {
6717 if (RHSIsOK) {
6718 if (E->getOpcode() == BO_LOr)
6719 return Success(lhsResult || rhsResult, E, Result);
6720 else
6721 return Success(lhsResult && rhsResult, E, Result);
6722 }
6723 } else {
6724 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006725 // We can't evaluate the LHS; however, sometimes the result
6726 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6727 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006728 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006729 }
6730 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006731
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006732 return false;
6733 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006734
6735 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6736 E->getRHS()->getType()->isIntegralOrEnumerationType());
6737
6738 if (LHSResult.Failed || RHSResult.Failed)
6739 return false;
6740
6741 const APValue &LHSVal = LHSResult.Val;
6742 const APValue &RHSVal = RHSResult.Val;
6743
6744 // Handle cases like (unsigned long)&a + 4.
6745 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6746 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006747 CharUnits AdditionalOffset =
6748 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006749 if (E->getOpcode() == BO_Add)
6750 Result.getLValueOffset() += AdditionalOffset;
6751 else
6752 Result.getLValueOffset() -= AdditionalOffset;
6753 return true;
6754 }
6755
6756 // Handle cases like 4 + (unsigned long)&a
6757 if (E->getOpcode() == BO_Add &&
6758 RHSVal.isLValue() && LHSVal.isInt()) {
6759 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006760 Result.getLValueOffset() +=
6761 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006762 return true;
6763 }
6764
6765 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6766 // Handle (intptr_t)&&A - (intptr_t)&&B.
6767 if (!LHSVal.getLValueOffset().isZero() ||
6768 !RHSVal.getLValueOffset().isZero())
6769 return false;
6770 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6771 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6772 if (!LHSExpr || !RHSExpr)
6773 return false;
6774 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6775 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6776 if (!LHSAddrExpr || !RHSAddrExpr)
6777 return false;
6778 // Make sure both labels come from the same function.
6779 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6780 RHSAddrExpr->getLabel()->getDeclContext())
6781 return false;
6782 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6783 return true;
6784 }
Richard Smith43e77732013-05-07 04:50:00 +00006785
6786 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006787 if (!LHSVal.isInt() || !RHSVal.isInt())
6788 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006789
6790 // Set up the width and signedness manually, in case it can't be deduced
6791 // from the operation we're performing.
6792 // FIXME: Don't do this in the cases where we can deduce it.
6793 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6794 E->getType()->isUnsignedIntegerOrEnumerationType());
6795 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6796 RHSVal.getInt(), Value))
6797 return false;
6798 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006799}
6800
Richard Trieuba4d0872012-03-21 23:30:30 +00006801void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006802 Job &job = Queue.back();
6803
6804 switch (job.Kind) {
6805 case Job::AnyExprKind: {
6806 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6807 if (shouldEnqueue(Bop)) {
6808 job.Kind = Job::BinOpKind;
6809 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006810 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006811 }
6812 }
6813
6814 EvaluateExpr(job.E, Result);
6815 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006816 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006817 }
6818
6819 case Job::BinOpKind: {
6820 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006821 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006822 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006823 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006824 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006825 }
6826 if (SuppressRHSDiags)
6827 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006828 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006829 job.Kind = Job::BinOpVisitedLHSKind;
6830 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006831 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006832 }
6833
6834 case Job::BinOpVisitedLHSKind: {
6835 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6836 EvalResult RHS;
6837 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006838 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006839 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006840 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006841 }
6842 }
6843
6844 llvm_unreachable("Invalid Job::Kind!");
6845}
6846
6847bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00006848 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006849 return Error(E);
6850
6851 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6852 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006853
Anders Carlssonacc79812008-11-16 07:17:21 +00006854 QualType LHSTy = E->getLHS()->getType();
6855 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006856
Chandler Carruthb29a7432014-10-11 11:03:30 +00006857 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006858 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00006859 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00006860 if (E->isAssignmentOp()) {
6861 LValue LV;
6862 EvaluateLValue(E->getLHS(), LV, Info);
6863 LHSOK = false;
6864 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00006865 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6866 if (LHSOK) {
6867 LHS.makeComplexFloat();
6868 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6869 }
6870 } else {
6871 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6872 }
Richard Smith253c2a32012-01-27 01:14:48 +00006873 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006874 return false;
6875
Chandler Carruthb29a7432014-10-11 11:03:30 +00006876 if (E->getRHS()->getType()->isRealFloatingType()) {
6877 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6878 return false;
6879 RHS.makeComplexFloat();
6880 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6881 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006882 return false;
6883
6884 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006885 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006886 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006887 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006888 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6889
John McCalle3027922010-08-25 11:45:40 +00006890 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006891 return Success((CR_r == APFloat::cmpEqual &&
6892 CR_i == APFloat::cmpEqual), E);
6893 else {
John McCalle3027922010-08-25 11:45:40 +00006894 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006895 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006896 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006897 CR_r == APFloat::cmpLessThan ||
6898 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006899 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006900 CR_i == APFloat::cmpLessThan ||
6901 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006902 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006903 } else {
John McCalle3027922010-08-25 11:45:40 +00006904 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006905 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6906 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6907 else {
John McCalle3027922010-08-25 11:45:40 +00006908 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006909 "Invalid compex comparison.");
6910 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6911 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6912 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006913 }
6914 }
Mike Stump11289f42009-09-09 15:08:12 +00006915
Anders Carlssonacc79812008-11-16 07:17:21 +00006916 if (LHSTy->isRealFloatingType() &&
6917 RHSTy->isRealFloatingType()) {
6918 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006919
Richard Smith253c2a32012-01-27 01:14:48 +00006920 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6921 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006922 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006923
Richard Smith253c2a32012-01-27 01:14:48 +00006924 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006925 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006926
Anders Carlssonacc79812008-11-16 07:17:21 +00006927 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006928
Anders Carlssonacc79812008-11-16 07:17:21 +00006929 switch (E->getOpcode()) {
6930 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006931 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006932 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006933 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006934 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006935 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006936 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006937 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006938 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006939 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006940 E);
John McCalle3027922010-08-25 11:45:40 +00006941 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006942 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006943 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006944 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006945 || CR == APFloat::cmpLessThan
6946 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006947 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949
Eli Friedmana38da572009-04-28 19:17:36 +00006950 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006951 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006952 LValue LHSValue, RHSValue;
6953
6954 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6955 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006956 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006957
Richard Smith253c2a32012-01-27 01:14:48 +00006958 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006959 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006960
Richard Smith8b3497e2011-10-31 01:37:14 +00006961 // Reject differing bases from the normal codepath; we special-case
6962 // comparisons to null.
6963 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006964 if (E->getOpcode() == BO_Sub) {
6965 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006966 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6967 return false;
6968 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006969 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006970 if (!LHSExpr || !RHSExpr)
6971 return false;
6972 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6973 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6974 if (!LHSAddrExpr || !RHSAddrExpr)
6975 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006976 // Make sure both labels come from the same function.
6977 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6978 RHSAddrExpr->getLabel()->getDeclContext())
6979 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006980 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006981 return true;
6982 }
Richard Smith83c68212011-10-31 05:11:32 +00006983 // Inequalities and subtractions between unrelated pointers have
6984 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006985 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006986 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006987 // A constant address may compare equal to the address of a symbol.
6988 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006989 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006990 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6991 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006992 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006993 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006994 // distinct addresses. In clang, the result of such a comparison is
6995 // unspecified, so it is not a constant expression. However, we do know
6996 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006997 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6998 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006999 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007000 // We can't tell whether weak symbols will end up pointing to the same
7001 // object.
7002 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007003 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007004 // We can't compare the address of the start of one object with the
7005 // past-the-end address of another object, per C++ DR1652.
7006 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7007 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7008 (RHSValue.Base && RHSValue.Offset.isZero() &&
7009 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7010 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007011 // We can't tell whether an object is at the same address as another
7012 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007013 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7014 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007015 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007016 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007017 // (Note that clang defaults to -fmerge-all-constants, which can
7018 // lead to inconsistent results for comparisons involving the address
7019 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007020 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007021 }
Eli Friedman64004332009-03-23 04:38:34 +00007022
Richard Smith1b470412012-02-01 08:10:20 +00007023 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7024 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7025
Richard Smith84f6dcf2012-02-02 01:16:57 +00007026 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7027 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7028
John McCalle3027922010-08-25 11:45:40 +00007029 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007030 // C++11 [expr.add]p6:
7031 // Unless both pointers point to elements of the same array object, or
7032 // one past the last element of the array object, the behavior is
7033 // undefined.
7034 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7035 !AreElementsOfSameArray(getType(LHSValue.Base),
7036 LHSDesignator, RHSDesignator))
7037 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7038
Chris Lattner882bdf22010-04-20 17:13:14 +00007039 QualType Type = E->getLHS()->getType();
7040 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007041
Richard Smithd62306a2011-11-10 06:34:14 +00007042 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007043 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007044 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007045
Richard Smith84c6b3d2013-09-10 21:34:14 +00007046 // As an extension, a type may have zero size (empty struct or union in
7047 // C, array of zero length). Pointer subtraction in such cases has
7048 // undefined behavior, so is not constant.
7049 if (ElementSize.isZero()) {
7050 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7051 << ElementType;
7052 return false;
7053 }
7054
Richard Smith1b470412012-02-01 08:10:20 +00007055 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7056 // and produce incorrect results when it overflows. Such behavior
7057 // appears to be non-conforming, but is common, so perhaps we should
7058 // assume the standard intended for such cases to be undefined behavior
7059 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007060
Richard Smith1b470412012-02-01 08:10:20 +00007061 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7062 // overflow in the final conversion to ptrdiff_t.
7063 APSInt LHS(
7064 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7065 APSInt RHS(
7066 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7067 APSInt ElemSize(
7068 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7069 APSInt TrueResult = (LHS - RHS) / ElemSize;
7070 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7071
7072 if (Result.extend(65) != TrueResult)
7073 HandleOverflow(Info, E, TrueResult, E->getType());
7074 return Success(Result, E);
7075 }
Richard Smithde21b242012-01-31 06:41:30 +00007076
7077 // C++11 [expr.rel]p3:
7078 // Pointers to void (after pointer conversions) can be compared, with a
7079 // result defined as follows: If both pointers represent the same
7080 // address or are both the null pointer value, the result is true if the
7081 // operator is <= or >= and false otherwise; otherwise the result is
7082 // unspecified.
7083 // We interpret this as applying to pointers to *cv* void.
7084 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007085 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007086 CCEDiag(E, diag::note_constexpr_void_comparison);
7087
Richard Smith84f6dcf2012-02-02 01:16:57 +00007088 // C++11 [expr.rel]p2:
7089 // - If two pointers point to non-static data members of the same object,
7090 // or to subobjects or array elements fo such members, recursively, the
7091 // pointer to the later declared member compares greater provided the
7092 // two members have the same access control and provided their class is
7093 // not a union.
7094 // [...]
7095 // - Otherwise pointer comparisons are unspecified.
7096 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7097 E->isRelationalOp()) {
7098 bool WasArrayIndex;
7099 unsigned Mismatch =
7100 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7101 RHSDesignator, WasArrayIndex);
7102 // At the point where the designators diverge, the comparison has a
7103 // specified value if:
7104 // - we are comparing array indices
7105 // - we are comparing fields of a union, or fields with the same access
7106 // Otherwise, the result is unspecified and thus the comparison is not a
7107 // constant expression.
7108 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7109 Mismatch < RHSDesignator.Entries.size()) {
7110 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7111 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7112 if (!LF && !RF)
7113 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7114 else if (!LF)
7115 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7116 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7117 << RF->getParent() << RF;
7118 else if (!RF)
7119 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7120 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7121 << LF->getParent() << LF;
7122 else if (!LF->getParent()->isUnion() &&
7123 LF->getAccess() != RF->getAccess())
7124 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7125 << LF << LF->getAccess() << RF << RF->getAccess()
7126 << LF->getParent();
7127 }
7128 }
7129
Eli Friedman6c31cb42012-04-16 04:30:08 +00007130 // The comparison here must be unsigned, and performed with the same
7131 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007132 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7133 uint64_t CompareLHS = LHSOffset.getQuantity();
7134 uint64_t CompareRHS = RHSOffset.getQuantity();
7135 assert(PtrSize <= 64 && "Unexpected pointer width");
7136 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7137 CompareLHS &= Mask;
7138 CompareRHS &= Mask;
7139
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007140 // If there is a base and this is a relational operator, we can only
7141 // compare pointers within the object in question; otherwise, the result
7142 // depends on where the object is located in memory.
7143 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7144 QualType BaseTy = getType(LHSValue.Base);
7145 if (BaseTy->isIncompleteType())
7146 return Error(E);
7147 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7148 uint64_t OffsetLimit = Size.getQuantity();
7149 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7150 return Error(E);
7151 }
7152
Richard Smith8b3497e2011-10-31 01:37:14 +00007153 switch (E->getOpcode()) {
7154 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007155 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7156 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7157 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7158 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7159 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7160 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007161 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007162 }
7163 }
Richard Smith7bb00672012-02-01 01:42:44 +00007164
7165 if (LHSTy->isMemberPointerType()) {
7166 assert(E->isEqualityOp() && "unexpected member pointer operation");
7167 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7168
7169 MemberPtr LHSValue, RHSValue;
7170
7171 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7172 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7173 return false;
7174
7175 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7176 return false;
7177
7178 // C++11 [expr.eq]p2:
7179 // If both operands are null, they compare equal. Otherwise if only one is
7180 // null, they compare unequal.
7181 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7182 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7183 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7184 }
7185
7186 // Otherwise if either is a pointer to a virtual member function, the
7187 // result is unspecified.
7188 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7189 if (MD->isVirtual())
7190 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7191 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7192 if (MD->isVirtual())
7193 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7194
7195 // Otherwise they compare equal if and only if they would refer to the
7196 // same member of the same most derived object or the same subobject if
7197 // they were dereferenced with a hypothetical object of the associated
7198 // class type.
7199 bool Equal = LHSValue == RHSValue;
7200 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7201 }
7202
Richard Smithab44d9b2012-02-14 22:35:28 +00007203 if (LHSTy->isNullPtrType()) {
7204 assert(E->isComparisonOp() && "unexpected nullptr operation");
7205 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7206 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7207 // are compared, the result is true of the operator is <=, >= or ==, and
7208 // false otherwise.
7209 BinaryOperator::Opcode Opcode = E->getOpcode();
7210 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7211 }
7212
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007213 assert((!LHSTy->isIntegralOrEnumerationType() ||
7214 !RHSTy->isIntegralOrEnumerationType()) &&
7215 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7216 // We can't continue from here for non-integral types.
7217 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007218}
7219
Peter Collingbournee190dee2011-03-11 19:24:49 +00007220/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7221/// a result as the expression's type.
7222bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7223 const UnaryExprOrTypeTraitExpr *E) {
7224 switch(E->getKind()) {
7225 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007226 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007227 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007228 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007229 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007230 }
Eli Friedman64004332009-03-23 04:38:34 +00007231
Peter Collingbournee190dee2011-03-11 19:24:49 +00007232 case UETT_VecStep: {
7233 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007234
Peter Collingbournee190dee2011-03-11 19:24:49 +00007235 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007236 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007237
Peter Collingbournee190dee2011-03-11 19:24:49 +00007238 // The vec_step built-in functions that take a 3-component
7239 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7240 if (n == 3)
7241 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007242
Peter Collingbournee190dee2011-03-11 19:24:49 +00007243 return Success(n, E);
7244 } else
7245 return Success(1, E);
7246 }
7247
7248 case UETT_SizeOf: {
7249 QualType SrcTy = E->getTypeOfArgument();
7250 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7251 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007252 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7253 SrcTy = Ref->getPointeeType();
7254
Richard Smithd62306a2011-11-10 06:34:14 +00007255 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007256 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007257 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007258 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007259 }
Alexey Bataev00396512015-07-02 03:40:19 +00007260 case UETT_OpenMPRequiredSimdAlign:
7261 assert(E->isArgumentType());
7262 return Success(
7263 Info.Ctx.toCharUnitsFromBits(
7264 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7265 .getQuantity(),
7266 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007267 }
7268
7269 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007270}
7271
Peter Collingbournee9200682011-05-13 03:29:01 +00007272bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007273 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007274 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007275 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007276 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007277 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007278 for (unsigned i = 0; i != n; ++i) {
7279 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7280 switch (ON.getKind()) {
7281 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007282 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007283 APSInt IdxResult;
7284 if (!EvaluateInteger(Idx, IdxResult, Info))
7285 return false;
7286 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7287 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007288 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007289 CurrentType = AT->getElementType();
7290 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7291 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007292 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007293 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007294
Douglas Gregor882211c2010-04-28 22:16:22 +00007295 case OffsetOfExpr::OffsetOfNode::Field: {
7296 FieldDecl *MemberDecl = ON.getField();
7297 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007298 if (!RT)
7299 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007300 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007301 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007302 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007303 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007304 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007305 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007306 CurrentType = MemberDecl->getType().getNonReferenceType();
7307 break;
7308 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007309
Douglas Gregor882211c2010-04-28 22:16:22 +00007310 case OffsetOfExpr::OffsetOfNode::Identifier:
7311 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007312
Douglas Gregord1702062010-04-29 00:18:15 +00007313 case OffsetOfExpr::OffsetOfNode::Base: {
7314 CXXBaseSpecifier *BaseSpec = ON.getBase();
7315 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007316 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007317
7318 // Find the layout of the class whose base we are looking into.
7319 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007320 if (!RT)
7321 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007322 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007323 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007324 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7325
7326 // Find the base class itself.
7327 CurrentType = BaseSpec->getType();
7328 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7329 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007330 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007331
7332 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007333 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007334 break;
7335 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007336 }
7337 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007338 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007339}
7340
Chris Lattnere13042c2008-07-11 19:10:17 +00007341bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007342 switch (E->getOpcode()) {
7343 default:
7344 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7345 // See C99 6.6p3.
7346 return Error(E);
7347 case UO_Extension:
7348 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7349 // If so, we could clear the diagnostic ID.
7350 return Visit(E->getSubExpr());
7351 case UO_Plus:
7352 // The result is just the value.
7353 return Visit(E->getSubExpr());
7354 case UO_Minus: {
7355 if (!Visit(E->getSubExpr()))
7356 return false;
7357 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007358 const APSInt &Value = Result.getInt();
7359 if (Value.isSigned() && Value.isMinSignedValue())
7360 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7361 E->getType());
7362 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007363 }
7364 case UO_Not: {
7365 if (!Visit(E->getSubExpr()))
7366 return false;
7367 if (!Result.isInt()) return Error(E);
7368 return Success(~Result.getInt(), E);
7369 }
7370 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007371 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007372 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007373 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007374 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007375 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007376 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007377}
Mike Stump11289f42009-09-09 15:08:12 +00007378
Chris Lattner477c4be2008-07-12 01:15:53 +00007379/// HandleCast - This is used to evaluate implicit or explicit casts where the
7380/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007381bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7382 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007383 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007384 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007385
Eli Friedmanc757de22011-03-25 00:43:55 +00007386 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007387 case CK_BaseToDerived:
7388 case CK_DerivedToBase:
7389 case CK_UncheckedDerivedToBase:
7390 case CK_Dynamic:
7391 case CK_ToUnion:
7392 case CK_ArrayToPointerDecay:
7393 case CK_FunctionToPointerDecay:
7394 case CK_NullToPointer:
7395 case CK_NullToMemberPointer:
7396 case CK_BaseToDerivedMemberPointer:
7397 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007398 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007399 case CK_ConstructorConversion:
7400 case CK_IntegralToPointer:
7401 case CK_ToVoid:
7402 case CK_VectorSplat:
7403 case CK_IntegralToFloating:
7404 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007405 case CK_CPointerToObjCPointerCast:
7406 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007407 case CK_AnyPointerToBlockPointerCast:
7408 case CK_ObjCObjectLValueCast:
7409 case CK_FloatingRealToComplex:
7410 case CK_FloatingComplexToReal:
7411 case CK_FloatingComplexCast:
7412 case CK_FloatingComplexToIntegralComplex:
7413 case CK_IntegralRealToComplex:
7414 case CK_IntegralComplexCast:
7415 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007416 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007417 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007418 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007419 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007420 llvm_unreachable("invalid cast kind for integral value");
7421
Eli Friedman9faf2f92011-03-25 19:07:11 +00007422 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007423 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007424 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007425 case CK_ARCProduceObject:
7426 case CK_ARCConsumeObject:
7427 case CK_ARCReclaimReturnedObject:
7428 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007429 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007430 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007431
Richard Smith4ef685b2012-01-17 21:17:26 +00007432 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007433 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007434 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007435 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007436 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007437
7438 case CK_MemberPointerToBoolean:
7439 case CK_PointerToBoolean:
7440 case CK_IntegralToBoolean:
7441 case CK_FloatingToBoolean:
7442 case CK_FloatingComplexToBoolean:
7443 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007444 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007445 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007446 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007447 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007448 }
7449
Eli Friedmanc757de22011-03-25 00:43:55 +00007450 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007451 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007452 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007453
Eli Friedman742421e2009-02-20 01:15:07 +00007454 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007455 // Allow casts of address-of-label differences if they are no-ops
7456 // or narrowing. (The narrowing case isn't actually guaranteed to
7457 // be constant-evaluatable except in some narrow cases which are hard
7458 // to detect here. We let it through on the assumption the user knows
7459 // what they are doing.)
7460 if (Result.isAddrLabelDiff())
7461 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007462 // Only allow casts of lvalues if they are lossless.
7463 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7464 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007465
Richard Smith911e1422012-01-30 22:27:01 +00007466 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7467 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007468 }
Mike Stump11289f42009-09-09 15:08:12 +00007469
Eli Friedmanc757de22011-03-25 00:43:55 +00007470 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007471 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7472
John McCall45d55e42010-05-07 21:00:08 +00007473 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007474 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007475 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007476
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007477 if (LV.getLValueBase()) {
7478 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007479 // FIXME: Allow a larger integer size than the pointer size, and allow
7480 // narrowing back down to pointer width in subsequent integral casts.
7481 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007482 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007483 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007484
Richard Smithcf74da72011-11-16 07:18:12 +00007485 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007486 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007487 return true;
7488 }
7489
Ken Dyck02990832010-01-15 12:37:54 +00007490 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7491 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007492 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007493 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007494
Eli Friedmanc757de22011-03-25 00:43:55 +00007495 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007496 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007497 if (!EvaluateComplex(SubExpr, C, Info))
7498 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007499 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007500 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007501
Eli Friedmanc757de22011-03-25 00:43:55 +00007502 case CK_FloatingToIntegral: {
7503 APFloat F(0.0);
7504 if (!EvaluateFloat(SubExpr, F, Info))
7505 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007506
Richard Smith357362d2011-12-13 06:39:58 +00007507 APSInt Value;
7508 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7509 return false;
7510 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007511 }
7512 }
Mike Stump11289f42009-09-09 15:08:12 +00007513
Eli Friedmanc757de22011-03-25 00:43:55 +00007514 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007515}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007516
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007517bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7518 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007519 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007520 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7521 return false;
7522 if (!LV.isComplexInt())
7523 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007524 return Success(LV.getComplexIntReal(), E);
7525 }
7526
7527 return Visit(E->getSubExpr());
7528}
7529
Eli Friedman4e7a2412009-02-27 04:45:43 +00007530bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007531 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007532 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007533 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7534 return false;
7535 if (!LV.isComplexInt())
7536 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007537 return Success(LV.getComplexIntImag(), E);
7538 }
7539
Richard Smith4a678122011-10-24 18:44:57 +00007540 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007541 return Success(0, E);
7542}
7543
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007544bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7545 return Success(E->getPackLength(), E);
7546}
7547
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007548bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7549 return Success(E->getValue(), E);
7550}
7551
Chris Lattner05706e882008-07-11 18:11:29 +00007552//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007553// Float Evaluation
7554//===----------------------------------------------------------------------===//
7555
7556namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007557class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007558 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007559 APFloat &Result;
7560public:
7561 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007562 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007563
Richard Smith2e312c82012-03-03 22:46:17 +00007564 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007565 Result = V.getFloat();
7566 return true;
7567 }
Eli Friedman24c01542008-08-22 00:06:13 +00007568
Richard Smithfddd3842011-12-30 21:15:51 +00007569 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007570 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7571 return true;
7572 }
7573
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007574 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007575
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007576 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007577 bool VisitBinaryOperator(const BinaryOperator *E);
7578 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007579 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007580
John McCallb1fb0d32010-05-07 22:08:54 +00007581 bool VisitUnaryReal(const UnaryOperator *E);
7582 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007583
Richard Smithfddd3842011-12-30 21:15:51 +00007584 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007585};
7586} // end anonymous namespace
7587
7588static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007589 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007590 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007591}
7592
Jay Foad39c79802011-01-12 09:06:06 +00007593static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007594 QualType ResultTy,
7595 const Expr *Arg,
7596 bool SNaN,
7597 llvm::APFloat &Result) {
7598 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7599 if (!S) return false;
7600
7601 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7602
7603 llvm::APInt fill;
7604
7605 // Treat empty strings as if they were zero.
7606 if (S->getString().empty())
7607 fill = llvm::APInt(32, 0);
7608 else if (S->getString().getAsInteger(0, fill))
7609 return false;
7610
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007611 if (Context.getTargetInfo().isNan2008()) {
7612 if (SNaN)
7613 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7614 else
7615 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7616 } else {
7617 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7618 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7619 // a different encoding to what became a standard in 2008, and for pre-
7620 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7621 // sNaN. This is now known as "legacy NaN" encoding.
7622 if (SNaN)
7623 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7624 else
7625 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7626 }
7627
John McCall16291492010-02-28 13:00:19 +00007628 return true;
7629}
7630
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007631bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007632 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007633 default:
7634 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7635
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007636 case Builtin::BI__builtin_huge_val:
7637 case Builtin::BI__builtin_huge_valf:
7638 case Builtin::BI__builtin_huge_vall:
7639 case Builtin::BI__builtin_inf:
7640 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007641 case Builtin::BI__builtin_infl: {
7642 const llvm::fltSemantics &Sem =
7643 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007644 Result = llvm::APFloat::getInf(Sem);
7645 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007646 }
Mike Stump11289f42009-09-09 15:08:12 +00007647
John McCall16291492010-02-28 13:00:19 +00007648 case Builtin::BI__builtin_nans:
7649 case Builtin::BI__builtin_nansf:
7650 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007651 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7652 true, Result))
7653 return Error(E);
7654 return true;
John McCall16291492010-02-28 13:00:19 +00007655
Chris Lattner0b7282e2008-10-06 06:31:58 +00007656 case Builtin::BI__builtin_nan:
7657 case Builtin::BI__builtin_nanf:
7658 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007659 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007660 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007661 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7662 false, Result))
7663 return Error(E);
7664 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007665
7666 case Builtin::BI__builtin_fabs:
7667 case Builtin::BI__builtin_fabsf:
7668 case Builtin::BI__builtin_fabsl:
7669 if (!EvaluateFloat(E->getArg(0), Result, Info))
7670 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007671
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007672 if (Result.isNegative())
7673 Result.changeSign();
7674 return true;
7675
Richard Smith8889a3d2013-06-13 06:26:32 +00007676 // FIXME: Builtin::BI__builtin_powi
7677 // FIXME: Builtin::BI__builtin_powif
7678 // FIXME: Builtin::BI__builtin_powil
7679
Mike Stump11289f42009-09-09 15:08:12 +00007680 case Builtin::BI__builtin_copysign:
7681 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007682 case Builtin::BI__builtin_copysignl: {
7683 APFloat RHS(0.);
7684 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7685 !EvaluateFloat(E->getArg(1), RHS, Info))
7686 return false;
7687 Result.copySign(RHS);
7688 return true;
7689 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007690 }
7691}
7692
John McCallb1fb0d32010-05-07 22:08:54 +00007693bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007694 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7695 ComplexValue CV;
7696 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7697 return false;
7698 Result = CV.FloatReal;
7699 return true;
7700 }
7701
7702 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007703}
7704
7705bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007706 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7707 ComplexValue CV;
7708 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7709 return false;
7710 Result = CV.FloatImag;
7711 return true;
7712 }
7713
Richard Smith4a678122011-10-24 18:44:57 +00007714 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007715 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7716 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007717 return true;
7718}
7719
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007720bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007721 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007722 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007723 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007724 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007725 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007726 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7727 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007728 Result.changeSign();
7729 return true;
7730 }
7731}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007732
Eli Friedman24c01542008-08-22 00:06:13 +00007733bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007734 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7735 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007736
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007737 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007738 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7739 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007740 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007741 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7742 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007743}
7744
7745bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7746 Result = E->getValue();
7747 return true;
7748}
7749
Peter Collingbournee9200682011-05-13 03:29:01 +00007750bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7751 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007752
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007753 switch (E->getCastKind()) {
7754 default:
Richard Smith11562c52011-10-28 17:51:58 +00007755 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007756
7757 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007758 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007759 return EvaluateInteger(SubExpr, IntResult, Info) &&
7760 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7761 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007762 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007763
7764 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007765 if (!Visit(SubExpr))
7766 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007767 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7768 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007769 }
John McCalld7646252010-11-14 08:17:51 +00007770
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007771 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007772 ComplexValue V;
7773 if (!EvaluateComplex(SubExpr, V, Info))
7774 return false;
7775 Result = V.getComplexFloatReal();
7776 return true;
7777 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007778 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007779}
7780
Eli Friedman24c01542008-08-22 00:06:13 +00007781//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007782// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007783//===----------------------------------------------------------------------===//
7784
7785namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007786class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007787 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007788 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007789
Anders Carlsson537969c2008-11-16 20:27:53 +00007790public:
John McCall93d91dc2010-05-07 17:22:02 +00007791 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007792 : ExprEvaluatorBaseTy(info), Result(Result) {}
7793
Richard Smith2e312c82012-03-03 22:46:17 +00007794 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007795 Result.setFrom(V);
7796 return true;
7797 }
Mike Stump11289f42009-09-09 15:08:12 +00007798
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007799 bool ZeroInitialization(const Expr *E);
7800
Anders Carlsson537969c2008-11-16 20:27:53 +00007801 //===--------------------------------------------------------------------===//
7802 // Visitor Methods
7803 //===--------------------------------------------------------------------===//
7804
Peter Collingbournee9200682011-05-13 03:29:01 +00007805 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007806 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007807 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007808 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007809 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007810};
7811} // end anonymous namespace
7812
John McCall93d91dc2010-05-07 17:22:02 +00007813static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7814 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007815 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007816 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007817}
7818
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007819bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007820 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007821 if (ElemTy->isRealFloatingType()) {
7822 Result.makeComplexFloat();
7823 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7824 Result.FloatReal = Zero;
7825 Result.FloatImag = Zero;
7826 } else {
7827 Result.makeComplexInt();
7828 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7829 Result.IntReal = Zero;
7830 Result.IntImag = Zero;
7831 }
7832 return true;
7833}
7834
Peter Collingbournee9200682011-05-13 03:29:01 +00007835bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7836 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007837
7838 if (SubExpr->getType()->isRealFloatingType()) {
7839 Result.makeComplexFloat();
7840 APFloat &Imag = Result.FloatImag;
7841 if (!EvaluateFloat(SubExpr, Imag, Info))
7842 return false;
7843
7844 Result.FloatReal = APFloat(Imag.getSemantics());
7845 return true;
7846 } else {
7847 assert(SubExpr->getType()->isIntegerType() &&
7848 "Unexpected imaginary literal.");
7849
7850 Result.makeComplexInt();
7851 APSInt &Imag = Result.IntImag;
7852 if (!EvaluateInteger(SubExpr, Imag, Info))
7853 return false;
7854
7855 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7856 return true;
7857 }
7858}
7859
Peter Collingbournee9200682011-05-13 03:29:01 +00007860bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007861
John McCallfcef3cf2010-12-14 17:51:41 +00007862 switch (E->getCastKind()) {
7863 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007864 case CK_BaseToDerived:
7865 case CK_DerivedToBase:
7866 case CK_UncheckedDerivedToBase:
7867 case CK_Dynamic:
7868 case CK_ToUnion:
7869 case CK_ArrayToPointerDecay:
7870 case CK_FunctionToPointerDecay:
7871 case CK_NullToPointer:
7872 case CK_NullToMemberPointer:
7873 case CK_BaseToDerivedMemberPointer:
7874 case CK_DerivedToBaseMemberPointer:
7875 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007876 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007877 case CK_ConstructorConversion:
7878 case CK_IntegralToPointer:
7879 case CK_PointerToIntegral:
7880 case CK_PointerToBoolean:
7881 case CK_ToVoid:
7882 case CK_VectorSplat:
7883 case CK_IntegralCast:
7884 case CK_IntegralToBoolean:
7885 case CK_IntegralToFloating:
7886 case CK_FloatingToIntegral:
7887 case CK_FloatingToBoolean:
7888 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007889 case CK_CPointerToObjCPointerCast:
7890 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007891 case CK_AnyPointerToBlockPointerCast:
7892 case CK_ObjCObjectLValueCast:
7893 case CK_FloatingComplexToReal:
7894 case CK_FloatingComplexToBoolean:
7895 case CK_IntegralComplexToReal:
7896 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007897 case CK_ARCProduceObject:
7898 case CK_ARCConsumeObject:
7899 case CK_ARCReclaimReturnedObject:
7900 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007901 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007902 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007903 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007904 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007905 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007906 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007907
John McCallfcef3cf2010-12-14 17:51:41 +00007908 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007909 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007910 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007911 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007912
7913 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007914 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007915 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007916 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007917
7918 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007919 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007920 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007921 return false;
7922
John McCallfcef3cf2010-12-14 17:51:41 +00007923 Result.makeComplexFloat();
7924 Result.FloatImag = APFloat(Real.getSemantics());
7925 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007926 }
7927
John McCallfcef3cf2010-12-14 17:51:41 +00007928 case CK_FloatingComplexCast: {
7929 if (!Visit(E->getSubExpr()))
7930 return false;
7931
7932 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7933 QualType From
7934 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7935
Richard Smith357362d2011-12-13 06:39:58 +00007936 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7937 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007938 }
7939
7940 case CK_FloatingComplexToIntegralComplex: {
7941 if (!Visit(E->getSubExpr()))
7942 return false;
7943
7944 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7945 QualType From
7946 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7947 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007948 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7949 To, Result.IntReal) &&
7950 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7951 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007952 }
7953
7954 case CK_IntegralRealToComplex: {
7955 APSInt &Real = Result.IntReal;
7956 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7957 return false;
7958
7959 Result.makeComplexInt();
7960 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7961 return true;
7962 }
7963
7964 case CK_IntegralComplexCast: {
7965 if (!Visit(E->getSubExpr()))
7966 return false;
7967
7968 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7969 QualType From
7970 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7971
Richard Smith911e1422012-01-30 22:27:01 +00007972 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7973 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007974 return true;
7975 }
7976
7977 case CK_IntegralComplexToFloatingComplex: {
7978 if (!Visit(E->getSubExpr()))
7979 return false;
7980
Ted Kremenek28831752012-08-23 20:46:57 +00007981 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007982 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007983 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007984 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007985 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7986 To, Result.FloatReal) &&
7987 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7988 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007989 }
7990 }
7991
7992 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007993}
7994
John McCall93d91dc2010-05-07 17:22:02 +00007995bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007996 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007997 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7998
Chandler Carrutha216cad2014-10-11 00:57:18 +00007999 // Track whether the LHS or RHS is real at the type system level. When this is
8000 // the case we can simplify our evaluation strategy.
8001 bool LHSReal = false, RHSReal = false;
8002
8003 bool LHSOK;
8004 if (E->getLHS()->getType()->isRealFloatingType()) {
8005 LHSReal = true;
8006 APFloat &Real = Result.FloatReal;
8007 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8008 if (LHSOK) {
8009 Result.makeComplexFloat();
8010 Result.FloatImag = APFloat(Real.getSemantics());
8011 }
8012 } else {
8013 LHSOK = Visit(E->getLHS());
8014 }
Richard Smith253c2a32012-01-27 01:14:48 +00008015 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008016 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008017
John McCall93d91dc2010-05-07 17:22:02 +00008018 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008019 if (E->getRHS()->getType()->isRealFloatingType()) {
8020 RHSReal = true;
8021 APFloat &Real = RHS.FloatReal;
8022 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8023 return false;
8024 RHS.makeComplexFloat();
8025 RHS.FloatImag = APFloat(Real.getSemantics());
8026 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008027 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008028
Chandler Carrutha216cad2014-10-11 00:57:18 +00008029 assert(!(LHSReal && RHSReal) &&
8030 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008031 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008032 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008033 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008034 if (Result.isComplexFloat()) {
8035 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8036 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008037 if (LHSReal)
8038 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8039 else if (!RHSReal)
8040 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8041 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008042 } else {
8043 Result.getComplexIntReal() += RHS.getComplexIntReal();
8044 Result.getComplexIntImag() += RHS.getComplexIntImag();
8045 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008046 break;
John McCalle3027922010-08-25 11:45:40 +00008047 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008048 if (Result.isComplexFloat()) {
8049 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8050 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008051 if (LHSReal) {
8052 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8053 Result.getComplexFloatImag().changeSign();
8054 } else if (!RHSReal) {
8055 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8056 APFloat::rmNearestTiesToEven);
8057 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008058 } else {
8059 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8060 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8061 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008062 break;
John McCalle3027922010-08-25 11:45:40 +00008063 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008064 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008065 // This is an implementation of complex multiplication according to the
8066 // constraints laid out in C11 Annex G. The implemantion uses the
8067 // following naming scheme:
8068 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008069 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008070 APFloat &A = LHS.getComplexFloatReal();
8071 APFloat &B = LHS.getComplexFloatImag();
8072 APFloat &C = RHS.getComplexFloatReal();
8073 APFloat &D = RHS.getComplexFloatImag();
8074 APFloat &ResR = Result.getComplexFloatReal();
8075 APFloat &ResI = Result.getComplexFloatImag();
8076 if (LHSReal) {
8077 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8078 ResR = A * C;
8079 ResI = A * D;
8080 } else if (RHSReal) {
8081 ResR = C * A;
8082 ResI = C * B;
8083 } else {
8084 // In the fully general case, we need to handle NaNs and infinities
8085 // robustly.
8086 APFloat AC = A * C;
8087 APFloat BD = B * D;
8088 APFloat AD = A * D;
8089 APFloat BC = B * C;
8090 ResR = AC - BD;
8091 ResI = AD + BC;
8092 if (ResR.isNaN() && ResI.isNaN()) {
8093 bool Recalc = false;
8094 if (A.isInfinity() || B.isInfinity()) {
8095 A = APFloat::copySign(
8096 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8097 B = APFloat::copySign(
8098 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8099 if (C.isNaN())
8100 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8101 if (D.isNaN())
8102 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8103 Recalc = true;
8104 }
8105 if (C.isInfinity() || D.isInfinity()) {
8106 C = APFloat::copySign(
8107 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8108 D = APFloat::copySign(
8109 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8110 if (A.isNaN())
8111 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8112 if (B.isNaN())
8113 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8114 Recalc = true;
8115 }
8116 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8117 AD.isInfinity() || BC.isInfinity())) {
8118 if (A.isNaN())
8119 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8120 if (B.isNaN())
8121 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8122 if (C.isNaN())
8123 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8124 if (D.isNaN())
8125 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8126 Recalc = true;
8127 }
8128 if (Recalc) {
8129 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8130 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8131 }
8132 }
8133 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008134 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008135 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008136 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008137 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8138 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008139 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008140 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8141 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8142 }
8143 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008144 case BO_Div:
8145 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008146 // This is an implementation of complex division according to the
8147 // constraints laid out in C11 Annex G. The implemantion uses the
8148 // following naming scheme:
8149 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008150 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008151 APFloat &A = LHS.getComplexFloatReal();
8152 APFloat &B = LHS.getComplexFloatImag();
8153 APFloat &C = RHS.getComplexFloatReal();
8154 APFloat &D = RHS.getComplexFloatImag();
8155 APFloat &ResR = Result.getComplexFloatReal();
8156 APFloat &ResI = Result.getComplexFloatImag();
8157 if (RHSReal) {
8158 ResR = A / C;
8159 ResI = B / C;
8160 } else {
8161 if (LHSReal) {
8162 // No real optimizations we can do here, stub out with zero.
8163 B = APFloat::getZero(A.getSemantics());
8164 }
8165 int DenomLogB = 0;
8166 APFloat MaxCD = maxnum(abs(C), abs(D));
8167 if (MaxCD.isFinite()) {
8168 DenomLogB = ilogb(MaxCD);
8169 C = scalbn(C, -DenomLogB);
8170 D = scalbn(D, -DenomLogB);
8171 }
8172 APFloat Denom = C * C + D * D;
8173 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8174 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8175 if (ResR.isNaN() && ResI.isNaN()) {
8176 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8177 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8178 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8179 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8180 D.isFinite()) {
8181 A = APFloat::copySign(
8182 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8183 B = APFloat::copySign(
8184 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8185 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8186 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8187 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8188 C = APFloat::copySign(
8189 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8190 D = APFloat::copySign(
8191 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8192 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8193 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8194 }
8195 }
8196 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008197 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008198 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8199 return Error(E, diag::note_expr_divide_by_zero);
8200
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008201 ComplexValue LHS = Result;
8202 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8203 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8204 Result.getComplexIntReal() =
8205 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8206 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8207 Result.getComplexIntImag() =
8208 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8209 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8210 }
8211 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008212 }
8213
John McCall93d91dc2010-05-07 17:22:02 +00008214 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008215}
8216
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008217bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8218 // Get the operand value into 'Result'.
8219 if (!Visit(E->getSubExpr()))
8220 return false;
8221
8222 switch (E->getOpcode()) {
8223 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008224 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008225 case UO_Extension:
8226 return true;
8227 case UO_Plus:
8228 // The result is always just the subexpr.
8229 return true;
8230 case UO_Minus:
8231 if (Result.isComplexFloat()) {
8232 Result.getComplexFloatReal().changeSign();
8233 Result.getComplexFloatImag().changeSign();
8234 }
8235 else {
8236 Result.getComplexIntReal() = -Result.getComplexIntReal();
8237 Result.getComplexIntImag() = -Result.getComplexIntImag();
8238 }
8239 return true;
8240 case UO_Not:
8241 if (Result.isComplexFloat())
8242 Result.getComplexFloatImag().changeSign();
8243 else
8244 Result.getComplexIntImag() = -Result.getComplexIntImag();
8245 return true;
8246 }
8247}
8248
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008249bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8250 if (E->getNumInits() == 2) {
8251 if (E->getType()->isComplexType()) {
8252 Result.makeComplexFloat();
8253 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8254 return false;
8255 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8256 return false;
8257 } else {
8258 Result.makeComplexInt();
8259 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8260 return false;
8261 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8262 return false;
8263 }
8264 return true;
8265 }
8266 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8267}
8268
Anders Carlsson537969c2008-11-16 20:27:53 +00008269//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008270// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8271// implicit conversion.
8272//===----------------------------------------------------------------------===//
8273
8274namespace {
8275class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008276 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008277 APValue &Result;
8278public:
8279 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8280 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8281
8282 bool Success(const APValue &V, const Expr *E) {
8283 Result = V;
8284 return true;
8285 }
8286
8287 bool ZeroInitialization(const Expr *E) {
8288 ImplicitValueInitExpr VIE(
8289 E->getType()->castAs<AtomicType>()->getValueType());
8290 return Evaluate(Result, Info, &VIE);
8291 }
8292
8293 bool VisitCastExpr(const CastExpr *E) {
8294 switch (E->getCastKind()) {
8295 default:
8296 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8297 case CK_NonAtomicToAtomic:
8298 return Evaluate(Result, Info, E->getSubExpr());
8299 }
8300 }
8301};
8302} // end anonymous namespace
8303
8304static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8305 assert(E->isRValue() && E->getType()->isAtomicType());
8306 return AtomicExprEvaluator(Info, Result).Visit(E);
8307}
8308
8309//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008310// Void expression evaluation, primarily for a cast to void on the LHS of a
8311// comma operator
8312//===----------------------------------------------------------------------===//
8313
8314namespace {
8315class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008316 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008317public:
8318 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8319
Richard Smith2e312c82012-03-03 22:46:17 +00008320 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008321
8322 bool VisitCastExpr(const CastExpr *E) {
8323 switch (E->getCastKind()) {
8324 default:
8325 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8326 case CK_ToVoid:
8327 VisitIgnoredValue(E->getSubExpr());
8328 return true;
8329 }
8330 }
Hal Finkela8443c32014-07-17 14:49:58 +00008331
8332 bool VisitCallExpr(const CallExpr *E) {
8333 switch (E->getBuiltinCallee()) {
8334 default:
8335 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8336 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008337 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008338 // The argument is not evaluated!
8339 return true;
8340 }
8341 }
Richard Smith42d3af92011-12-07 00:43:50 +00008342};
8343} // end anonymous namespace
8344
8345static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8346 assert(E->isRValue() && E->getType()->isVoidType());
8347 return VoidExprEvaluator(Info).Visit(E);
8348}
8349
8350//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008351// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008352//===----------------------------------------------------------------------===//
8353
Richard Smith2e312c82012-03-03 22:46:17 +00008354static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008355 // In C, function designators are not lvalues, but we evaluate them as if they
8356 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008357 QualType T = E->getType();
8358 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008359 LValue LV;
8360 if (!EvaluateLValue(E, LV, Info))
8361 return false;
8362 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008363 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008364 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008365 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008366 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008367 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008368 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008369 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008370 LValue LV;
8371 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008372 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008373 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008374 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008375 llvm::APFloat F(0.0);
8376 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008377 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008378 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008379 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008380 ComplexValue C;
8381 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008382 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008383 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008384 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008385 MemberPtr P;
8386 if (!EvaluateMemberPointer(E, P, Info))
8387 return false;
8388 P.moveInto(Result);
8389 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008390 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008391 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008392 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008393 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8394 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008395 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008396 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008397 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008398 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008399 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008400 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8401 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008402 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008403 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008404 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008405 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008406 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008407 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008408 if (!EvaluateVoid(E, Info))
8409 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008410 } else if (T->isAtomicType()) {
8411 if (!EvaluateAtomic(E, Result, Info))
8412 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008413 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008414 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008415 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008416 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008417 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008418 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008419 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008420
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008421 return true;
8422}
8423
Richard Smithb228a862012-02-15 02:18:13 +00008424/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8425/// cases, the in-place evaluation is essential, since later initializers for
8426/// an object can indirectly refer to subobjects which were initialized earlier.
8427static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008428 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008429 assert(!E->isValueDependent());
8430
Richard Smith7525ff62013-05-09 07:14:00 +00008431 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008432 return false;
8433
8434 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008435 // Evaluate arrays and record types in-place, so that later initializers can
8436 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008437 if (E->getType()->isArrayType())
8438 return EvaluateArray(E, This, Result, Info);
8439 else if (E->getType()->isRecordType())
8440 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008441 }
8442
8443 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008444 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008445}
8446
Richard Smithf57d8cb2011-12-09 22:58:01 +00008447/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8448/// lvalue-to-rvalue cast if it is an lvalue.
8449static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008450 if (E->getType().isNull())
8451 return false;
8452
Richard Smithfddd3842011-12-30 21:15:51 +00008453 if (!CheckLiteralType(Info, E))
8454 return false;
8455
Richard Smith2e312c82012-03-03 22:46:17 +00008456 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008457 return false;
8458
8459 if (E->isGLValue()) {
8460 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008461 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008462 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008463 return false;
8464 }
8465
Richard Smith2e312c82012-03-03 22:46:17 +00008466 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008467 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008468}
Richard Smith11562c52011-10-28 17:51:58 +00008469
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008470static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8471 const ASTContext &Ctx, bool &IsConst) {
8472 // Fast-path evaluations of integer literals, since we sometimes see files
8473 // containing vast quantities of these.
8474 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8475 Result.Val = APValue(APSInt(L->getValue(),
8476 L->getType()->isUnsignedIntegerType()));
8477 IsConst = true;
8478 return true;
8479 }
James Dennett0492ef02014-03-14 17:44:10 +00008480
8481 // This case should be rare, but we need to check it before we check on
8482 // the type below.
8483 if (Exp->getType().isNull()) {
8484 IsConst = false;
8485 return true;
8486 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008487
8488 // FIXME: Evaluating values of large array and record types can cause
8489 // performance problems. Only do so in C++11 for now.
8490 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8491 Exp->getType()->isRecordType()) &&
8492 !Ctx.getLangOpts().CPlusPlus11) {
8493 IsConst = false;
8494 return true;
8495 }
8496 return false;
8497}
8498
8499
Richard Smith7b553f12011-10-29 00:50:52 +00008500/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008501/// any crazy technique (that has nothing to do with language standards) that
8502/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008503/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8504/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008505bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008506 bool IsConst;
8507 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8508 return IsConst;
8509
Richard Smith6d4c6582013-11-05 22:18:15 +00008510 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008511 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008512}
8513
Jay Foad39c79802011-01-12 09:06:06 +00008514bool Expr::EvaluateAsBooleanCondition(bool &Result,
8515 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008516 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008517 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008518 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008519}
8520
Richard Smith5fab0c92011-12-28 19:48:30 +00008521bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8522 SideEffectsKind AllowSideEffects) const {
8523 if (!getType()->isIntegralOrEnumerationType())
8524 return false;
8525
Richard Smith11562c52011-10-28 17:51:58 +00008526 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008527 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8528 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008529 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008530
Richard Smith11562c52011-10-28 17:51:58 +00008531 Result = ExprResult.Val.getInt();
8532 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008533}
8534
Jay Foad39c79802011-01-12 09:06:06 +00008535bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008536 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008537
John McCall45d55e42010-05-07 21:00:08 +00008538 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008539 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8540 !CheckLValueConstantExpression(Info, getExprLoc(),
8541 Ctx.getLValueReferenceType(getType()), LV))
8542 return false;
8543
Richard Smith2e312c82012-03-03 22:46:17 +00008544 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008545 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008546}
8547
Richard Smithd0b4dd62011-12-19 06:19:21 +00008548bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8549 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008550 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008551 // FIXME: Evaluating initializers for large array and record types can cause
8552 // performance problems. Only do so in C++11 for now.
8553 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008554 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008555 return false;
8556
Richard Smithd0b4dd62011-12-19 06:19:21 +00008557 Expr::EvalStatus EStatus;
8558 EStatus.Diag = &Notes;
8559
Richard Smith6d4c6582013-11-05 22:18:15 +00008560 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008561 InitInfo.setEvaluatingDecl(VD, Value);
8562
8563 LValue LVal;
8564 LVal.set(VD);
8565
Richard Smithfddd3842011-12-30 21:15:51 +00008566 // C++11 [basic.start.init]p2:
8567 // Variables with static storage duration or thread storage duration shall be
8568 // zero-initialized before any other initialization takes place.
8569 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008570 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008571 !VD->getType()->isReferenceType()) {
8572 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008573 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008574 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008575 return false;
8576 }
8577
Richard Smith7525ff62013-05-09 07:14:00 +00008578 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8579 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008580 EStatus.HasSideEffects)
8581 return false;
8582
8583 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8584 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008585}
8586
Richard Smith7b553f12011-10-29 00:50:52 +00008587/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8588/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008589bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008590 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008591 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008592}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008593
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008594APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008595 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008596 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008597 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008598 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008599 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008600 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008601 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008602
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008603 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008604}
John McCall864e3962010-05-07 05:32:02 +00008605
Richard Smithe9ff7702013-11-05 22:23:30 +00008606void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008607 bool IsConst;
8608 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008609 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008610 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008611 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8612 }
8613}
8614
Richard Smithe6c01442013-06-05 00:46:14 +00008615bool Expr::EvalResult::isGlobalLValue() const {
8616 assert(Val.isLValue());
8617 return IsGlobalLValue(Val.getLValueBase());
8618}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008619
8620
John McCall864e3962010-05-07 05:32:02 +00008621/// isIntegerConstantExpr - this recursive routine will test if an expression is
8622/// an integer constant expression.
8623
8624/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8625/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008626
8627// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008628// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8629// and a (possibly null) SourceLocation indicating the location of the problem.
8630//
John McCall864e3962010-05-07 05:32:02 +00008631// Note that to reduce code duplication, this helper does no evaluation
8632// itself; the caller checks whether the expression is evaluatable, and
8633// in the rare cases where CheckICE actually cares about the evaluated
8634// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008635
Dan Gohman28ade552010-07-26 21:25:24 +00008636namespace {
8637
Richard Smith9e575da2012-12-28 13:25:52 +00008638enum ICEKind {
8639 /// This expression is an ICE.
8640 IK_ICE,
8641 /// This expression is not an ICE, but if it isn't evaluated, it's
8642 /// a legal subexpression for an ICE. This return value is used to handle
8643 /// the comma operator in C99 mode, and non-constant subexpressions.
8644 IK_ICEIfUnevaluated,
8645 /// This expression is not an ICE, and is not a legal subexpression for one.
8646 IK_NotICE
8647};
8648
John McCall864e3962010-05-07 05:32:02 +00008649struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008650 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008651 SourceLocation Loc;
8652
Richard Smith9e575da2012-12-28 13:25:52 +00008653 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008654};
8655
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008656}
Dan Gohman28ade552010-07-26 21:25:24 +00008657
Richard Smith9e575da2012-12-28 13:25:52 +00008658static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8659
8660static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008661
Craig Toppera31a8822013-08-22 07:09:37 +00008662static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008663 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008664 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008665 !EVResult.Val.isInt())
8666 return ICEDiag(IK_NotICE, E->getLocStart());
8667
John McCall864e3962010-05-07 05:32:02 +00008668 return NoDiag();
8669}
8670
Craig Toppera31a8822013-08-22 07:09:37 +00008671static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008672 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008673 if (!E->getType()->isIntegralOrEnumerationType())
8674 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008675
8676 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008677#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008678#define STMT(Node, Base) case Expr::Node##Class:
8679#define EXPR(Node, Base)
8680#include "clang/AST/StmtNodes.inc"
8681 case Expr::PredefinedExprClass:
8682 case Expr::FloatingLiteralClass:
8683 case Expr::ImaginaryLiteralClass:
8684 case Expr::StringLiteralClass:
8685 case Expr::ArraySubscriptExprClass:
8686 case Expr::MemberExprClass:
8687 case Expr::CompoundAssignOperatorClass:
8688 case Expr::CompoundLiteralExprClass:
8689 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008690 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00008691 case Expr::NoInitExprClass:
8692 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00008693 case Expr::ImplicitValueInitExprClass:
8694 case Expr::ParenListExprClass:
8695 case Expr::VAArgExprClass:
8696 case Expr::AddrLabelExprClass:
8697 case Expr::StmtExprClass:
8698 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008699 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008700 case Expr::CXXDynamicCastExprClass:
8701 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008702 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008703 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008704 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008705 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008706 case Expr::CXXThisExprClass:
8707 case Expr::CXXThrowExprClass:
8708 case Expr::CXXNewExprClass:
8709 case Expr::CXXDeleteExprClass:
8710 case Expr::CXXPseudoDestructorExprClass:
8711 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00008712 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00008713 case Expr::DependentScopeDeclRefExprClass:
8714 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008715 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008716 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008717 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008718 case Expr::CXXTemporaryObjectExprClass:
8719 case Expr::CXXUnresolvedConstructExprClass:
8720 case Expr::CXXDependentScopeMemberExprClass:
8721 case Expr::UnresolvedMemberExprClass:
8722 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008723 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008724 case Expr::ObjCArrayLiteralClass:
8725 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008726 case Expr::ObjCEncodeExprClass:
8727 case Expr::ObjCMessageExprClass:
8728 case Expr::ObjCSelectorExprClass:
8729 case Expr::ObjCProtocolExprClass:
8730 case Expr::ObjCIvarRefExprClass:
8731 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008732 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008733 case Expr::ObjCIsaExprClass:
8734 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008735 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008736 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008737 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008738 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008739 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008740 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008741 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008742 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008743 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008744 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008745 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008746 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008747 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00008748 case Expr::CXXFoldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008749 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008750
Richard Smithf137f932014-01-25 20:50:08 +00008751 case Expr::InitListExprClass: {
8752 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8753 // form "T x = { a };" is equivalent to "T x = a;".
8754 // Unless we're initializing a reference, T is a scalar as it is known to be
8755 // of integral or enumeration type.
8756 if (E->isRValue())
8757 if (cast<InitListExpr>(E)->getNumInits() == 1)
8758 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8759 return ICEDiag(IK_NotICE, E->getLocStart());
8760 }
8761
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008762 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008763 case Expr::GNUNullExprClass:
8764 // GCC considers the GNU __null value to be an integral constant expression.
8765 return NoDiag();
8766
John McCall7c454bb2011-07-15 05:09:51 +00008767 case Expr::SubstNonTypeTemplateParmExprClass:
8768 return
8769 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8770
John McCall864e3962010-05-07 05:32:02 +00008771 case Expr::ParenExprClass:
8772 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008773 case Expr::GenericSelectionExprClass:
8774 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008775 case Expr::IntegerLiteralClass:
8776 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008777 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008778 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008779 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008780 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008781 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008782 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008783 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008784 return NoDiag();
8785 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008786 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008787 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8788 // constant expressions, but they can never be ICEs because an ICE cannot
8789 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008790 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008791 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008792 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008793 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008794 }
Richard Smith6365c912012-02-24 22:12:32 +00008795 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008796 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8797 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008798 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008799 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008800 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008801 // Parameter variables are never constants. Without this check,
8802 // getAnyInitializer() can find a default argument, which leads
8803 // to chaos.
8804 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008805 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008806
8807 // C++ 7.1.5.1p2
8808 // A variable of non-volatile const-qualified integral or enumeration
8809 // type initialized by an ICE can be used in ICEs.
8810 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008811 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008812 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008813
Richard Smithd0b4dd62011-12-19 06:19:21 +00008814 const VarDecl *VD;
8815 // Look for a declaration of this variable that has an initializer, and
8816 // check whether it is an ICE.
8817 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8818 return NoDiag();
8819 else
Richard Smith9e575da2012-12-28 13:25:52 +00008820 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008821 }
8822 }
Richard Smith9e575da2012-12-28 13:25:52 +00008823 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008824 }
John McCall864e3962010-05-07 05:32:02 +00008825 case Expr::UnaryOperatorClass: {
8826 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8827 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008828 case UO_PostInc:
8829 case UO_PostDec:
8830 case UO_PreInc:
8831 case UO_PreDec:
8832 case UO_AddrOf:
8833 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008834 // C99 6.6/3 allows increment and decrement within unevaluated
8835 // subexpressions of constant expressions, but they can never be ICEs
8836 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008837 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008838 case UO_Extension:
8839 case UO_LNot:
8840 case UO_Plus:
8841 case UO_Minus:
8842 case UO_Not:
8843 case UO_Real:
8844 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008845 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008846 }
Richard Smith9e575da2012-12-28 13:25:52 +00008847
John McCall864e3962010-05-07 05:32:02 +00008848 // OffsetOf falls through here.
8849 }
8850 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008851 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8852 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8853 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8854 // compliance: we should warn earlier for offsetof expressions with
8855 // array subscripts that aren't ICEs, and if the array subscripts
8856 // are ICEs, the value of the offsetof must be an integer constant.
8857 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008858 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008859 case Expr::UnaryExprOrTypeTraitExprClass: {
8860 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8861 if ((Exp->getKind() == UETT_SizeOf) &&
8862 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008863 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008864 return NoDiag();
8865 }
8866 case Expr::BinaryOperatorClass: {
8867 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8868 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008869 case BO_PtrMemD:
8870 case BO_PtrMemI:
8871 case BO_Assign:
8872 case BO_MulAssign:
8873 case BO_DivAssign:
8874 case BO_RemAssign:
8875 case BO_AddAssign:
8876 case BO_SubAssign:
8877 case BO_ShlAssign:
8878 case BO_ShrAssign:
8879 case BO_AndAssign:
8880 case BO_XorAssign:
8881 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008882 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8883 // constant expressions, but they can never be ICEs because an ICE cannot
8884 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008885 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008886
John McCalle3027922010-08-25 11:45:40 +00008887 case BO_Mul:
8888 case BO_Div:
8889 case BO_Rem:
8890 case BO_Add:
8891 case BO_Sub:
8892 case BO_Shl:
8893 case BO_Shr:
8894 case BO_LT:
8895 case BO_GT:
8896 case BO_LE:
8897 case BO_GE:
8898 case BO_EQ:
8899 case BO_NE:
8900 case BO_And:
8901 case BO_Xor:
8902 case BO_Or:
8903 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008904 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8905 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008906 if (Exp->getOpcode() == BO_Div ||
8907 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008908 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008909 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008910 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008911 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008912 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008913 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008914 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008915 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008916 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008917 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008918 }
8919 }
8920 }
John McCalle3027922010-08-25 11:45:40 +00008921 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008922 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008923 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8924 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008925 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8926 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008927 } else {
8928 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008929 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008930 }
8931 }
Richard Smith9e575da2012-12-28 13:25:52 +00008932 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008933 }
John McCalle3027922010-08-25 11:45:40 +00008934 case BO_LAnd:
8935 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008936 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8937 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008938 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008939 // Rare case where the RHS has a comma "side-effect"; we need
8940 // to actually check the condition to see whether the side
8941 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008942 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008943 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008944 return RHSResult;
8945 return NoDiag();
8946 }
8947
Richard Smith9e575da2012-12-28 13:25:52 +00008948 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008949 }
8950 }
8951 }
8952 case Expr::ImplicitCastExprClass:
8953 case Expr::CStyleCastExprClass:
8954 case Expr::CXXFunctionalCastExprClass:
8955 case Expr::CXXStaticCastExprClass:
8956 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008957 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008958 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008959 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008960 if (isa<ExplicitCastExpr>(E)) {
8961 if (const FloatingLiteral *FL
8962 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8963 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8964 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8965 APSInt IgnoredVal(DestWidth, !DestSigned);
8966 bool Ignored;
8967 // If the value does not fit in the destination type, the behavior is
8968 // undefined, so we are not required to treat it as a constant
8969 // expression.
8970 if (FL->getValue().convertToInteger(IgnoredVal,
8971 llvm::APFloat::rmTowardZero,
8972 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008973 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008974 return NoDiag();
8975 }
8976 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008977 switch (cast<CastExpr>(E)->getCastKind()) {
8978 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008979 case CK_AtomicToNonAtomic:
8980 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008981 case CK_NoOp:
8982 case CK_IntegralToBoolean:
8983 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008984 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008985 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008986 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008987 }
John McCall864e3962010-05-07 05:32:02 +00008988 }
John McCallc07a0c72011-02-17 10:25:35 +00008989 case Expr::BinaryConditionalOperatorClass: {
8990 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8991 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008992 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008993 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008994 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8995 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8996 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008997 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008998 return FalseResult;
8999 }
John McCall864e3962010-05-07 05:32:02 +00009000 case Expr::ConditionalOperatorClass: {
9001 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9002 // If the condition (ignoring parens) is a __builtin_constant_p call,
9003 // then only the true side is actually considered in an integer constant
9004 // expression, and it is fully evaluated. This is an important GNU
9005 // extension. See GCC PR38377 for discussion.
9006 if (const CallExpr *CallCE
9007 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009008 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009009 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009010 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009011 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009012 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009013
Richard Smithf57d8cb2011-12-09 22:58:01 +00009014 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9015 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009016
Richard Smith9e575da2012-12-28 13:25:52 +00009017 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009018 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009019 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009020 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009021 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009022 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009023 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009024 return NoDiag();
9025 // Rare case where the diagnostics depend on which side is evaluated
9026 // Note that if we get here, CondResult is 0, and at least one of
9027 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009028 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009029 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009030 return TrueResult;
9031 }
9032 case Expr::CXXDefaultArgExprClass:
9033 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009034 case Expr::CXXDefaultInitExprClass:
9035 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009036 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009037 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009038 }
9039 }
9040
David Blaikiee4d798f2012-01-20 21:50:17 +00009041 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009042}
9043
Richard Smithf57d8cb2011-12-09 22:58:01 +00009044/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009045static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009046 const Expr *E,
9047 llvm::APSInt *Value,
9048 SourceLocation *Loc) {
9049 if (!E->getType()->isIntegralOrEnumerationType()) {
9050 if (Loc) *Loc = E->getExprLoc();
9051 return false;
9052 }
9053
Richard Smith66e05fe2012-01-18 05:21:49 +00009054 APValue Result;
9055 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009056 return false;
9057
Richard Smith98710fc2014-11-13 23:03:19 +00009058 if (!Result.isInt()) {
9059 if (Loc) *Loc = E->getExprLoc();
9060 return false;
9061 }
9062
Richard Smith66e05fe2012-01-18 05:21:49 +00009063 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009064 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009065}
9066
Craig Toppera31a8822013-08-22 07:09:37 +00009067bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9068 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009069 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009070 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009071
Richard Smith9e575da2012-12-28 13:25:52 +00009072 ICEDiag D = CheckICE(this, Ctx);
9073 if (D.Kind != IK_ICE) {
9074 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009075 return false;
9076 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009077 return true;
9078}
9079
Craig Toppera31a8822013-08-22 07:09:37 +00009080bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009081 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009082 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009083 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9084
9085 if (!isIntegerConstantExpr(Ctx, Loc))
9086 return false;
9087 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009088 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009089 return true;
9090}
Richard Smith66e05fe2012-01-18 05:21:49 +00009091
Craig Toppera31a8822013-08-22 07:09:37 +00009092bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009093 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009094}
9095
Craig Toppera31a8822013-08-22 07:09:37 +00009096bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009097 SourceLocation *Loc) const {
9098 // We support this checking in C++98 mode in order to diagnose compatibility
9099 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009100 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009101
Richard Smith98a0a492012-02-14 21:38:30 +00009102 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009103 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009104 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009105 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009106 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009107
9108 APValue Scratch;
9109 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9110
9111 if (!Diags.empty()) {
9112 IsConstExpr = false;
9113 if (Loc) *Loc = Diags[0].first;
9114 } else if (!IsConstExpr) {
9115 // FIXME: This shouldn't happen.
9116 if (Loc) *Loc = getExprLoc();
9117 }
9118
9119 return IsConstExpr;
9120}
Richard Smith253c2a32012-01-27 01:14:48 +00009121
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009122bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9123 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009124 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009125 Expr::EvalStatus Status;
9126 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9127
9128 ArgVector ArgValues(Args.size());
9129 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9130 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009131 if ((*I)->isValueDependent() ||
9132 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009133 // If evaluation fails, throw away the argument entirely.
9134 ArgValues[I - Args.begin()] = APValue();
9135 if (Info.EvalStatus.HasSideEffects)
9136 return false;
9137 }
9138
9139 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009140 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009141 ArgValues.data());
9142 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9143}
9144
Richard Smith253c2a32012-01-27 01:14:48 +00009145bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009146 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009147 PartialDiagnosticAt> &Diags) {
9148 // FIXME: It would be useful to check constexpr function templates, but at the
9149 // moment the constant expression evaluator cannot cope with the non-rigorous
9150 // ASTs which we build for dependent expressions.
9151 if (FD->isDependentContext())
9152 return true;
9153
9154 Expr::EvalStatus Status;
9155 Status.Diag = &Diags;
9156
Richard Smith6d4c6582013-11-05 22:18:15 +00009157 EvalInfo Info(FD->getASTContext(), Status,
9158 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009159
9160 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009161 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009162
Richard Smith7525ff62013-05-09 07:14:00 +00009163 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009164 // is a temporary being used as the 'this' pointer.
9165 LValue This;
9166 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009167 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009168
Richard Smith253c2a32012-01-27 01:14:48 +00009169 ArrayRef<const Expr*> Args;
9170
9171 SourceLocation Loc = FD->getLocation();
9172
Richard Smith2e312c82012-03-03 22:46:17 +00009173 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009174 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9175 // Evaluate the call as a constant initializer, to allow the construction
9176 // of objects of non-literal types.
9177 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009178 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009179 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009180 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00009181 Args, FD->getBody(), Info, Scratch);
9182
9183 return Diags.empty();
9184}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009185
9186bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9187 const FunctionDecl *FD,
9188 SmallVectorImpl<
9189 PartialDiagnosticAt> &Diags) {
9190 Expr::EvalStatus Status;
9191 Status.Diag = &Diags;
9192
9193 EvalInfo Info(FD->getASTContext(), Status,
9194 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9195
9196 // Fabricate a call stack frame to give the arguments a plausible cover story.
9197 ArrayRef<const Expr*> Args;
9198 ArgVector ArgValues(0);
9199 bool Success = EvaluateArgs(Args, ArgValues, Info);
9200 (void)Success;
9201 assert(Success &&
9202 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009203 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009204
9205 APValue ResultScratch;
9206 Evaluate(ResultScratch, Info, E);
9207 return Diags.empty();
9208}