blob: 9bd630a272fd7dc874ff3049908bf33f5681ff9e [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;
Richard Smithf6f003a2011-12-16 19:06:07 +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 }
John McCall93d91dc2010-05-07 17:22:02 +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.
1332 if (Info.getLangOpts().CPlusPlus1y && 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 Smithb228a862012-02-15 02:18:13 +00001356 // Core issue 1454: For a literal constant expression of array or class type,
1357 // each subobject of its value shall have been initialized by a constant
1358 // expression.
1359 if (Value.isArray()) {
1360 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1361 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1362 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1363 Value.getArrayInitializedElt(I)))
1364 return false;
1365 }
1366 if (!Value.hasArrayFiller())
1367 return true;
1368 return CheckConstantExpression(Info, DiagLoc, EltTy,
1369 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001370 }
Richard Smithb228a862012-02-15 02:18:13 +00001371 if (Value.isUnion() && Value.getUnionField()) {
1372 return CheckConstantExpression(Info, DiagLoc,
1373 Value.getUnionField()->getType(),
1374 Value.getUnionValue());
1375 }
1376 if (Value.isStruct()) {
1377 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1378 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1379 unsigned BaseIndex = 0;
1380 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1381 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1382 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1383 Value.getStructBase(BaseIndex)))
1384 return false;
1385 }
1386 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001387 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001388 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1389 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001390 return false;
1391 }
1392 }
1393
1394 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001395 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001396 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001397 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1398 }
1399
1400 // Everything else is fine.
1401 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001402}
1403
Richard Smith83c68212011-10-31 05:11:32 +00001404const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001405 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001406}
1407
1408static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001409 if (Value.CallIndex)
1410 return false;
1411 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1412 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001413}
1414
Richard Smithcecf1842011-11-01 21:06:14 +00001415static bool IsWeakLValue(const LValue &Value) {
1416 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001417 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001418}
1419
Richard Smith2e312c82012-03-03 22:46:17 +00001420static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001421 // A null base expression indicates a null pointer. These are always
1422 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001423 if (!Value.getLValueBase()) {
1424 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001425 return true;
1426 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001427
Richard Smith027bf112011-11-17 22:56:20 +00001428 // We have a non-null base. These are generally known to be true, but if it's
1429 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001430 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001431 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001432 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001433}
1434
Richard Smith2e312c82012-03-03 22:46:17 +00001435static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001436 switch (Val.getKind()) {
1437 case APValue::Uninitialized:
1438 return false;
1439 case APValue::Int:
1440 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001441 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001442 case APValue::Float:
1443 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001444 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001445 case APValue::ComplexInt:
1446 Result = Val.getComplexIntReal().getBoolValue() ||
1447 Val.getComplexIntImag().getBoolValue();
1448 return true;
1449 case APValue::ComplexFloat:
1450 Result = !Val.getComplexFloatReal().isZero() ||
1451 !Val.getComplexFloatImag().isZero();
1452 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001453 case APValue::LValue:
1454 return EvalPointerValueAsBool(Val, Result);
1455 case APValue::MemberPointer:
1456 Result = Val.getMemberPointerDecl();
1457 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001458 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001459 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001460 case APValue::Struct:
1461 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001462 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001463 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001464 }
1465
Richard Smith11562c52011-10-28 17:51:58 +00001466 llvm_unreachable("unknown APValue kind");
1467}
1468
1469static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1470 EvalInfo &Info) {
1471 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001472 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001473 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001474 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001475 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001476}
1477
Richard Smith357362d2011-12-13 06:39:58 +00001478template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001479static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001480 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001481 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001482 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001483}
1484
1485static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1486 QualType SrcType, const APFloat &Value,
1487 QualType DestType, APSInt &Result) {
1488 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001489 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001490 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001491
Richard Smith357362d2011-12-13 06:39:58 +00001492 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001493 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001494 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1495 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001496 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001497 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001498}
1499
Richard Smith357362d2011-12-13 06:39:58 +00001500static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1501 QualType SrcType, QualType DestType,
1502 APFloat &Result) {
1503 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001504 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001505 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1506 APFloat::rmNearestTiesToEven, &ignored)
1507 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001508 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001509 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001510}
1511
Richard Smith911e1422012-01-30 22:27:01 +00001512static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1513 QualType DestType, QualType SrcType,
1514 APSInt &Value) {
1515 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001516 APSInt Result = Value;
1517 // Figure out if this is a truncate, extend or noop cast.
1518 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001519 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001520 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001521 return Result;
1522}
1523
Richard Smith357362d2011-12-13 06:39:58 +00001524static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1525 QualType SrcType, const APSInt &Value,
1526 QualType DestType, APFloat &Result) {
1527 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1528 if (Result.convertFromAPInt(Value, Value.isSigned(),
1529 APFloat::rmNearestTiesToEven)
1530 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001531 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001532 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001533}
1534
Richard Smith49ca8aa2013-08-06 07:09:20 +00001535static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1536 APValue &Value, const FieldDecl *FD) {
1537 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1538
1539 if (!Value.isInt()) {
1540 // Trying to store a pointer-cast-to-integer into a bitfield.
1541 // FIXME: In this case, we should provide the diagnostic for casting
1542 // a pointer to an integer.
1543 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1544 Info.Diag(E);
1545 return false;
1546 }
1547
1548 APSInt &Int = Value.getInt();
1549 unsigned OldBitWidth = Int.getBitWidth();
1550 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1551 if (NewBitWidth < OldBitWidth)
1552 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1553 return true;
1554}
1555
Eli Friedman803acb32011-12-22 03:51:45 +00001556static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1557 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001558 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001559 if (!Evaluate(SVal, Info, E))
1560 return false;
1561 if (SVal.isInt()) {
1562 Res = SVal.getInt();
1563 return true;
1564 }
1565 if (SVal.isFloat()) {
1566 Res = SVal.getFloat().bitcastToAPInt();
1567 return true;
1568 }
1569 if (SVal.isVector()) {
1570 QualType VecTy = E->getType();
1571 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1572 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1573 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1574 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1575 Res = llvm::APInt::getNullValue(VecSize);
1576 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1577 APValue &Elt = SVal.getVectorElt(i);
1578 llvm::APInt EltAsInt;
1579 if (Elt.isInt()) {
1580 EltAsInt = Elt.getInt();
1581 } else if (Elt.isFloat()) {
1582 EltAsInt = Elt.getFloat().bitcastToAPInt();
1583 } else {
1584 // Don't try to handle vectors of anything other than int or float
1585 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001586 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001587 return false;
1588 }
1589 unsigned BaseEltSize = EltAsInt.getBitWidth();
1590 if (BigEndian)
1591 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1592 else
1593 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1594 }
1595 return true;
1596 }
1597 // Give up if the input isn't an int, float, or vector. For example, we
1598 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001599 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001600 return false;
1601}
1602
Richard Smith43e77732013-05-07 04:50:00 +00001603/// Perform the given integer operation, which is known to need at most BitWidth
1604/// bits, and check for overflow in the original type (if that type was not an
1605/// unsigned type).
1606template<typename Operation>
1607static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1608 const APSInt &LHS, const APSInt &RHS,
1609 unsigned BitWidth, Operation Op) {
1610 if (LHS.isUnsigned())
1611 return Op(LHS, RHS);
1612
1613 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1614 APSInt Result = Value.trunc(LHS.getBitWidth());
1615 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001616 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001617 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1618 diag::warn_integer_constant_overflow)
1619 << Result.toString(10) << E->getType();
1620 else
1621 HandleOverflow(Info, E, Value, E->getType());
1622 }
1623 return Result;
1624}
1625
1626/// Perform the given binary integer operation.
1627static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1628 BinaryOperatorKind Opcode, APSInt RHS,
1629 APSInt &Result) {
1630 switch (Opcode) {
1631 default:
1632 Info.Diag(E);
1633 return false;
1634 case BO_Mul:
1635 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1636 std::multiplies<APSInt>());
1637 return true;
1638 case BO_Add:
1639 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1640 std::plus<APSInt>());
1641 return true;
1642 case BO_Sub:
1643 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1644 std::minus<APSInt>());
1645 return true;
1646 case BO_And: Result = LHS & RHS; return true;
1647 case BO_Xor: Result = LHS ^ RHS; return true;
1648 case BO_Or: Result = LHS | RHS; return true;
1649 case BO_Div:
1650 case BO_Rem:
1651 if (RHS == 0) {
1652 Info.Diag(E, diag::note_expr_divide_by_zero);
1653 return false;
1654 }
1655 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1656 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1657 LHS.isSigned() && LHS.isMinSignedValue())
1658 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1659 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1660 return true;
1661 case BO_Shl: {
1662 if (Info.getLangOpts().OpenCL)
1663 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1664 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1665 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1666 RHS.isUnsigned());
1667 else if (RHS.isSigned() && RHS.isNegative()) {
1668 // During constant-folding, a negative shift is an opposite shift. Such
1669 // a shift is not a constant expression.
1670 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1671 RHS = -RHS;
1672 goto shift_right;
1673 }
1674 shift_left:
1675 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1676 // the shifted type.
1677 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1678 if (SA != RHS) {
1679 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1680 << RHS << E->getType() << LHS.getBitWidth();
1681 } else if (LHS.isSigned()) {
1682 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1683 // operand, and must not overflow the corresponding unsigned type.
1684 if (LHS.isNegative())
1685 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1686 else if (LHS.countLeadingZeros() < SA)
1687 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1688 }
1689 Result = LHS << SA;
1690 return true;
1691 }
1692 case BO_Shr: {
1693 if (Info.getLangOpts().OpenCL)
1694 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1695 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1696 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1697 RHS.isUnsigned());
1698 else if (RHS.isSigned() && RHS.isNegative()) {
1699 // During constant-folding, a negative shift is an opposite shift. Such a
1700 // shift is not a constant expression.
1701 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1702 RHS = -RHS;
1703 goto shift_left;
1704 }
1705 shift_right:
1706 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1707 // shifted type.
1708 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1709 if (SA != RHS)
1710 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1711 << RHS << E->getType() << LHS.getBitWidth();
1712 Result = LHS >> SA;
1713 return true;
1714 }
1715
1716 case BO_LT: Result = LHS < RHS; return true;
1717 case BO_GT: Result = LHS > RHS; return true;
1718 case BO_LE: Result = LHS <= RHS; return true;
1719 case BO_GE: Result = LHS >= RHS; return true;
1720 case BO_EQ: Result = LHS == RHS; return true;
1721 case BO_NE: Result = LHS != RHS; return true;
1722 }
1723}
1724
Richard Smith861b5b52013-05-07 23:34:45 +00001725/// Perform the given binary floating-point operation, in-place, on LHS.
1726static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1727 APFloat &LHS, BinaryOperatorKind Opcode,
1728 const APFloat &RHS) {
1729 switch (Opcode) {
1730 default:
1731 Info.Diag(E);
1732 return false;
1733 case BO_Mul:
1734 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1735 break;
1736 case BO_Add:
1737 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1738 break;
1739 case BO_Sub:
1740 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1741 break;
1742 case BO_Div:
1743 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1744 break;
1745 }
1746
1747 if (LHS.isInfinity() || LHS.isNaN())
1748 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1749 return true;
1750}
1751
Richard Smitha8105bc2012-01-06 16:39:00 +00001752/// Cast an lvalue referring to a base subobject to a derived class, by
1753/// truncating the lvalue's path to the given length.
1754static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1755 const RecordDecl *TruncatedType,
1756 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001757 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001758
1759 // Check we actually point to a derived class object.
1760 if (TruncatedElements == D.Entries.size())
1761 return true;
1762 assert(TruncatedElements >= D.MostDerivedPathLength &&
1763 "not casting to a derived class");
1764 if (!Result.checkSubobject(Info, E, CSK_Derived))
1765 return false;
1766
1767 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001768 const RecordDecl *RD = TruncatedType;
1769 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001770 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1772 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001773 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001774 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001775 else
Richard Smithd62306a2011-11-10 06:34:14 +00001776 Result.Offset -= Layout.getBaseClassOffset(Base);
1777 RD = Base;
1778 }
Richard Smith027bf112011-11-17 22:56:20 +00001779 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001780 return true;
1781}
1782
John McCalld7bca762012-05-01 00:38:49 +00001783static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001784 const CXXRecordDecl *Derived,
1785 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001786 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001787 if (!RL) {
1788 if (Derived->isInvalidDecl()) return false;
1789 RL = &Info.Ctx.getASTRecordLayout(Derived);
1790 }
1791
Richard Smithd62306a2011-11-10 06:34:14 +00001792 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001793 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001794 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001795}
1796
Richard Smitha8105bc2012-01-06 16:39:00 +00001797static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001798 const CXXRecordDecl *DerivedDecl,
1799 const CXXBaseSpecifier *Base) {
1800 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1801
John McCalld7bca762012-05-01 00:38:49 +00001802 if (!Base->isVirtual())
1803 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001804
Richard Smitha8105bc2012-01-06 16:39:00 +00001805 SubobjectDesignator &D = Obj.Designator;
1806 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001807 return false;
1808
Richard Smitha8105bc2012-01-06 16:39:00 +00001809 // Extract most-derived object and corresponding type.
1810 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1811 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1812 return false;
1813
1814 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001815 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001816 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1817 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001818 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001819 return true;
1820}
1821
Richard Smith84401042013-06-03 05:03:02 +00001822static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1823 QualType Type, LValue &Result) {
1824 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1825 PathE = E->path_end();
1826 PathI != PathE; ++PathI) {
1827 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1828 *PathI))
1829 return false;
1830 Type = (*PathI)->getType();
1831 }
1832 return true;
1833}
1834
Richard Smithd62306a2011-11-10 06:34:14 +00001835/// Update LVal to refer to the given field, which must be a member of the type
1836/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001837static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001838 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001839 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001840 if (!RL) {
1841 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001842 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001843 }
Richard Smithd62306a2011-11-10 06:34:14 +00001844
1845 unsigned I = FD->getFieldIndex();
1846 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001847 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001848 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001849}
1850
Richard Smith1b78b3d2012-01-25 22:15:11 +00001851/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001852static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001853 LValue &LVal,
1854 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001855 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001856 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001857 return false;
1858 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001859}
1860
Richard Smithd62306a2011-11-10 06:34:14 +00001861/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001862static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1863 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001864 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1865 // extension.
1866 if (Type->isVoidType() || Type->isFunctionType()) {
1867 Size = CharUnits::One();
1868 return true;
1869 }
1870
1871 if (!Type->isConstantSizeType()) {
1872 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001873 // FIXME: Better diagnostic.
1874 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001875 return false;
1876 }
1877
1878 Size = Info.Ctx.getTypeSizeInChars(Type);
1879 return true;
1880}
1881
1882/// Update a pointer value to model pointer arithmetic.
1883/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001884/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001885/// \param LVal - The pointer value to be updated.
1886/// \param EltTy - The pointee type represented by LVal.
1887/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001888static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1889 LValue &LVal, QualType EltTy,
1890 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001891 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001892 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001893 return false;
1894
1895 // Compute the new offset in the appropriate width.
1896 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001897 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001898 return true;
1899}
1900
Richard Smith66c96992012-02-18 22:04:06 +00001901/// Update an lvalue to refer to a component of a complex number.
1902/// \param Info - Information about the ongoing evaluation.
1903/// \param LVal - The lvalue to be updated.
1904/// \param EltTy - The complex number's component type.
1905/// \param Imag - False for the real component, true for the imaginary.
1906static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1907 LValue &LVal, QualType EltTy,
1908 bool Imag) {
1909 if (Imag) {
1910 CharUnits SizeOfComponent;
1911 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1912 return false;
1913 LVal.Offset += SizeOfComponent;
1914 }
1915 LVal.addComplex(Info, E, EltTy, Imag);
1916 return true;
1917}
1918
Richard Smith27908702011-10-24 17:54:18 +00001919/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001920///
1921/// \param Info Information about the ongoing evaluation.
1922/// \param E An expression to be used when printing diagnostics.
1923/// \param VD The variable whose initializer should be obtained.
1924/// \param Frame The frame in which the variable was created. Must be null
1925/// if this variable is not local to the evaluation.
1926/// \param Result Filled in with a pointer to the value of the variable.
1927static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1928 const VarDecl *VD, CallStackFrame *Frame,
1929 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001930 // If this is a parameter to an active constexpr function call, perform
1931 // argument substitution.
1932 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001933 // Assume arguments of a potential constant expression are unknown
1934 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001935 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001936 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001937 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001938 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001939 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001940 }
Richard Smith3229b742013-05-05 21:17:10 +00001941 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001942 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001943 }
Richard Smith27908702011-10-24 17:54:18 +00001944
Richard Smithd9f663b2013-04-22 15:31:51 +00001945 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001946 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001947 Result = Frame->getTemporary(VD);
1948 assert(Result && "missing value for local variable");
1949 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001950 }
1951
Richard Smithd0b4dd62011-12-19 06:19:21 +00001952 // Dig out the initializer, and use the declaration which it's attached to.
1953 const Expr *Init = VD->getAnyInitializer(VD);
1954 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001955 // If we're checking a potential constant expression, the variable could be
1956 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001957 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001958 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001959 return false;
1960 }
1961
Richard Smithd62306a2011-11-10 06:34:14 +00001962 // If we're currently evaluating the initializer of this declaration, use that
1963 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001964 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001965 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001966 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001967 }
1968
Richard Smithcecf1842011-11-01 21:06:14 +00001969 // Never evaluate the initializer of a weak variable. We can't be sure that
1970 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001971 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001972 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001973 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001974 }
Richard Smithcecf1842011-11-01 21:06:14 +00001975
Richard Smithd0b4dd62011-12-19 06:19:21 +00001976 // Check that we can fold the initializer. In C++, we will have already done
1977 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001978 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001979 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001980 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001981 Notes.size() + 1) << VD;
1982 Info.Note(VD->getLocation(), diag::note_declared_at);
1983 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001984 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001985 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001986 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001987 Notes.size() + 1) << VD;
1988 Info.Note(VD->getLocation(), diag::note_declared_at);
1989 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001990 }
Richard Smith27908702011-10-24 17:54:18 +00001991
Richard Smith3229b742013-05-05 21:17:10 +00001992 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001993 return true;
Richard Smith27908702011-10-24 17:54:18 +00001994}
1995
Richard Smith11562c52011-10-28 17:51:58 +00001996static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001997 Qualifiers Quals = T.getQualifiers();
1998 return Quals.hasConst() && !Quals.hasVolatile();
1999}
2000
Richard Smithe97cbd72011-11-11 04:05:33 +00002001/// Get the base index of the given base class within an APValue representing
2002/// the given derived class.
2003static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2004 const CXXRecordDecl *Base) {
2005 Base = Base->getCanonicalDecl();
2006 unsigned Index = 0;
2007 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2008 E = Derived->bases_end(); I != E; ++I, ++Index) {
2009 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2010 return Index;
2011 }
2012
2013 llvm_unreachable("base class missing from derived class's bases list");
2014}
2015
Richard Smith3da88fa2013-04-26 14:36:30 +00002016/// Extract the value of a character from a string literal.
2017static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2018 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00002019 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00002020 const StringLiteral *S = cast<StringLiteral>(Lit);
2021 const ConstantArrayType *CAT =
2022 Info.Ctx.getAsConstantArrayType(S->getType());
2023 assert(CAT && "string literal isn't an array");
2024 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002025 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002026
2027 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002028 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002029 if (Index < S->getLength())
2030 Value = S->getCodeUnit(Index);
2031 return Value;
2032}
2033
Richard Smith3da88fa2013-04-26 14:36:30 +00002034// Expand a string literal into an array of characters.
2035static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2036 APValue &Result) {
2037 const StringLiteral *S = cast<StringLiteral>(Lit);
2038 const ConstantArrayType *CAT =
2039 Info.Ctx.getAsConstantArrayType(S->getType());
2040 assert(CAT && "string literal isn't an array");
2041 QualType CharType = CAT->getElementType();
2042 assert(CharType->isIntegerType() && "unexpected character type");
2043
2044 unsigned Elts = CAT->getSize().getZExtValue();
2045 Result = APValue(APValue::UninitArray(),
2046 std::min(S->getLength(), Elts), Elts);
2047 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2048 CharType->isUnsignedIntegerType());
2049 if (Result.hasArrayFiller())
2050 Result.getArrayFiller() = APValue(Value);
2051 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2052 Value = S->getCodeUnit(I);
2053 Result.getArrayInitializedElt(I) = APValue(Value);
2054 }
2055}
2056
2057// Expand an array so that it has more than Index filled elements.
2058static void expandArray(APValue &Array, unsigned Index) {
2059 unsigned Size = Array.getArraySize();
2060 assert(Index < Size);
2061
2062 // Always at least double the number of elements for which we store a value.
2063 unsigned OldElts = Array.getArrayInitializedElts();
2064 unsigned NewElts = std::max(Index+1, OldElts * 2);
2065 NewElts = std::min(Size, std::max(NewElts, 8u));
2066
2067 // Copy the data across.
2068 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2069 for (unsigned I = 0; I != OldElts; ++I)
2070 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2071 for (unsigned I = OldElts; I != NewElts; ++I)
2072 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2073 if (NewValue.hasArrayFiller())
2074 NewValue.getArrayFiller() = Array.getArrayFiller();
2075 Array.swap(NewValue);
2076}
2077
Richard Smith861b5b52013-05-07 23:34:45 +00002078/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002079enum AccessKinds {
2080 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002081 AK_Assign,
2082 AK_Increment,
2083 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002084};
2085
Richard Smith3229b742013-05-05 21:17:10 +00002086/// A handle to a complete object (an object that is not a subobject of
2087/// another object).
2088struct CompleteObject {
2089 /// The value of the complete object.
2090 APValue *Value;
2091 /// The type of the complete object.
2092 QualType Type;
2093
Craig Topper36250ad2014-05-12 05:36:57 +00002094 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002095 CompleteObject(APValue *Value, QualType Type)
2096 : Value(Value), Type(Type) {
2097 assert(Value && "missing value for complete object");
2098 }
2099
David Blaikie7d170102013-05-15 07:37:26 +00002100 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002101};
2102
Richard Smith3da88fa2013-04-26 14:36:30 +00002103/// Find the designated sub-object of an rvalue.
2104template<typename SubobjectHandler>
2105typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002106findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002107 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002108 if (Sub.Invalid)
2109 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002110 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002111 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002112 if (Info.getLangOpts().CPlusPlus11)
2113 Info.Diag(E, diag::note_constexpr_access_past_end)
2114 << handler.AccessKind;
2115 else
2116 Info.Diag(E);
2117 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002118 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002119
Richard Smith3229b742013-05-05 21:17:10 +00002120 APValue *O = Obj.Value;
2121 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002122 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002123
Richard Smithd62306a2011-11-10 06:34:14 +00002124 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002125 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2126 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002127 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002128 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2129 return handler.failed();
2130 }
2131
Richard Smith49ca8aa2013-08-06 07:09:20 +00002132 if (I == N) {
2133 if (!handler.found(*O, ObjType))
2134 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002135
Richard Smith49ca8aa2013-08-06 07:09:20 +00002136 // If we modified a bit-field, truncate it to the right width.
2137 if (handler.AccessKind != AK_Read &&
2138 LastField && LastField->isBitField() &&
2139 !truncateBitfieldValue(Info, E, *O, LastField))
2140 return false;
2141
2142 return true;
2143 }
2144
Craig Topper36250ad2014-05-12 05:36:57 +00002145 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002146 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002147 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002148 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002149 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002150 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002151 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002152 // Note, it should not be possible to form a pointer with a valid
2153 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002154 if (Info.getLangOpts().CPlusPlus11)
2155 Info.Diag(E, diag::note_constexpr_access_past_end)
2156 << handler.AccessKind;
2157 else
2158 Info.Diag(E);
2159 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002160 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002161
2162 ObjType = CAT->getElementType();
2163
Richard Smith14a94132012-02-17 03:35:37 +00002164 // An array object is represented as either an Array APValue or as an
2165 // LValue which refers to a string literal.
2166 if (O->isLValue()) {
2167 assert(I == N - 1 && "extracting subobject of character?");
2168 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002169 if (handler.AccessKind != AK_Read)
2170 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2171 *O);
2172 else
2173 return handler.foundString(*O, ObjType, Index);
2174 }
2175
2176 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002177 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002178 else if (handler.AccessKind != AK_Read) {
2179 expandArray(*O, Index);
2180 O = &O->getArrayInitializedElt(Index);
2181 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002182 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002183 } else if (ObjType->isAnyComplexType()) {
2184 // Next subobject is a complex number.
2185 uint64_t Index = Sub.Entries[I].ArrayIndex;
2186 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002187 if (Info.getLangOpts().CPlusPlus11)
2188 Info.Diag(E, diag::note_constexpr_access_past_end)
2189 << handler.AccessKind;
2190 else
2191 Info.Diag(E);
2192 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002193 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002194
2195 bool WasConstQualified = ObjType.isConstQualified();
2196 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2197 if (WasConstQualified)
2198 ObjType.addConst();
2199
Richard Smith66c96992012-02-18 22:04:06 +00002200 assert(I == N - 1 && "extracting subobject of scalar?");
2201 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002202 return handler.found(Index ? O->getComplexIntImag()
2203 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002204 } else {
2205 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002206 return handler.found(Index ? O->getComplexFloatImag()
2207 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002208 }
Richard Smithd62306a2011-11-10 06:34:14 +00002209 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002210 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002211 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002212 << Field;
2213 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002214 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002215 }
2216
Richard Smithd62306a2011-11-10 06:34:14 +00002217 // Next subobject is a class, struct or union field.
2218 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2219 if (RD->isUnion()) {
2220 const FieldDecl *UnionField = O->getUnionField();
2221 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002222 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002223 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2224 << handler.AccessKind << Field << !UnionField << UnionField;
2225 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002226 }
Richard Smithd62306a2011-11-10 06:34:14 +00002227 O = &O->getUnionValue();
2228 } else
2229 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002230
2231 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002232 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002233 if (WasConstQualified && !Field->isMutable())
2234 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002235
2236 if (ObjType.isVolatileQualified()) {
2237 if (Info.getLangOpts().CPlusPlus) {
2238 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002239 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2240 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002241 Info.Note(Field->getLocation(), diag::note_declared_at);
2242 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002243 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002244 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002245 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002246 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002247
2248 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002249 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002250 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002251 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2252 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2253 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002254
2255 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002256 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002257 if (WasConstQualified)
2258 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002259 }
2260 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002261}
2262
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002263namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002264struct ExtractSubobjectHandler {
2265 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002266 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002267
2268 static const AccessKinds AccessKind = AK_Read;
2269
2270 typedef bool result_type;
2271 bool failed() { return false; }
2272 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002273 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002274 return true;
2275 }
2276 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002277 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002278 return true;
2279 }
2280 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002281 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002282 return true;
2283 }
2284 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002285 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002286 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2287 return true;
2288 }
2289};
Richard Smith3229b742013-05-05 21:17:10 +00002290} // end anonymous namespace
2291
Richard Smith3da88fa2013-04-26 14:36:30 +00002292const AccessKinds ExtractSubobjectHandler::AccessKind;
2293
2294/// Extract the designated sub-object of an rvalue.
2295static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002296 const CompleteObject &Obj,
2297 const SubobjectDesignator &Sub,
2298 APValue &Result) {
2299 ExtractSubobjectHandler Handler = { Info, Result };
2300 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002301}
2302
Richard Smith3229b742013-05-05 21:17:10 +00002303namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002304struct ModifySubobjectHandler {
2305 EvalInfo &Info;
2306 APValue &NewVal;
2307 const Expr *E;
2308
2309 typedef bool result_type;
2310 static const AccessKinds AccessKind = AK_Assign;
2311
2312 bool checkConst(QualType QT) {
2313 // Assigning to a const object has undefined behavior.
2314 if (QT.isConstQualified()) {
2315 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2316 return false;
2317 }
2318 return true;
2319 }
2320
2321 bool failed() { return false; }
2322 bool found(APValue &Subobj, QualType SubobjType) {
2323 if (!checkConst(SubobjType))
2324 return false;
2325 // We've been given ownership of NewVal, so just swap it in.
2326 Subobj.swap(NewVal);
2327 return true;
2328 }
2329 bool found(APSInt &Value, QualType SubobjType) {
2330 if (!checkConst(SubobjType))
2331 return false;
2332 if (!NewVal.isInt()) {
2333 // Maybe trying to write a cast pointer value into a complex?
2334 Info.Diag(E);
2335 return false;
2336 }
2337 Value = NewVal.getInt();
2338 return true;
2339 }
2340 bool found(APFloat &Value, QualType SubobjType) {
2341 if (!checkConst(SubobjType))
2342 return false;
2343 Value = NewVal.getFloat();
2344 return true;
2345 }
2346 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2347 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2348 }
2349};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002350} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002351
Richard Smith3229b742013-05-05 21:17:10 +00002352const AccessKinds ModifySubobjectHandler::AccessKind;
2353
Richard Smith3da88fa2013-04-26 14:36:30 +00002354/// Update the designated sub-object of an rvalue to the given value.
2355static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002356 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002357 const SubobjectDesignator &Sub,
2358 APValue &NewVal) {
2359 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002360 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002361}
2362
Richard Smith84f6dcf2012-02-02 01:16:57 +00002363/// Find the position where two subobject designators diverge, or equivalently
2364/// the length of the common initial subsequence.
2365static unsigned FindDesignatorMismatch(QualType ObjType,
2366 const SubobjectDesignator &A,
2367 const SubobjectDesignator &B,
2368 bool &WasArrayIndex) {
2369 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2370 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002371 if (!ObjType.isNull() &&
2372 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002373 // Next subobject is an array element.
2374 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2375 WasArrayIndex = true;
2376 return I;
2377 }
Richard Smith66c96992012-02-18 22:04:06 +00002378 if (ObjType->isAnyComplexType())
2379 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2380 else
2381 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002382 } else {
2383 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2384 WasArrayIndex = false;
2385 return I;
2386 }
2387 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2388 // Next subobject is a field.
2389 ObjType = FD->getType();
2390 else
2391 // Next subobject is a base class.
2392 ObjType = QualType();
2393 }
2394 }
2395 WasArrayIndex = false;
2396 return I;
2397}
2398
2399/// Determine whether the given subobject designators refer to elements of the
2400/// same array object.
2401static bool AreElementsOfSameArray(QualType ObjType,
2402 const SubobjectDesignator &A,
2403 const SubobjectDesignator &B) {
2404 if (A.Entries.size() != B.Entries.size())
2405 return false;
2406
2407 bool IsArray = A.MostDerivedArraySize != 0;
2408 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2409 // A is a subobject of the array element.
2410 return false;
2411
2412 // If A (and B) designates an array element, the last entry will be the array
2413 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2414 // of length 1' case, and the entire path must match.
2415 bool WasArrayIndex;
2416 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2417 return CommonLength >= A.Entries.size() - IsArray;
2418}
2419
Richard Smith3229b742013-05-05 21:17:10 +00002420/// Find the complete object to which an LValue refers.
2421CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2422 const LValue &LVal, QualType LValType) {
2423 if (!LVal.Base) {
2424 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2425 return CompleteObject();
2426 }
2427
Craig Topper36250ad2014-05-12 05:36:57 +00002428 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002429 if (LVal.CallIndex) {
2430 Frame = Info.getCallFrame(LVal.CallIndex);
2431 if (!Frame) {
2432 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2433 << AK << LVal.Base.is<const ValueDecl*>();
2434 NoteLValueLocation(Info, LVal.Base);
2435 return CompleteObject();
2436 }
Richard Smith3229b742013-05-05 21:17:10 +00002437 }
2438
2439 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2440 // is not a constant expression (even if the object is non-volatile). We also
2441 // apply this rule to C++98, in order to conform to the expected 'volatile'
2442 // semantics.
2443 if (LValType.isVolatileQualified()) {
2444 if (Info.getLangOpts().CPlusPlus)
2445 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2446 << AK << LValType;
2447 else
2448 Info.Diag(E);
2449 return CompleteObject();
2450 }
2451
2452 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002453 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002454 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002455
2456 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2457 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2458 // In C++11, constexpr, non-volatile variables initialized with constant
2459 // expressions are constant expressions too. Inside constexpr functions,
2460 // parameters are constant expressions even if they're non-const.
2461 // In C++1y, objects local to a constant expression (those with a Frame) are
2462 // both readable and writable inside constant expressions.
2463 // In C, such things can also be folded, although they are not ICEs.
2464 const VarDecl *VD = dyn_cast<VarDecl>(D);
2465 if (VD) {
2466 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2467 VD = VDef;
2468 }
2469 if (!VD || VD->isInvalidDecl()) {
2470 Info.Diag(E);
2471 return CompleteObject();
2472 }
2473
2474 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002475 if (BaseType.isVolatileQualified()) {
2476 if (Info.getLangOpts().CPlusPlus) {
2477 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2478 << AK << 1 << VD;
2479 Info.Note(VD->getLocation(), diag::note_declared_at);
2480 } else {
2481 Info.Diag(E);
2482 }
2483 return CompleteObject();
2484 }
2485
2486 // Unless we're looking at a local variable or argument in a constexpr call,
2487 // the variable we're reading must be const.
2488 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002489 if (Info.getLangOpts().CPlusPlus1y &&
2490 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2491 // OK, we can read and modify an object if we're in the process of
2492 // evaluating its initializer, because its lifetime began in this
2493 // evaluation.
2494 } else if (AK != AK_Read) {
2495 // All the remaining cases only permit reading.
2496 Info.Diag(E, diag::note_constexpr_modify_global);
2497 return CompleteObject();
2498 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002499 // OK, we can read this variable.
2500 } else if (BaseType->isIntegralOrEnumerationType()) {
2501 if (!BaseType.isConstQualified()) {
2502 if (Info.getLangOpts().CPlusPlus) {
2503 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2504 Info.Note(VD->getLocation(), diag::note_declared_at);
2505 } else {
2506 Info.Diag(E);
2507 }
2508 return CompleteObject();
2509 }
2510 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2511 // We support folding of const floating-point types, in order to make
2512 // static const data members of such types (supported as an extension)
2513 // more useful.
2514 if (Info.getLangOpts().CPlusPlus11) {
2515 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2516 Info.Note(VD->getLocation(), diag::note_declared_at);
2517 } else {
2518 Info.CCEDiag(E);
2519 }
2520 } else {
2521 // FIXME: Allow folding of values of any literal type in all languages.
2522 if (Info.getLangOpts().CPlusPlus11) {
2523 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2524 Info.Note(VD->getLocation(), diag::note_declared_at);
2525 } else {
2526 Info.Diag(E);
2527 }
2528 return CompleteObject();
2529 }
2530 }
2531
2532 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2533 return CompleteObject();
2534 } else {
2535 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2536
2537 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002538 if (const MaterializeTemporaryExpr *MTE =
2539 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2540 assert(MTE->getStorageDuration() == SD_Static &&
2541 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002542
Richard Smithe6c01442013-06-05 00:46:14 +00002543 // Per C++1y [expr.const]p2:
2544 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2545 // - a [...] glvalue of integral or enumeration type that refers to
2546 // a non-volatile const object [...]
2547 // [...]
2548 // - a [...] glvalue of literal type that refers to a non-volatile
2549 // object whose lifetime began within the evaluation of e.
2550 //
2551 // C++11 misses the 'began within the evaluation of e' check and
2552 // instead allows all temporaries, including things like:
2553 // int &&r = 1;
2554 // int x = ++r;
2555 // constexpr int k = r;
2556 // Therefore we use the C++1y rules in C++11 too.
2557 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2558 const ValueDecl *ED = MTE->getExtendingDecl();
2559 if (!(BaseType.isConstQualified() &&
2560 BaseType->isIntegralOrEnumerationType()) &&
2561 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2562 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2563 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2564 return CompleteObject();
2565 }
2566
2567 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2568 assert(BaseVal && "got reference to unevaluated temporary");
2569 } else {
2570 Info.Diag(E);
2571 return CompleteObject();
2572 }
2573 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002574 BaseVal = Frame->getTemporary(Base);
2575 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002576 }
Richard Smith3229b742013-05-05 21:17:10 +00002577
2578 // Volatile temporary objects cannot be accessed in constant expressions.
2579 if (BaseType.isVolatileQualified()) {
2580 if (Info.getLangOpts().CPlusPlus) {
2581 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2582 << AK << 0;
2583 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2584 } else {
2585 Info.Diag(E);
2586 }
2587 return CompleteObject();
2588 }
2589 }
2590
Richard Smith7525ff62013-05-09 07:14:00 +00002591 // During the construction of an object, it is not yet 'const'.
2592 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2593 // and this doesn't do quite the right thing for const subobjects of the
2594 // object under construction.
2595 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2596 BaseType = Info.Ctx.getCanonicalType(BaseType);
2597 BaseType.removeLocalConst();
2598 }
2599
Richard Smith6d4c6582013-11-05 22:18:15 +00002600 // In C++1y, we can't safely access any mutable state when we might be
2601 // evaluating after an unmodeled side effect or an evaluation failure.
2602 //
2603 // FIXME: Not all local state is mutable. Allow local constant subobjects
2604 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002605 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002606 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002607 return CompleteObject();
2608
2609 return CompleteObject(BaseVal, BaseType);
2610}
2611
Richard Smith243ef902013-05-05 23:31:59 +00002612/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2613/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2614/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002615///
2616/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002617/// \param Conv - The expression for which we are performing the conversion.
2618/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002619/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2620/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002621/// \param LVal - The glvalue on which we are attempting to perform this action.
2622/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002623static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002624 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002625 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002626 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002627 return false;
2628
Richard Smith3229b742013-05-05 21:17:10 +00002629 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002630 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002631 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2632 !Type.isVolatileQualified()) {
2633 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2634 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2635 // initializer until now for such expressions. Such an expression can't be
2636 // an ICE in C, so this only matters for fold.
2637 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2638 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002639 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002640 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002641 }
Richard Smith3229b742013-05-05 21:17:10 +00002642 APValue Lit;
2643 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2644 return false;
2645 CompleteObject LitObj(&Lit, Base->getType());
2646 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2647 } else if (isa<StringLiteral>(Base)) {
2648 // We represent a string literal array as an lvalue pointing at the
2649 // corresponding expression, rather than building an array of chars.
2650 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2651 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2652 CompleteObject StrObj(&Str, Base->getType());
2653 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002654 }
Richard Smith11562c52011-10-28 17:51:58 +00002655 }
2656
Richard Smith3229b742013-05-05 21:17:10 +00002657 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2658 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002659}
2660
2661/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002662static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002663 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002665 return false;
2666
Richard Smith3229b742013-05-05 21:17:10 +00002667 if (!Info.getLangOpts().CPlusPlus1y) {
2668 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 return false;
2670 }
2671
Richard Smith3229b742013-05-05 21:17:10 +00002672 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2673 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002674}
2675
Richard Smith243ef902013-05-05 23:31:59 +00002676static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2677 return T->isSignedIntegerType() &&
2678 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2679}
2680
2681namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002682struct CompoundAssignSubobjectHandler {
2683 EvalInfo &Info;
2684 const Expr *E;
2685 QualType PromotedLHSType;
2686 BinaryOperatorKind Opcode;
2687 const APValue &RHS;
2688
2689 static const AccessKinds AccessKind = AK_Assign;
2690
2691 typedef bool result_type;
2692
2693 bool checkConst(QualType QT) {
2694 // Assigning to a const object has undefined behavior.
2695 if (QT.isConstQualified()) {
2696 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2697 return false;
2698 }
2699 return true;
2700 }
2701
2702 bool failed() { return false; }
2703 bool found(APValue &Subobj, QualType SubobjType) {
2704 switch (Subobj.getKind()) {
2705 case APValue::Int:
2706 return found(Subobj.getInt(), SubobjType);
2707 case APValue::Float:
2708 return found(Subobj.getFloat(), SubobjType);
2709 case APValue::ComplexInt:
2710 case APValue::ComplexFloat:
2711 // FIXME: Implement complex compound assignment.
2712 Info.Diag(E);
2713 return false;
2714 case APValue::LValue:
2715 return foundPointer(Subobj, SubobjType);
2716 default:
2717 // FIXME: can this happen?
2718 Info.Diag(E);
2719 return false;
2720 }
2721 }
2722 bool found(APSInt &Value, QualType SubobjType) {
2723 if (!checkConst(SubobjType))
2724 return false;
2725
2726 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2727 // We don't support compound assignment on integer-cast-to-pointer
2728 // values.
2729 Info.Diag(E);
2730 return false;
2731 }
2732
2733 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2734 SubobjType, Value);
2735 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2736 return false;
2737 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2738 return true;
2739 }
2740 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002741 return checkConst(SubobjType) &&
2742 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2743 Value) &&
2744 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2745 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002746 }
2747 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2748 if (!checkConst(SubobjType))
2749 return false;
2750
2751 QualType PointeeType;
2752 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2753 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002754
2755 if (PointeeType.isNull() || !RHS.isInt() ||
2756 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002757 Info.Diag(E);
2758 return false;
2759 }
2760
Richard Smith861b5b52013-05-07 23:34:45 +00002761 int64_t Offset = getExtValue(RHS.getInt());
2762 if (Opcode == BO_Sub)
2763 Offset = -Offset;
2764
2765 LValue LVal;
2766 LVal.setFrom(Info.Ctx, Subobj);
2767 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2768 return false;
2769 LVal.moveInto(Subobj);
2770 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002771 }
2772 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2773 llvm_unreachable("shouldn't encounter string elements here");
2774 }
2775};
2776} // end anonymous namespace
2777
2778const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2779
2780/// Perform a compound assignment of LVal <op>= RVal.
2781static bool handleCompoundAssignment(
2782 EvalInfo &Info, const Expr *E,
2783 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2784 BinaryOperatorKind Opcode, const APValue &RVal) {
2785 if (LVal.Designator.Invalid)
2786 return false;
2787
2788 if (!Info.getLangOpts().CPlusPlus1y) {
2789 Info.Diag(E);
2790 return false;
2791 }
2792
2793 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2794 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2795 RVal };
2796 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2797}
2798
2799namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002800struct IncDecSubobjectHandler {
2801 EvalInfo &Info;
2802 const Expr *E;
2803 AccessKinds AccessKind;
2804 APValue *Old;
2805
2806 typedef bool result_type;
2807
2808 bool checkConst(QualType QT) {
2809 // Assigning to a const object has undefined behavior.
2810 if (QT.isConstQualified()) {
2811 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2812 return false;
2813 }
2814 return true;
2815 }
2816
2817 bool failed() { return false; }
2818 bool found(APValue &Subobj, QualType SubobjType) {
2819 // Stash the old value. Also clear Old, so we don't clobber it later
2820 // if we're post-incrementing a complex.
2821 if (Old) {
2822 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002823 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002824 }
2825
2826 switch (Subobj.getKind()) {
2827 case APValue::Int:
2828 return found(Subobj.getInt(), SubobjType);
2829 case APValue::Float:
2830 return found(Subobj.getFloat(), SubobjType);
2831 case APValue::ComplexInt:
2832 return found(Subobj.getComplexIntReal(),
2833 SubobjType->castAs<ComplexType>()->getElementType()
2834 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2835 case APValue::ComplexFloat:
2836 return found(Subobj.getComplexFloatReal(),
2837 SubobjType->castAs<ComplexType>()->getElementType()
2838 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2839 case APValue::LValue:
2840 return foundPointer(Subobj, SubobjType);
2841 default:
2842 // FIXME: can this happen?
2843 Info.Diag(E);
2844 return false;
2845 }
2846 }
2847 bool found(APSInt &Value, QualType SubobjType) {
2848 if (!checkConst(SubobjType))
2849 return false;
2850
2851 if (!SubobjType->isIntegerType()) {
2852 // We don't support increment / decrement on integer-cast-to-pointer
2853 // values.
2854 Info.Diag(E);
2855 return false;
2856 }
2857
2858 if (Old) *Old = APValue(Value);
2859
2860 // bool arithmetic promotes to int, and the conversion back to bool
2861 // doesn't reduce mod 2^n, so special-case it.
2862 if (SubobjType->isBooleanType()) {
2863 if (AccessKind == AK_Increment)
2864 Value = 1;
2865 else
2866 Value = !Value;
2867 return true;
2868 }
2869
2870 bool WasNegative = Value.isNegative();
2871 if (AccessKind == AK_Increment) {
2872 ++Value;
2873
2874 if (!WasNegative && Value.isNegative() &&
2875 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2876 APSInt ActualValue(Value, /*IsUnsigned*/true);
2877 HandleOverflow(Info, E, ActualValue, SubobjType);
2878 }
2879 } else {
2880 --Value;
2881
2882 if (WasNegative && !Value.isNegative() &&
2883 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2884 unsigned BitWidth = Value.getBitWidth();
2885 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2886 ActualValue.setBit(BitWidth);
2887 HandleOverflow(Info, E, ActualValue, SubobjType);
2888 }
2889 }
2890 return true;
2891 }
2892 bool found(APFloat &Value, QualType SubobjType) {
2893 if (!checkConst(SubobjType))
2894 return false;
2895
2896 if (Old) *Old = APValue(Value);
2897
2898 APFloat One(Value.getSemantics(), 1);
2899 if (AccessKind == AK_Increment)
2900 Value.add(One, APFloat::rmNearestTiesToEven);
2901 else
2902 Value.subtract(One, APFloat::rmNearestTiesToEven);
2903 return true;
2904 }
2905 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2907 return false;
2908
2909 QualType PointeeType;
2910 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2911 PointeeType = PT->getPointeeType();
2912 else {
2913 Info.Diag(E);
2914 return false;
2915 }
2916
2917 LValue LVal;
2918 LVal.setFrom(Info.Ctx, Subobj);
2919 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2920 AccessKind == AK_Increment ? 1 : -1))
2921 return false;
2922 LVal.moveInto(Subobj);
2923 return true;
2924 }
2925 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2926 llvm_unreachable("shouldn't encounter string elements here");
2927 }
2928};
2929} // end anonymous namespace
2930
2931/// Perform an increment or decrement on LVal.
2932static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2933 QualType LValType, bool IsIncrement, APValue *Old) {
2934 if (LVal.Designator.Invalid)
2935 return false;
2936
2937 if (!Info.getLangOpts().CPlusPlus1y) {
2938 Info.Diag(E);
2939 return false;
2940 }
2941
2942 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2943 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2944 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2945 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2946}
2947
Richard Smithe97cbd72011-11-11 04:05:33 +00002948/// Build an lvalue for the object argument of a member function call.
2949static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2950 LValue &This) {
2951 if (Object->getType()->isPointerType())
2952 return EvaluatePointer(Object, This, Info);
2953
2954 if (Object->isGLValue())
2955 return EvaluateLValue(Object, This, Info);
2956
Richard Smithd9f663b2013-04-22 15:31:51 +00002957 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002958 return EvaluateTemporary(Object, This, Info);
2959
Richard Smith3e79a572014-06-11 19:53:12 +00002960 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002961 return false;
2962}
2963
2964/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2965/// lvalue referring to the result.
2966///
2967/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002968/// \param LV - An lvalue referring to the base of the member pointer.
2969/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002970/// \param IncludeMember - Specifies whether the member itself is included in
2971/// the resulting LValue subobject designator. This is not possible when
2972/// creating a bound member function.
2973/// \return The field or method declaration to which the member pointer refers,
2974/// or 0 if evaluation fails.
2975static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002976 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002977 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002978 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002979 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002980 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002981 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00002982 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00002983
2984 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2985 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002986 if (!MemPtr.getDecl()) {
2987 // FIXME: Specific diagnostic.
2988 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002989 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002990 }
Richard Smith253c2a32012-01-27 01:14:48 +00002991
Richard Smith027bf112011-11-17 22:56:20 +00002992 if (MemPtr.isDerivedMember()) {
2993 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002994 // The end of the derived-to-base path for the base object must match the
2995 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002996 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002997 LV.Designator.Entries.size()) {
2998 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002999 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003000 }
Richard Smith027bf112011-11-17 22:56:20 +00003001 unsigned PathLengthToMember =
3002 LV.Designator.Entries.size() - MemPtr.Path.size();
3003 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3004 const CXXRecordDecl *LVDecl = getAsBaseClass(
3005 LV.Designator.Entries[PathLengthToMember + I]);
3006 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003007 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3008 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003009 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003010 }
Richard Smith027bf112011-11-17 22:56:20 +00003011 }
3012
3013 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003014 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003015 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003016 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003017 } else if (!MemPtr.Path.empty()) {
3018 // Extend the LValue path with the member pointer's path.
3019 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3020 MemPtr.Path.size() + IncludeMember);
3021
3022 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003023 if (const PointerType *PT = LVType->getAs<PointerType>())
3024 LVType = PT->getPointeeType();
3025 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3026 assert(RD && "member pointer access on non-class-type expression");
3027 // The first class in the path is that of the lvalue.
3028 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3029 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003030 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003031 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003032 RD = Base;
3033 }
3034 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003035 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3036 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003037 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003038 }
3039
3040 // Add the member. Note that we cannot build bound member functions here.
3041 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003042 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003043 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003044 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003045 } else if (const IndirectFieldDecl *IFD =
3046 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003047 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003048 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003049 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003050 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003051 }
Richard Smith027bf112011-11-17 22:56:20 +00003052 }
3053
3054 return MemPtr.getDecl();
3055}
3056
Richard Smith84401042013-06-03 05:03:02 +00003057static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3058 const BinaryOperator *BO,
3059 LValue &LV,
3060 bool IncludeMember = true) {
3061 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3062
3063 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3064 if (Info.keepEvaluatingAfterFailure()) {
3065 MemberPtr MemPtr;
3066 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3067 }
Craig Topper36250ad2014-05-12 05:36:57 +00003068 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003069 }
3070
3071 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3072 BO->getRHS(), IncludeMember);
3073}
3074
Richard Smith027bf112011-11-17 22:56:20 +00003075/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3076/// the provided lvalue, which currently refers to the base object.
3077static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3078 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003079 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003080 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003081 return false;
3082
Richard Smitha8105bc2012-01-06 16:39:00 +00003083 QualType TargetQT = E->getType();
3084 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3085 TargetQT = PT->getPointeeType();
3086
3087 // Check this cast lands within the final derived-to-base subobject path.
3088 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003089 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003090 << D.MostDerivedType << TargetQT;
3091 return false;
3092 }
3093
Richard Smith027bf112011-11-17 22:56:20 +00003094 // Check the type of the final cast. We don't need to check the path,
3095 // since a cast can only be formed if the path is unique.
3096 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003097 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3098 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003099 if (NewEntriesSize == D.MostDerivedPathLength)
3100 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3101 else
Richard Smith027bf112011-11-17 22:56:20 +00003102 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003103 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003104 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003105 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003106 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003107 }
Richard Smith027bf112011-11-17 22:56:20 +00003108
3109 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003110 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003111}
3112
Mike Stump876387b2009-10-27 22:09:17 +00003113namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003114enum EvalStmtResult {
3115 /// Evaluation failed.
3116 ESR_Failed,
3117 /// Hit a 'return' statement.
3118 ESR_Returned,
3119 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003120 ESR_Succeeded,
3121 /// Hit a 'continue' statement.
3122 ESR_Continue,
3123 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003124 ESR_Break,
3125 /// Still scanning for 'case' or 'default' statement.
3126 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003127};
3128}
3129
Richard Smithd9f663b2013-04-22 15:31:51 +00003130static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3132 // We don't need to evaluate the initializer for a static local.
3133 if (!VD->hasLocalStorage())
3134 return true;
3135
3136 LValue Result;
3137 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003138 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003139
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003140 const Expr *InitE = VD->getInit();
3141 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003142 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3143 << false << VD->getType();
3144 Val = APValue();
3145 return false;
3146 }
3147
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003148 if (InitE->isValueDependent())
3149 return false;
3150
3151 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003152 // Wipe out any partially-computed value, to allow tracking that this
3153 // evaluation failed.
3154 Val = APValue();
3155 return false;
3156 }
3157 }
3158
3159 return true;
3160}
3161
Richard Smith4e18ca52013-05-06 05:56:11 +00003162/// Evaluate a condition (either a variable declaration or an expression).
3163static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3164 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003165 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003166 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3167 return false;
3168 return EvaluateAsBooleanCondition(Cond, Result, Info);
3169}
3170
3171static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003172 const Stmt *S,
3173 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003174
3175/// Evaluate the body of a loop, and translate the result as appropriate.
3176static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003177 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003178 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003179 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003180 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003181 case ESR_Break:
3182 return ESR_Succeeded;
3183 case ESR_Succeeded:
3184 case ESR_Continue:
3185 return ESR_Continue;
3186 case ESR_Failed:
3187 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003188 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003189 return ESR;
3190 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003191 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003192}
3193
Richard Smith496ddcf2013-05-12 17:32:42 +00003194/// Evaluate a switch statement.
3195static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3196 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003197 BlockScopeRAII Scope(Info);
3198
Richard Smith496ddcf2013-05-12 17:32:42 +00003199 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003200 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003201 {
3202 FullExpressionRAII Scope(Info);
3203 if (SS->getConditionVariable() &&
3204 !EvaluateDecl(Info, SS->getConditionVariable()))
3205 return ESR_Failed;
3206 if (!EvaluateInteger(SS->getCond(), Value, Info))
3207 return ESR_Failed;
3208 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003209
3210 // Find the switch case corresponding to the value of the condition.
3211 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003212 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003213 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3214 SC = SC->getNextSwitchCase()) {
3215 if (isa<DefaultStmt>(SC)) {
3216 Found = SC;
3217 continue;
3218 }
3219
3220 const CaseStmt *CS = cast<CaseStmt>(SC);
3221 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3222 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3223 : LHS;
3224 if (LHS <= Value && Value <= RHS) {
3225 Found = SC;
3226 break;
3227 }
3228 }
3229
3230 if (!Found)
3231 return ESR_Succeeded;
3232
3233 // Search the switch body for the switch case and evaluate it from there.
3234 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3235 case ESR_Break:
3236 return ESR_Succeeded;
3237 case ESR_Succeeded:
3238 case ESR_Continue:
3239 case ESR_Failed:
3240 case ESR_Returned:
3241 return ESR;
3242 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003243 // This can only happen if the switch case is nested within a statement
3244 // expression. We have no intention of supporting that.
3245 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3246 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003247 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003248 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003249}
3250
Richard Smith254a73d2011-10-28 22:34:42 +00003251// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003252static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003253 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003254 if (!Info.nextStep(S))
3255 return ESR_Failed;
3256
Richard Smith496ddcf2013-05-12 17:32:42 +00003257 // If we're hunting down a 'case' or 'default' label, recurse through
3258 // substatements until we hit the label.
3259 if (Case) {
3260 // FIXME: We don't start the lifetime of objects whose initialization we
3261 // jump over. However, such objects must be of class type with a trivial
3262 // default constructor that initialize all subobjects, so must be empty,
3263 // so this almost never matters.
3264 switch (S->getStmtClass()) {
3265 case Stmt::CompoundStmtClass:
3266 // FIXME: Precompute which substatement of a compound statement we
3267 // would jump to, and go straight there rather than performing a
3268 // linear scan each time.
3269 case Stmt::LabelStmtClass:
3270 case Stmt::AttributedStmtClass:
3271 case Stmt::DoStmtClass:
3272 break;
3273
3274 case Stmt::CaseStmtClass:
3275 case Stmt::DefaultStmtClass:
3276 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003277 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003278 break;
3279
3280 case Stmt::IfStmtClass: {
3281 // FIXME: Precompute which side of an 'if' we would jump to, and go
3282 // straight there rather than scanning both sides.
3283 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003284
3285 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3286 // preceded by our switch label.
3287 BlockScopeRAII Scope(Info);
3288
Richard Smith496ddcf2013-05-12 17:32:42 +00003289 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3290 if (ESR != ESR_CaseNotFound || !IS->getElse())
3291 return ESR;
3292 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3293 }
3294
3295 case Stmt::WhileStmtClass: {
3296 EvalStmtResult ESR =
3297 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3298 if (ESR != ESR_Continue)
3299 return ESR;
3300 break;
3301 }
3302
3303 case Stmt::ForStmtClass: {
3304 const ForStmt *FS = cast<ForStmt>(S);
3305 EvalStmtResult ESR =
3306 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3307 if (ESR != ESR_Continue)
3308 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003309 if (FS->getInc()) {
3310 FullExpressionRAII IncScope(Info);
3311 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3312 return ESR_Failed;
3313 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003314 break;
3315 }
3316
3317 case Stmt::DeclStmtClass:
3318 // FIXME: If the variable has initialization that can't be jumped over,
3319 // bail out of any immediately-surrounding compound-statement too.
3320 default:
3321 return ESR_CaseNotFound;
3322 }
3323 }
3324
Richard Smith254a73d2011-10-28 22:34:42 +00003325 switch (S->getStmtClass()) {
3326 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003327 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003328 // Don't bother evaluating beyond an expression-statement which couldn't
3329 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003330 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003331 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003332 return ESR_Failed;
3333 return ESR_Succeeded;
3334 }
3335
3336 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003337 return ESR_Failed;
3338
3339 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003340 return ESR_Succeeded;
3341
Richard Smithd9f663b2013-04-22 15:31:51 +00003342 case Stmt::DeclStmtClass: {
3343 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003344 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003345 // Each declaration initialization is its own full-expression.
3346 // FIXME: This isn't quite right; if we're performing aggregate
3347 // initialization, each braced subexpression is its own full-expression.
3348 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003349 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003350 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003351 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003352 return ESR_Succeeded;
3353 }
3354
Richard Smith357362d2011-12-13 06:39:58 +00003355 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003356 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003357 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003358 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003359 return ESR_Failed;
3360 return ESR_Returned;
3361 }
Richard Smith254a73d2011-10-28 22:34:42 +00003362
3363 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003364 BlockScopeRAII Scope(Info);
3365
Richard Smith254a73d2011-10-28 22:34:42 +00003366 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003367 for (const auto *BI : CS->body()) {
3368 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003369 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003370 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003371 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003372 return ESR;
3373 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003374 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003375 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003376
3377 case Stmt::IfStmtClass: {
3378 const IfStmt *IS = cast<IfStmt>(S);
3379
3380 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003381 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003382 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003383 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003384 return ESR_Failed;
3385
3386 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3387 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3388 if (ESR != ESR_Succeeded)
3389 return ESR;
3390 }
3391 return ESR_Succeeded;
3392 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003393
3394 case Stmt::WhileStmtClass: {
3395 const WhileStmt *WS = cast<WhileStmt>(S);
3396 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003397 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003398 bool Continue;
3399 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3400 Continue))
3401 return ESR_Failed;
3402 if (!Continue)
3403 break;
3404
3405 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3406 if (ESR != ESR_Continue)
3407 return ESR;
3408 }
3409 return ESR_Succeeded;
3410 }
3411
3412 case Stmt::DoStmtClass: {
3413 const DoStmt *DS = cast<DoStmt>(S);
3414 bool Continue;
3415 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003416 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003417 if (ESR != ESR_Continue)
3418 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003419 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003420
Richard Smith08d6a2c2013-07-24 07:11:57 +00003421 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003422 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3423 return ESR_Failed;
3424 } while (Continue);
3425 return ESR_Succeeded;
3426 }
3427
3428 case Stmt::ForStmtClass: {
3429 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003430 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003431 if (FS->getInit()) {
3432 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3433 if (ESR != ESR_Succeeded)
3434 return ESR;
3435 }
3436 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003437 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003438 bool Continue = true;
3439 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3440 FS->getCond(), Continue))
3441 return ESR_Failed;
3442 if (!Continue)
3443 break;
3444
3445 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3446 if (ESR != ESR_Continue)
3447 return ESR;
3448
Richard Smith08d6a2c2013-07-24 07:11:57 +00003449 if (FS->getInc()) {
3450 FullExpressionRAII IncScope(Info);
3451 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3452 return ESR_Failed;
3453 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003454 }
3455 return ESR_Succeeded;
3456 }
3457
Richard Smith896e0d72013-05-06 06:51:17 +00003458 case Stmt::CXXForRangeStmtClass: {
3459 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003460 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003461
3462 // Initialize the __range variable.
3463 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3464 if (ESR != ESR_Succeeded)
3465 return ESR;
3466
3467 // Create the __begin and __end iterators.
3468 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3469 if (ESR != ESR_Succeeded)
3470 return ESR;
3471
3472 while (true) {
3473 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003474 {
3475 bool Continue = true;
3476 FullExpressionRAII CondExpr(Info);
3477 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3478 return ESR_Failed;
3479 if (!Continue)
3480 break;
3481 }
Richard Smith896e0d72013-05-06 06:51:17 +00003482
3483 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003484 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003485 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3486 if (ESR != ESR_Succeeded)
3487 return ESR;
3488
3489 // Loop body.
3490 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3491 if (ESR != ESR_Continue)
3492 return ESR;
3493
3494 // Increment: ++__begin
3495 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3496 return ESR_Failed;
3497 }
3498
3499 return ESR_Succeeded;
3500 }
3501
Richard Smith496ddcf2013-05-12 17:32:42 +00003502 case Stmt::SwitchStmtClass:
3503 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3504
Richard Smith4e18ca52013-05-06 05:56:11 +00003505 case Stmt::ContinueStmtClass:
3506 return ESR_Continue;
3507
3508 case Stmt::BreakStmtClass:
3509 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003510
3511 case Stmt::LabelStmtClass:
3512 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3513
3514 case Stmt::AttributedStmtClass:
3515 // As a general principle, C++11 attributes can be ignored without
3516 // any semantic impact.
3517 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3518 Case);
3519
3520 case Stmt::CaseStmtClass:
3521 case Stmt::DefaultStmtClass:
3522 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003523 }
3524}
3525
Richard Smithcc36f692011-12-22 02:22:31 +00003526/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3527/// default constructor. If so, we'll fold it whether or not it's marked as
3528/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3529/// so we need special handling.
3530static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003531 const CXXConstructorDecl *CD,
3532 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003533 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3534 return false;
3535
Richard Smith66e05fe2012-01-18 05:21:49 +00003536 // Value-initialization does not call a trivial default constructor, so such a
3537 // call is a core constant expression whether or not the constructor is
3538 // constexpr.
3539 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003540 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003541 // FIXME: If DiagDecl is an implicitly-declared special member function,
3542 // we should be much more explicit about why it's not constexpr.
3543 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3544 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3545 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003546 } else {
3547 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3548 }
3549 }
3550 return true;
3551}
3552
Richard Smith357362d2011-12-13 06:39:58 +00003553/// CheckConstexprFunction - Check that a function can be called in a constant
3554/// expression.
3555static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3556 const FunctionDecl *Declaration,
3557 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003558 // Potential constant expressions can contain calls to declared, but not yet
3559 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003560 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003561 Declaration->isConstexpr())
3562 return false;
3563
Richard Smith0838f3a2013-05-14 05:18:44 +00003564 // Bail out with no diagnostic if the function declaration itself is invalid.
3565 // We will have produced a relevant diagnostic while parsing it.
3566 if (Declaration->isInvalidDecl())
3567 return false;
3568
Richard Smith357362d2011-12-13 06:39:58 +00003569 // Can we evaluate this function call?
3570 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3571 return true;
3572
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003573 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003574 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003575 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3576 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003577 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3578 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3579 << DiagDecl;
3580 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3581 } else {
3582 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3583 }
3584 return false;
3585}
3586
Richard Smithd62306a2011-11-10 06:34:14 +00003587namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003588typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003589}
3590
3591/// EvaluateArgs - Evaluate the arguments to a function call.
3592static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3593 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003594 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003595 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003596 I != E; ++I) {
3597 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3598 // If we're checking for a potential constant expression, evaluate all
3599 // initializers even if some of them fail.
3600 if (!Info.keepEvaluatingAfterFailure())
3601 return false;
3602 Success = false;
3603 }
3604 }
3605 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003606}
3607
Richard Smith254a73d2011-10-28 22:34:42 +00003608/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003609static bool HandleFunctionCall(SourceLocation CallLoc,
3610 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003611 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003612 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003613 ArgVector ArgValues(Args.size());
3614 if (!EvaluateArgs(Args, ArgValues, Info))
3615 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003616
Richard Smith253c2a32012-01-27 01:14:48 +00003617 if (!Info.CheckCallLimit(CallLoc))
3618 return false;
3619
3620 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003621
3622 // For a trivial copy or move assignment, perform an APValue copy. This is
3623 // essential for unions, where the operations performed by the assignment
3624 // operator cannot be represented as statements.
3625 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3626 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3627 assert(This &&
3628 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3629 LValue RHS;
3630 RHS.setFrom(Info.Ctx, ArgValues[0]);
3631 APValue RHSValue;
3632 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3633 RHS, RHSValue))
3634 return false;
3635 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3636 RHSValue))
3637 return false;
3638 This->moveInto(Result);
3639 return true;
3640 }
3641
Richard Smithd9f663b2013-04-22 15:31:51 +00003642 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003643 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003644 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003645 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003646 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003647 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003648 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003649}
3650
Richard Smithd62306a2011-11-10 06:34:14 +00003651/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003652static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003653 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003654 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003655 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003656 ArgVector ArgValues(Args.size());
3657 if (!EvaluateArgs(Args, ArgValues, Info))
3658 return false;
3659
Richard Smith253c2a32012-01-27 01:14:48 +00003660 if (!Info.CheckCallLimit(CallLoc))
3661 return false;
3662
Richard Smith3607ffe2012-02-13 03:54:03 +00003663 const CXXRecordDecl *RD = Definition->getParent();
3664 if (RD->getNumVBases()) {
3665 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3666 return false;
3667 }
3668
Richard Smith253c2a32012-01-27 01:14:48 +00003669 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003670
3671 // If it's a delegating constructor, just delegate.
3672 if (Definition->isDelegatingConstructor()) {
3673 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003674 {
3675 FullExpressionRAII InitScope(Info);
3676 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3677 return false;
3678 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003679 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003680 }
3681
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003682 // For a trivial copy or move constructor, perform an APValue copy. This is
3683 // essential for unions, where the operations performed by the constructor
3684 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003685 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003686 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3687 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003688 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003689 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003690 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003691 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003692 }
3693
3694 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003695 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003696 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003697 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003698
John McCalld7bca762012-05-01 00:38:49 +00003699 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003700 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3701
Richard Smith08d6a2c2013-07-24 07:11:57 +00003702 // A scope for temporaries lifetime-extended by reference members.
3703 BlockScopeRAII LifetimeExtendedScope(Info);
3704
Richard Smith253c2a32012-01-27 01:14:48 +00003705 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003706 unsigned BasesSeen = 0;
3707#ifndef NDEBUG
3708 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3709#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003710 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003711 LValue Subobject = This;
3712 APValue *Value = &Result;
3713
3714 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003715 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003716 if (I->isBaseInitializer()) {
3717 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003718#ifndef NDEBUG
3719 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003720 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003721 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3722 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3723 "base class initializers not in expected order");
3724 ++BaseIt;
3725#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003726 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003727 BaseType->getAsCXXRecordDecl(), &Layout))
3728 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003729 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003730 } else if ((FD = I->getMember())) {
3731 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003732 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003733 if (RD->isUnion()) {
3734 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003735 Value = &Result.getUnionValue();
3736 } else {
3737 Value = &Result.getStructField(FD->getFieldIndex());
3738 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003739 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003740 // Walk the indirect field decl's chain to find the object to initialize,
3741 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003742 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003743 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003744 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3745 // Switch the union field if it differs. This happens if we had
3746 // preceding zero-initialization, and we're now initializing a union
3747 // subobject other than the first.
3748 // FIXME: In this case, the values of the other subobjects are
3749 // specified, since zero-initialization sets all padding bits to zero.
3750 if (Value->isUninit() ||
3751 (Value->isUnion() && Value->getUnionField() != FD)) {
3752 if (CD->isUnion())
3753 *Value = APValue(FD);
3754 else
3755 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003756 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003757 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003758 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003759 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003760 if (CD->isUnion())
3761 Value = &Value->getUnionValue();
3762 else
3763 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003764 }
Richard Smithd62306a2011-11-10 06:34:14 +00003765 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003766 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003767 }
Richard Smith253c2a32012-01-27 01:14:48 +00003768
Richard Smith08d6a2c2013-07-24 07:11:57 +00003769 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003770 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3771 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003772 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003773 // If we're checking for a potential constant expression, evaluate all
3774 // initializers even if some of them fail.
3775 if (!Info.keepEvaluatingAfterFailure())
3776 return false;
3777 Success = false;
3778 }
Richard Smithd62306a2011-11-10 06:34:14 +00003779 }
3780
Richard Smithd9f663b2013-04-22 15:31:51 +00003781 return Success &&
3782 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003783}
3784
Eli Friedman9a156e52008-11-12 09:44:48 +00003785//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003786// Generic Evaluation
3787//===----------------------------------------------------------------------===//
3788namespace {
3789
Aaron Ballman68af21c2014-01-03 19:26:43 +00003790template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003791class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003792 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003793private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003794 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003795 return static_cast<Derived*>(this)->Success(V, E);
3796 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003797 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003798 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003799 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003800
Richard Smith17100ba2012-02-16 02:46:34 +00003801 // Check whether a conditional operator with a non-constant condition is a
3802 // potential constant expression. If neither arm is a potential constant
3803 // expression, then the conditional operator is not either.
3804 template<typename ConditionalOperator>
3805 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003806 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003807
3808 // Speculatively evaluate both arms.
3809 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003810 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003811 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3812
3813 StmtVisitorTy::Visit(E->getFalseExpr());
3814 if (Diag.empty())
3815 return;
3816
3817 Diag.clear();
3818 StmtVisitorTy::Visit(E->getTrueExpr());
3819 if (Diag.empty())
3820 return;
3821 }
3822
3823 Error(E, diag::note_constexpr_conditional_never_const);
3824 }
3825
3826
3827 template<typename ConditionalOperator>
3828 bool HandleConditionalOperator(const ConditionalOperator *E) {
3829 bool BoolResult;
3830 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003831 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003832 CheckPotentialConstantConditional(E);
3833 return false;
3834 }
3835
3836 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3837 return StmtVisitorTy::Visit(EvalExpr);
3838 }
3839
Peter Collingbournee9200682011-05-13 03:29:01 +00003840protected:
3841 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003842 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003843 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3844
Richard Smith92b1ce02011-12-12 09:28:41 +00003845 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003846 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003847 }
3848
Aaron Ballman68af21c2014-01-03 19:26:43 +00003849 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003850
3851public:
3852 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3853
3854 EvalInfo &getEvalInfo() { return Info; }
3855
Richard Smithf57d8cb2011-12-09 22:58:01 +00003856 /// Report an evaluation error. This should only be called when an error is
3857 /// first discovered. When propagating an error, just return false.
3858 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003859 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003860 return false;
3861 }
3862 bool Error(const Expr *E) {
3863 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3864 }
3865
Aaron Ballman68af21c2014-01-03 19:26:43 +00003866 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003867 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003868 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003869 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003870 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003871 }
3872
Aaron Ballman68af21c2014-01-03 19:26:43 +00003873 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003874 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003875 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003876 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003877 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003878 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003879 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003880 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003881 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003882 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003883 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003884 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003885 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003886 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003887 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003888 // The initializer may not have been parsed yet, or might be erroneous.
3889 if (!E->getExpr())
3890 return Error(E);
3891 return StmtVisitorTy::Visit(E->getExpr());
3892 }
Richard Smith5894a912011-12-19 22:12:41 +00003893 // We cannot create any objects for which cleanups are required, so there is
3894 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003895 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003896 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003897
Aaron Ballman68af21c2014-01-03 19:26:43 +00003898 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003899 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3900 return static_cast<Derived*>(this)->VisitCastExpr(E);
3901 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003902 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003903 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3904 return static_cast<Derived*>(this)->VisitCastExpr(E);
3905 }
3906
Aaron Ballman68af21c2014-01-03 19:26:43 +00003907 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003908 switch (E->getOpcode()) {
3909 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003910 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003911
3912 case BO_Comma:
3913 VisitIgnoredValue(E->getLHS());
3914 return StmtVisitorTy::Visit(E->getRHS());
3915
3916 case BO_PtrMemD:
3917 case BO_PtrMemI: {
3918 LValue Obj;
3919 if (!HandleMemberPointerAccess(Info, E, Obj))
3920 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003921 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003922 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003923 return false;
3924 return DerivedSuccess(Result, E);
3925 }
3926 }
3927 }
3928
Aaron Ballman68af21c2014-01-03 19:26:43 +00003929 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003930 // Evaluate and cache the common expression. We treat it as a temporary,
3931 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003932 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003933 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003934 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003935
Richard Smith17100ba2012-02-16 02:46:34 +00003936 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003937 }
3938
Aaron Ballman68af21c2014-01-03 19:26:43 +00003939 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003940 bool IsBcpCall = false;
3941 // If the condition (ignoring parens) is a __builtin_constant_p call,
3942 // the result is a constant expression if it can be folded without
3943 // side-effects. This is an important GNU extension. See GCC PR38377
3944 // for discussion.
3945 if (const CallExpr *CallCE =
3946 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00003947 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003948 IsBcpCall = true;
3949
3950 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3951 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003952 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003953 return false;
3954
Richard Smith6d4c6582013-11-05 22:18:15 +00003955 FoldConstant Fold(Info, IsBcpCall);
3956 if (!HandleConditionalOperator(E)) {
3957 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003958 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003959 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003960
3961 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003962 }
3963
Aaron Ballman68af21c2014-01-03 19:26:43 +00003964 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003965 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3966 return DerivedSuccess(*Value, E);
3967
3968 const Expr *Source = E->getSourceExpr();
3969 if (!Source)
3970 return Error(E);
3971 if (Source == E) { // sanity checking.
3972 assert(0 && "OpaqueValueExpr recursively refers to itself");
3973 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003974 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003975 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003976 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003977
Aaron Ballman68af21c2014-01-03 19:26:43 +00003978 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003979 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003980 QualType CalleeType = Callee->getType();
3981
Craig Topper36250ad2014-05-12 05:36:57 +00003982 const FunctionDecl *FD = nullptr;
3983 LValue *This = nullptr, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003984 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003985 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003986
Richard Smithe97cbd72011-11-11 04:05:33 +00003987 // Extract function decl and 'this' pointer from the callee.
3988 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00003989 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003990 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3991 // Explicit bound member calls, such as x.f() or p->g();
3992 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003993 return false;
3994 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003995 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003996 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003997 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3998 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003999 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4000 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004001 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004002 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004003 return Error(Callee);
4004
4005 FD = dyn_cast<FunctionDecl>(Member);
4006 if (!FD)
4007 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004008 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004009 LValue Call;
4010 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004011 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004012
Richard Smitha8105bc2012-01-06 16:39:00 +00004013 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004014 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004015 FD = dyn_cast_or_null<FunctionDecl>(
4016 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004017 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004018 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004019
4020 // Overloaded operator calls to member functions are represented as normal
4021 // calls with '*this' as the first argument.
4022 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4023 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004024 // FIXME: When selecting an implicit conversion for an overloaded
4025 // operator delete, we sometimes try to evaluate calls to conversion
4026 // operators without a 'this' parameter!
4027 if (Args.empty())
4028 return Error(E);
4029
Richard Smithe97cbd72011-11-11 04:05:33 +00004030 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4031 return false;
4032 This = &ThisVal;
4033 Args = Args.slice(1);
4034 }
4035
4036 // Don't call function pointers which have been cast to some other type.
4037 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004038 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004039 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004040 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004041
Richard Smith47b34932012-02-01 02:39:43 +00004042 if (This && !This->checkSubobject(Info, E, CSK_This))
4043 return false;
4044
Richard Smith3607ffe2012-02-13 03:54:03 +00004045 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4046 // calls to such functions in constant expressions.
4047 if (This && !HasQualifier &&
4048 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4049 return Error(E, diag::note_constexpr_virtual_call);
4050
Craig Topper36250ad2014-05-12 05:36:57 +00004051 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004052 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004053 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004054
Richard Smith357362d2011-12-13 06:39:58 +00004055 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004056 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4057 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004058 return false;
4059
Richard Smithb228a862012-02-15 02:18:13 +00004060 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004061 }
4062
Aaron Ballman68af21c2014-01-03 19:26:43 +00004063 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004064 return StmtVisitorTy::Visit(E->getInitializer());
4065 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004066 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004067 if (E->getNumInits() == 0)
4068 return DerivedZeroInitialization(E);
4069 if (E->getNumInits() == 1)
4070 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004071 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004072 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004073 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004074 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004075 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004076 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004077 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004078 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004079 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004080 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004081 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004082
Richard Smithd62306a2011-11-10 06:34:14 +00004083 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004084 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004085 assert(!E->isArrow() && "missing call to bound member function?");
4086
Richard Smith2e312c82012-03-03 22:46:17 +00004087 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004088 if (!Evaluate(Val, Info, E->getBase()))
4089 return false;
4090
4091 QualType BaseTy = E->getBase()->getType();
4092
4093 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004094 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004095 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004096 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004097 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4098
Richard Smith3229b742013-05-05 21:17:10 +00004099 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004100 SubobjectDesignator Designator(BaseTy);
4101 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004102
Richard Smith3229b742013-05-05 21:17:10 +00004103 APValue Result;
4104 return extractSubobject(Info, E, Obj, Designator, Result) &&
4105 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004106 }
4107
Aaron Ballman68af21c2014-01-03 19:26:43 +00004108 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004109 switch (E->getCastKind()) {
4110 default:
4111 break;
4112
Richard Smitha23ab512013-05-23 00:30:41 +00004113 case CK_AtomicToNonAtomic: {
4114 APValue AtomicVal;
4115 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4116 return false;
4117 return DerivedSuccess(AtomicVal, E);
4118 }
4119
Richard Smith11562c52011-10-28 17:51:58 +00004120 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004121 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004122 return StmtVisitorTy::Visit(E->getSubExpr());
4123
4124 case CK_LValueToRValue: {
4125 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004126 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4127 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004128 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004129 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004130 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004131 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004132 return false;
4133 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004134 }
4135 }
4136
Richard Smithf57d8cb2011-12-09 22:58:01 +00004137 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004138 }
4139
Aaron Ballman68af21c2014-01-03 19:26:43 +00004140 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004141 return VisitUnaryPostIncDec(UO);
4142 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004143 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004144 return VisitUnaryPostIncDec(UO);
4145 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004146 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004147 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4148 return Error(UO);
4149
4150 LValue LVal;
4151 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4152 return false;
4153 APValue RVal;
4154 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4155 UO->isIncrementOp(), &RVal))
4156 return false;
4157 return DerivedSuccess(RVal, UO);
4158 }
4159
Aaron Ballman68af21c2014-01-03 19:26:43 +00004160 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004161 // We will have checked the full-expressions inside the statement expression
4162 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004163 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004164 return Error(E);
4165
Richard Smith08d6a2c2013-07-24 07:11:57 +00004166 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004167 const CompoundStmt *CS = E->getSubStmt();
4168 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4169 BE = CS->body_end();
4170 /**/; ++BI) {
4171 if (BI + 1 == BE) {
4172 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4173 if (!FinalExpr) {
4174 Info.Diag((*BI)->getLocStart(),
4175 diag::note_constexpr_stmt_expr_unsupported);
4176 return false;
4177 }
4178 return this->Visit(FinalExpr);
4179 }
4180
4181 APValue ReturnValue;
4182 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4183 if (ESR != ESR_Succeeded) {
4184 // FIXME: If the statement-expression terminated due to 'return',
4185 // 'break', or 'continue', it would be nice to propagate that to
4186 // the outer statement evaluation rather than bailing out.
4187 if (ESR != ESR_Failed)
4188 Info.Diag((*BI)->getLocStart(),
4189 diag::note_constexpr_stmt_expr_unsupported);
4190 return false;
4191 }
4192 }
4193 }
4194
Richard Smith4a678122011-10-24 18:44:57 +00004195 /// Visit a value which is evaluated, but whose value is ignored.
4196 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004197 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004198 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004199};
4200
4201}
4202
4203//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004204// Common base class for lvalue and temporary evaluation.
4205//===----------------------------------------------------------------------===//
4206namespace {
4207template<class Derived>
4208class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004209 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004210protected:
4211 LValue &Result;
4212 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004213 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004214
4215 bool Success(APValue::LValueBase B) {
4216 Result.set(B);
4217 return true;
4218 }
4219
4220public:
4221 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4222 ExprEvaluatorBaseTy(Info), Result(Result) {}
4223
Richard Smith2e312c82012-03-03 22:46:17 +00004224 bool Success(const APValue &V, const Expr *E) {
4225 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004226 return true;
4227 }
Richard Smith027bf112011-11-17 22:56:20 +00004228
Richard Smith027bf112011-11-17 22:56:20 +00004229 bool VisitMemberExpr(const MemberExpr *E) {
4230 // Handle non-static data members.
4231 QualType BaseTy;
4232 if (E->isArrow()) {
4233 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4234 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004235 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004236 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004237 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004238 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4239 return false;
4240 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004241 } else {
4242 if (!this->Visit(E->getBase()))
4243 return false;
4244 BaseTy = E->getBase()->getType();
4245 }
Richard Smith027bf112011-11-17 22:56:20 +00004246
Richard Smith1b78b3d2012-01-25 22:15:11 +00004247 const ValueDecl *MD = E->getMemberDecl();
4248 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4249 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4250 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4251 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004252 if (!HandleLValueMember(this->Info, E, Result, FD))
4253 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004254 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004255 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4256 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004257 } else
4258 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004259
Richard Smith1b78b3d2012-01-25 22:15:11 +00004260 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004261 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004262 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004263 RefValue))
4264 return false;
4265 return Success(RefValue, E);
4266 }
4267 return true;
4268 }
4269
4270 bool VisitBinaryOperator(const BinaryOperator *E) {
4271 switch (E->getOpcode()) {
4272 default:
4273 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4274
4275 case BO_PtrMemD:
4276 case BO_PtrMemI:
4277 return HandleMemberPointerAccess(this->Info, E, Result);
4278 }
4279 }
4280
4281 bool VisitCastExpr(const CastExpr *E) {
4282 switch (E->getCastKind()) {
4283 default:
4284 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4285
4286 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004287 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004288 if (!this->Visit(E->getSubExpr()))
4289 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004290
4291 // Now figure out the necessary offset to add to the base LV to get from
4292 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004293 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4294 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004295 }
4296 }
4297};
4298}
4299
4300//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004301// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004302//
4303// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4304// function designators (in C), decl references to void objects (in C), and
4305// temporaries (if building with -Wno-address-of-temporary).
4306//
4307// LValue evaluation produces values comprising a base expression of one of the
4308// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004309// - Declarations
4310// * VarDecl
4311// * FunctionDecl
4312// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004313// * CompoundLiteralExpr in C
4314// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004315// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004316// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004317// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004318// * ObjCEncodeExpr
4319// * AddrLabelExpr
4320// * BlockExpr
4321// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004322// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004323// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004324// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004325// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4326// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004327// * A MaterializeTemporaryExpr that has static storage duration, with no
4328// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004329// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004330//===----------------------------------------------------------------------===//
4331namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004332class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004333 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004334public:
Richard Smith027bf112011-11-17 22:56:20 +00004335 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4336 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004337
Richard Smith11562c52011-10-28 17:51:58 +00004338 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004339 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004340
Peter Collingbournee9200682011-05-13 03:29:01 +00004341 bool VisitDeclRefExpr(const DeclRefExpr *E);
4342 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004343 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004344 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4345 bool VisitMemberExpr(const MemberExpr *E);
4346 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4347 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004348 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004349 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004350 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4351 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004352 bool VisitUnaryReal(const UnaryOperator *E);
4353 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004354 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4355 return VisitUnaryPreIncDec(UO);
4356 }
4357 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4358 return VisitUnaryPreIncDec(UO);
4359 }
Richard Smith3229b742013-05-05 21:17:10 +00004360 bool VisitBinAssign(const BinaryOperator *BO);
4361 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004362
Peter Collingbournee9200682011-05-13 03:29:01 +00004363 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004364 switch (E->getCastKind()) {
4365 default:
Richard Smith027bf112011-11-17 22:56:20 +00004366 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004367
Eli Friedmance3e02a2011-10-11 00:13:24 +00004368 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004369 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004370 if (!Visit(E->getSubExpr()))
4371 return false;
4372 Result.Designator.setInvalid();
4373 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004374
Richard Smith027bf112011-11-17 22:56:20 +00004375 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004376 if (!Visit(E->getSubExpr()))
4377 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004378 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004379 }
4380 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004381};
4382} // end anonymous namespace
4383
Richard Smith11562c52011-10-28 17:51:58 +00004384/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004385/// expressions which are not glvalues, in two cases:
4386/// * function designators in C, and
4387/// * "extern void" objects
4388static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4389 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4390 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004391 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004392}
4393
Peter Collingbournee9200682011-05-13 03:29:01 +00004394bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004395 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004396 return Success(FD);
4397 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004398 return VisitVarDecl(E, VD);
4399 return Error(E);
4400}
Richard Smith733237d2011-10-24 23:14:33 +00004401
Richard Smith11562c52011-10-28 17:51:58 +00004402bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004403 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004404 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4405 Frame = Info.CurrentCall;
4406
Richard Smithfec09922011-11-01 16:57:24 +00004407 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004408 if (Frame) {
4409 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004410 return true;
4411 }
Richard Smithce40ad62011-11-12 22:28:03 +00004412 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004413 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004414
Richard Smith3229b742013-05-05 21:17:10 +00004415 APValue *V;
4416 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004417 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004418 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004419 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004420 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4421 return false;
4422 }
Richard Smith3229b742013-05-05 21:17:10 +00004423 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004424}
4425
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004426bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4427 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004428 // Walk through the expression to find the materialized temporary itself.
4429 SmallVector<const Expr *, 2> CommaLHSs;
4430 SmallVector<SubobjectAdjustment, 2> Adjustments;
4431 const Expr *Inner = E->GetTemporaryExpr()->
4432 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004433
Richard Smith84401042013-06-03 05:03:02 +00004434 // If we passed any comma operators, evaluate their LHSs.
4435 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4436 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4437 return false;
4438
Richard Smithe6c01442013-06-05 00:46:14 +00004439 // A materialized temporary with static storage duration can appear within the
4440 // result of a constant expression evaluation, so we need to preserve its
4441 // value for use outside this evaluation.
4442 APValue *Value;
4443 if (E->getStorageDuration() == SD_Static) {
4444 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004445 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004446 Result.set(E);
4447 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004448 Value = &Info.CurrentCall->
4449 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004450 Result.set(E, Info.CurrentCall->Index);
4451 }
4452
Richard Smithea4ad5d2013-06-06 08:19:16 +00004453 QualType Type = Inner->getType();
4454
Richard Smith84401042013-06-03 05:03:02 +00004455 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004456 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4457 (E->getStorageDuration() == SD_Static &&
4458 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4459 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004460 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004461 }
Richard Smith84401042013-06-03 05:03:02 +00004462
4463 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004464 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4465 --I;
4466 switch (Adjustments[I].Kind) {
4467 case SubobjectAdjustment::DerivedToBaseAdjustment:
4468 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4469 Type, Result))
4470 return false;
4471 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4472 break;
4473
4474 case SubobjectAdjustment::FieldAdjustment:
4475 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4476 return false;
4477 Type = Adjustments[I].Field->getType();
4478 break;
4479
4480 case SubobjectAdjustment::MemberPointerAdjustment:
4481 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4482 Adjustments[I].Ptr.RHS))
4483 return false;
4484 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4485 break;
4486 }
4487 }
4488
4489 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004490}
4491
Peter Collingbournee9200682011-05-13 03:29:01 +00004492bool
4493LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004494 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4495 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4496 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004497 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004498}
4499
Richard Smith6e525142011-12-27 12:18:28 +00004500bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004501 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004502 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004503
4504 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4505 << E->getExprOperand()->getType()
4506 << E->getExprOperand()->getSourceRange();
4507 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004508}
4509
Francois Pichet0066db92012-04-16 04:08:35 +00004510bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4511 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004512}
Francois Pichet0066db92012-04-16 04:08:35 +00004513
Peter Collingbournee9200682011-05-13 03:29:01 +00004514bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004515 // Handle static data members.
4516 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4517 VisitIgnoredValue(E->getBase());
4518 return VisitVarDecl(E, VD);
4519 }
4520
Richard Smith254a73d2011-10-28 22:34:42 +00004521 // Handle static member functions.
4522 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4523 if (MD->isStatic()) {
4524 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004525 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004526 }
4527 }
4528
Richard Smithd62306a2011-11-10 06:34:14 +00004529 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004530 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004531}
4532
Peter Collingbournee9200682011-05-13 03:29:01 +00004533bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004534 // FIXME: Deal with vectors as array subscript bases.
4535 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004536 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004537
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004538 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004539 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004540
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004541 APSInt Index;
4542 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004543 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004544
Richard Smith861b5b52013-05-07 23:34:45 +00004545 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4546 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004547}
Eli Friedman9a156e52008-11-12 09:44:48 +00004548
Peter Collingbournee9200682011-05-13 03:29:01 +00004549bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004550 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004551}
4552
Richard Smith66c96992012-02-18 22:04:06 +00004553bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4554 if (!Visit(E->getSubExpr()))
4555 return false;
4556 // __real is a no-op on scalar lvalues.
4557 if (E->getSubExpr()->getType()->isAnyComplexType())
4558 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4559 return true;
4560}
4561
4562bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4563 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4564 "lvalue __imag__ on scalar?");
4565 if (!Visit(E->getSubExpr()))
4566 return false;
4567 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4568 return true;
4569}
4570
Richard Smith243ef902013-05-05 23:31:59 +00004571bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4572 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004573 return Error(UO);
4574
4575 if (!this->Visit(UO->getSubExpr()))
4576 return false;
4577
Richard Smith243ef902013-05-05 23:31:59 +00004578 return handleIncDec(
4579 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004580 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004581}
4582
4583bool LValueExprEvaluator::VisitCompoundAssignOperator(
4584 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004585 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004586 return Error(CAO);
4587
Richard Smith3229b742013-05-05 21:17:10 +00004588 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004589
4590 // The overall lvalue result is the result of evaluating the LHS.
4591 if (!this->Visit(CAO->getLHS())) {
4592 if (Info.keepEvaluatingAfterFailure())
4593 Evaluate(RHS, this->Info, CAO->getRHS());
4594 return false;
4595 }
4596
Richard Smith3229b742013-05-05 21:17:10 +00004597 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4598 return false;
4599
Richard Smith43e77732013-05-07 04:50:00 +00004600 return handleCompoundAssignment(
4601 this->Info, CAO,
4602 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4603 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004604}
4605
4606bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004607 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4608 return Error(E);
4609
Richard Smith3229b742013-05-05 21:17:10 +00004610 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004611
4612 if (!this->Visit(E->getLHS())) {
4613 if (Info.keepEvaluatingAfterFailure())
4614 Evaluate(NewVal, this->Info, E->getRHS());
4615 return false;
4616 }
4617
Richard Smith3229b742013-05-05 21:17:10 +00004618 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4619 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004620
4621 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004622 NewVal);
4623}
4624
Eli Friedman9a156e52008-11-12 09:44:48 +00004625//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004626// Pointer Evaluation
4627//===----------------------------------------------------------------------===//
4628
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004629namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004630class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004631 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004632 LValue &Result;
4633
Peter Collingbournee9200682011-05-13 03:29:01 +00004634 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004635 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004636 return true;
4637 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004638public:
Mike Stump11289f42009-09-09 15:08:12 +00004639
John McCall45d55e42010-05-07 21:00:08 +00004640 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004641 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004642
Richard Smith2e312c82012-03-03 22:46:17 +00004643 bool Success(const APValue &V, const Expr *E) {
4644 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004645 return true;
4646 }
Richard Smithfddd3842011-12-30 21:15:51 +00004647 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004648 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004649 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004650
John McCall45d55e42010-05-07 21:00:08 +00004651 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004652 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004653 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004654 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004655 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004656 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004657 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004658 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004659 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004660 bool VisitCallExpr(const CallExpr *E);
4661 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004662 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004663 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004664 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004665 }
Richard Smithd62306a2011-11-10 06:34:14 +00004666 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004667 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004668 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004669 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004670 if (!Info.CurrentCall->This) {
4671 if (Info.getLangOpts().CPlusPlus11)
4672 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4673 else
4674 Info.Diag(E);
4675 return false;
4676 }
Richard Smithd62306a2011-11-10 06:34:14 +00004677 Result = *Info.CurrentCall->This;
4678 return true;
4679 }
John McCallc07a0c72011-02-17 10:25:35 +00004680
Eli Friedman449fe542009-03-23 04:56:01 +00004681 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004682};
Chris Lattner05706e882008-07-11 18:11:29 +00004683} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004684
John McCall45d55e42010-05-07 21:00:08 +00004685static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004686 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004687 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004688}
4689
John McCall45d55e42010-05-07 21:00:08 +00004690bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004691 if (E->getOpcode() != BO_Add &&
4692 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004693 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004694
Chris Lattner05706e882008-07-11 18:11:29 +00004695 const Expr *PExp = E->getLHS();
4696 const Expr *IExp = E->getRHS();
4697 if (IExp->getType()->isPointerType())
4698 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004699
Richard Smith253c2a32012-01-27 01:14:48 +00004700 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4701 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004702 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004703
John McCall45d55e42010-05-07 21:00:08 +00004704 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004705 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004706 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004707
4708 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004709 if (E->getOpcode() == BO_Sub)
4710 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004711
Ted Kremenek28831752012-08-23 20:46:57 +00004712 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004713 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4714 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004715}
Eli Friedman9a156e52008-11-12 09:44:48 +00004716
John McCall45d55e42010-05-07 21:00:08 +00004717bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4718 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004719}
Mike Stump11289f42009-09-09 15:08:12 +00004720
Peter Collingbournee9200682011-05-13 03:29:01 +00004721bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4722 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004723
Eli Friedman847a2bc2009-12-27 05:43:15 +00004724 switch (E->getCastKind()) {
4725 default:
4726 break;
4727
John McCalle3027922010-08-25 11:45:40 +00004728 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004729 case CK_CPointerToObjCPointerCast:
4730 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004731 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004732 if (!Visit(SubExpr))
4733 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004734 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4735 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4736 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004737 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004738 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004739 if (SubExpr->getType()->isVoidPointerType())
4740 CCEDiag(E, diag::note_constexpr_invalid_cast)
4741 << 3 << SubExpr->getType();
4742 else
4743 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4744 }
Richard Smith96e0c102011-11-04 02:25:55 +00004745 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004746
Anders Carlsson18275092010-10-31 20:41:46 +00004747 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004748 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004749 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004750 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004751 if (!Result.Base && Result.Offset.isZero())
4752 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004753
Richard Smithd62306a2011-11-10 06:34:14 +00004754 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004755 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004756 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4757 castAs<PointerType>()->getPointeeType(),
4758 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004759
Richard Smith027bf112011-11-17 22:56:20 +00004760 case CK_BaseToDerived:
4761 if (!Visit(E->getSubExpr()))
4762 return false;
4763 if (!Result.Base && Result.Offset.isZero())
4764 return true;
4765 return HandleBaseToDerivedCast(Info, E, Result);
4766
Richard Smith0b0a0b62011-10-29 20:57:55 +00004767 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004768 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004769 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004770
John McCalle3027922010-08-25 11:45:40 +00004771 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004772 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4773
Richard Smith2e312c82012-03-03 22:46:17 +00004774 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004775 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004776 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004777
John McCall45d55e42010-05-07 21:00:08 +00004778 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004779 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4780 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004781 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004782 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004783 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004784 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004785 return true;
4786 } else {
4787 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004788 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004789 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004790 }
4791 }
John McCalle3027922010-08-25 11:45:40 +00004792 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004793 if (SubExpr->isGLValue()) {
4794 if (!EvaluateLValue(SubExpr, Result, Info))
4795 return false;
4796 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004797 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004798 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004799 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004800 return false;
4801 }
Richard Smith96e0c102011-11-04 02:25:55 +00004802 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004803 if (const ConstantArrayType *CAT
4804 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4805 Result.addArray(Info, E, CAT);
4806 else
4807 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004808 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004809
John McCalle3027922010-08-25 11:45:40 +00004810 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004811 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004812 }
4813
Richard Smith11562c52011-10-28 17:51:58 +00004814 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004815}
Chris Lattner05706e882008-07-11 18:11:29 +00004816
Peter Collingbournee9200682011-05-13 03:29:01 +00004817bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004818 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004819 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004820
Alp Tokera724cff2013-12-28 21:59:02 +00004821 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004822 case Builtin::BI__builtin_addressof:
4823 return EvaluateLValue(E->getArg(0), Result, Info);
4824
4825 default:
4826 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4827 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004828}
Chris Lattner05706e882008-07-11 18:11:29 +00004829
4830//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004831// Member Pointer Evaluation
4832//===----------------------------------------------------------------------===//
4833
4834namespace {
4835class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004836 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004837 MemberPtr &Result;
4838
4839 bool Success(const ValueDecl *D) {
4840 Result = MemberPtr(D);
4841 return true;
4842 }
4843public:
4844
4845 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4846 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4847
Richard Smith2e312c82012-03-03 22:46:17 +00004848 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004849 Result.setFrom(V);
4850 return true;
4851 }
Richard Smithfddd3842011-12-30 21:15:51 +00004852 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004853 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00004854 }
4855
4856 bool VisitCastExpr(const CastExpr *E);
4857 bool VisitUnaryAddrOf(const UnaryOperator *E);
4858};
4859} // end anonymous namespace
4860
4861static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4862 EvalInfo &Info) {
4863 assert(E->isRValue() && E->getType()->isMemberPointerType());
4864 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4865}
4866
4867bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4868 switch (E->getCastKind()) {
4869 default:
4870 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4871
4872 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004873 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004874 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004875
4876 case CK_BaseToDerivedMemberPointer: {
4877 if (!Visit(E->getSubExpr()))
4878 return false;
4879 if (E->path_empty())
4880 return true;
4881 // Base-to-derived member pointer casts store the path in derived-to-base
4882 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4883 // the wrong end of the derived->base arc, so stagger the path by one class.
4884 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4885 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4886 PathI != PathE; ++PathI) {
4887 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4888 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4889 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004890 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004891 }
4892 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4893 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004894 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004895 return true;
4896 }
4897
4898 case CK_DerivedToBaseMemberPointer:
4899 if (!Visit(E->getSubExpr()))
4900 return false;
4901 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4902 PathE = E->path_end(); PathI != PathE; ++PathI) {
4903 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4904 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4905 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004906 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004907 }
4908 return true;
4909 }
4910}
4911
4912bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4913 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4914 // member can be formed.
4915 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4916}
4917
4918//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004919// Record Evaluation
4920//===----------------------------------------------------------------------===//
4921
4922namespace {
4923 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004924 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004925 const LValue &This;
4926 APValue &Result;
4927 public:
4928
4929 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4930 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4931
Richard Smith2e312c82012-03-03 22:46:17 +00004932 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004933 Result = V;
4934 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004935 }
Richard Smithfddd3842011-12-30 21:15:51 +00004936 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004937
Richard Smithe97cbd72011-11-11 04:05:33 +00004938 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004939 bool VisitInitListExpr(const InitListExpr *E);
4940 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004941 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004942 };
4943}
4944
Richard Smithfddd3842011-12-30 21:15:51 +00004945/// Perform zero-initialization on an object of non-union class type.
4946/// C++11 [dcl.init]p5:
4947/// To zero-initialize an object or reference of type T means:
4948/// [...]
4949/// -- if T is a (possibly cv-qualified) non-union class type,
4950/// each non-static data member and each base-class subobject is
4951/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004952static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4953 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004954 const LValue &This, APValue &Result) {
4955 assert(!RD->isUnion() && "Expected non-union class type");
4956 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4957 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00004958 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00004959
John McCalld7bca762012-05-01 00:38:49 +00004960 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004961 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4962
4963 if (CD) {
4964 unsigned Index = 0;
4965 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004966 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004967 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4968 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004969 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4970 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004971 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004972 Result.getStructBase(Index)))
4973 return false;
4974 }
4975 }
4976
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004977 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00004978 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004979 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004980 continue;
4981
4982 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004983 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004984 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004985
David Blaikie2d7c57e2012-04-30 02:36:29 +00004986 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004987 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004988 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004989 return false;
4990 }
4991
4992 return true;
4993}
4994
4995bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4996 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004997 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004998 if (RD->isUnion()) {
4999 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5000 // object's first non-static named data member is zero-initialized
5001 RecordDecl::field_iterator I = RD->field_begin();
5002 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005003 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005004 return true;
5005 }
5006
5007 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005008 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005009 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005010 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005011 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005012 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005013 }
5014
Richard Smith5d108602012-02-17 00:44:16 +00005015 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005016 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005017 return false;
5018 }
5019
Richard Smitha8105bc2012-01-06 16:39:00 +00005020 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005021}
5022
Richard Smithe97cbd72011-11-11 04:05:33 +00005023bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5024 switch (E->getCastKind()) {
5025 default:
5026 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5027
5028 case CK_ConstructorConversion:
5029 return Visit(E->getSubExpr());
5030
5031 case CK_DerivedToBase:
5032 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005033 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005034 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005036 if (!DerivedObject.isStruct())
5037 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005038
5039 // Derived-to-base rvalue conversion: just slice off the derived part.
5040 APValue *Value = &DerivedObject;
5041 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5042 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5043 PathE = E->path_end(); PathI != PathE; ++PathI) {
5044 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5045 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5046 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5047 RD = Base;
5048 }
5049 Result = *Value;
5050 return true;
5051 }
5052 }
5053}
5054
Richard Smithd62306a2011-11-10 06:34:14 +00005055bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5056 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005057 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005058 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5059
5060 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005061 const FieldDecl *Field = E->getInitializedFieldInUnion();
5062 Result = APValue(Field);
5063 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005064 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005065
5066 // If the initializer list for a union does not contain any elements, the
5067 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005068 // FIXME: The element should be initialized from an initializer list.
5069 // Is this difference ever observable for initializer lists which
5070 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005071 ImplicitValueInitExpr VIE(Field->getType());
5072 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5073
Richard Smithd62306a2011-11-10 06:34:14 +00005074 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005075 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5076 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005077
5078 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5079 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5080 isa<CXXDefaultInitExpr>(InitExpr));
5081
Richard Smithb228a862012-02-15 02:18:13 +00005082 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005083 }
5084
5085 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5086 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005087 Result = APValue(APValue::UninitStruct(), 0,
5088 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005089 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005090 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005091 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005092 // Anonymous bit-fields are not considered members of the class for
5093 // purposes of aggregate initialization.
5094 if (Field->isUnnamedBitfield())
5095 continue;
5096
5097 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005098
Richard Smith253c2a32012-01-27 01:14:48 +00005099 bool HaveInit = ElementNo < E->getNumInits();
5100
5101 // FIXME: Diagnostics here should point to the end of the initializer
5102 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005103 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005104 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005105 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005106
5107 // Perform an implicit value-initialization for members beyond the end of
5108 // the initializer list.
5109 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005110 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005111
Richard Smith852c9db2013-04-20 22:23:05 +00005112 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5113 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5114 isa<CXXDefaultInitExpr>(Init));
5115
Richard Smith49ca8aa2013-08-06 07:09:20 +00005116 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5117 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5118 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005119 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005120 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005121 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005122 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005123 }
5124 }
5125
Richard Smith253c2a32012-01-27 01:14:48 +00005126 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005127}
5128
5129bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5130 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005131 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5132
Richard Smithfddd3842011-12-30 21:15:51 +00005133 bool ZeroInit = E->requiresZeroInitialization();
5134 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005135 // If we've already performed zero-initialization, we're already done.
5136 if (!Result.isUninit())
5137 return true;
5138
Richard Smithda3f4fd2014-03-05 23:32:50 +00005139 // We can get here in two different ways:
5140 // 1) We're performing value-initialization, and should zero-initialize
5141 // the object, or
5142 // 2) We're performing default-initialization of an object with a trivial
5143 // constexpr default constructor, in which case we should start the
5144 // lifetimes of all the base subobjects (there can be no data member
5145 // subobjects in this case) per [basic.life]p1.
5146 // Either way, ZeroInitialization is appropriate.
5147 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005148 }
5149
Craig Topper36250ad2014-05-12 05:36:57 +00005150 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005151 FD->getBody(Definition);
5152
Richard Smith357362d2011-12-13 06:39:58 +00005153 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5154 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005155
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005156 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005157 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005158 if (const MaterializeTemporaryExpr *ME
5159 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5160 return Visit(ME->GetTemporaryExpr());
5161
Richard Smithfddd3842011-12-30 21:15:51 +00005162 if (ZeroInit && !ZeroInitialization(E))
5163 return false;
5164
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005165 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005166 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005167 cast<CXXConstructorDecl>(Definition), Info,
5168 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005169}
5170
Richard Smithcc1b96d2013-06-12 22:31:48 +00005171bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5172 const CXXStdInitializerListExpr *E) {
5173 const ConstantArrayType *ArrayType =
5174 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5175
5176 LValue Array;
5177 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5178 return false;
5179
5180 // Get a pointer to the first element of the array.
5181 Array.addArray(Info, E, ArrayType);
5182
5183 // FIXME: Perform the checks on the field types in SemaInit.
5184 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5185 RecordDecl::field_iterator Field = Record->field_begin();
5186 if (Field == Record->field_end())
5187 return Error(E);
5188
5189 // Start pointer.
5190 if (!Field->getType()->isPointerType() ||
5191 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5192 ArrayType->getElementType()))
5193 return Error(E);
5194
5195 // FIXME: What if the initializer_list type has base classes, etc?
5196 Result = APValue(APValue::UninitStruct(), 0, 2);
5197 Array.moveInto(Result.getStructField(0));
5198
5199 if (++Field == Record->field_end())
5200 return Error(E);
5201
5202 if (Field->getType()->isPointerType() &&
5203 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5204 ArrayType->getElementType())) {
5205 // End pointer.
5206 if (!HandleLValueArrayAdjustment(Info, E, Array,
5207 ArrayType->getElementType(),
5208 ArrayType->getSize().getZExtValue()))
5209 return false;
5210 Array.moveInto(Result.getStructField(1));
5211 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5212 // Length.
5213 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5214 else
5215 return Error(E);
5216
5217 if (++Field != Record->field_end())
5218 return Error(E);
5219
5220 return true;
5221}
5222
Richard Smithd62306a2011-11-10 06:34:14 +00005223static bool EvaluateRecord(const Expr *E, const LValue &This,
5224 APValue &Result, EvalInfo &Info) {
5225 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005226 "can't evaluate expression as a record rvalue");
5227 return RecordExprEvaluator(Info, This, Result).Visit(E);
5228}
5229
5230//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005231// Temporary Evaluation
5232//
5233// Temporaries are represented in the AST as rvalues, but generally behave like
5234// lvalues. The full-object of which the temporary is a subobject is implicitly
5235// materialized so that a reference can bind to it.
5236//===----------------------------------------------------------------------===//
5237namespace {
5238class TemporaryExprEvaluator
5239 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5240public:
5241 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5242 LValueExprEvaluatorBaseTy(Info, Result) {}
5243
5244 /// Visit an expression which constructs the value of this temporary.
5245 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005246 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005247 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5248 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005249 }
5250
5251 bool VisitCastExpr(const CastExpr *E) {
5252 switch (E->getCastKind()) {
5253 default:
5254 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5255
5256 case CK_ConstructorConversion:
5257 return VisitConstructExpr(E->getSubExpr());
5258 }
5259 }
5260 bool VisitInitListExpr(const InitListExpr *E) {
5261 return VisitConstructExpr(E);
5262 }
5263 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5264 return VisitConstructExpr(E);
5265 }
5266 bool VisitCallExpr(const CallExpr *E) {
5267 return VisitConstructExpr(E);
5268 }
5269};
5270} // end anonymous namespace
5271
5272/// Evaluate an expression of record type as a temporary.
5273static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005274 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005275 return TemporaryExprEvaluator(Info, Result).Visit(E);
5276}
5277
5278//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005279// Vector Evaluation
5280//===----------------------------------------------------------------------===//
5281
5282namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005283 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005284 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005285 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005286 public:
Mike Stump11289f42009-09-09 15:08:12 +00005287
Richard Smith2d406342011-10-22 21:10:00 +00005288 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5289 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005290
Richard Smith2d406342011-10-22 21:10:00 +00005291 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5292 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5293 // FIXME: remove this APValue copy.
5294 Result = APValue(V.data(), V.size());
5295 return true;
5296 }
Richard Smith2e312c82012-03-03 22:46:17 +00005297 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005298 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005299 Result = V;
5300 return true;
5301 }
Richard Smithfddd3842011-12-30 21:15:51 +00005302 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005303
Richard Smith2d406342011-10-22 21:10:00 +00005304 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005305 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005306 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005307 bool VisitInitListExpr(const InitListExpr *E);
5308 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005309 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005310 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005311 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005312 };
5313} // end anonymous namespace
5314
5315static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005316 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005317 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005318}
5319
Richard Smith2d406342011-10-22 21:10:00 +00005320bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5321 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005322 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005323
Richard Smith161f09a2011-12-06 22:44:34 +00005324 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005325 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005326
Eli Friedmanc757de22011-03-25 00:43:55 +00005327 switch (E->getCastKind()) {
5328 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005329 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005330 if (SETy->isIntegerType()) {
5331 APSInt IntResult;
5332 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005333 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005334 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005335 } else if (SETy->isRealFloatingType()) {
5336 APFloat F(0.0);
5337 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005338 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005339 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005340 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005341 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005342 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005343
5344 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005345 SmallVector<APValue, 4> Elts(NElts, Val);
5346 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005347 }
Eli Friedman803acb32011-12-22 03:51:45 +00005348 case CK_BitCast: {
5349 // Evaluate the operand into an APInt we can extract from.
5350 llvm::APInt SValInt;
5351 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5352 return false;
5353 // Extract the elements
5354 QualType EltTy = VTy->getElementType();
5355 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5356 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5357 SmallVector<APValue, 4> Elts;
5358 if (EltTy->isRealFloatingType()) {
5359 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005360 unsigned FloatEltSize = EltSize;
5361 if (&Sem == &APFloat::x87DoubleExtended)
5362 FloatEltSize = 80;
5363 for (unsigned i = 0; i < NElts; i++) {
5364 llvm::APInt Elt;
5365 if (BigEndian)
5366 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5367 else
5368 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005369 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005370 }
5371 } else if (EltTy->isIntegerType()) {
5372 for (unsigned i = 0; i < NElts; i++) {
5373 llvm::APInt Elt;
5374 if (BigEndian)
5375 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5376 else
5377 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5378 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5379 }
5380 } else {
5381 return Error(E);
5382 }
5383 return Success(Elts, E);
5384 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005385 default:
Richard Smith11562c52011-10-28 17:51:58 +00005386 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005387 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005388}
5389
Richard Smith2d406342011-10-22 21:10:00 +00005390bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005391VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005392 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005393 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005394 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005395
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005396 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005397 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005398
Eli Friedmanb9c71292012-01-03 23:24:20 +00005399 // The number of initializers can be less than the number of
5400 // vector elements. For OpenCL, this can be due to nested vector
5401 // initialization. For GCC compatibility, missing trailing elements
5402 // should be initialized with zeroes.
5403 unsigned CountInits = 0, CountElts = 0;
5404 while (CountElts < NumElements) {
5405 // Handle nested vector initialization.
5406 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005407 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005408 APValue v;
5409 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5410 return Error(E);
5411 unsigned vlen = v.getVectorLength();
5412 for (unsigned j = 0; j < vlen; j++)
5413 Elements.push_back(v.getVectorElt(j));
5414 CountElts += vlen;
5415 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005416 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005417 if (CountInits < NumInits) {
5418 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005419 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005420 } else // trailing integer zero.
5421 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5422 Elements.push_back(APValue(sInt));
5423 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005424 } else {
5425 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005426 if (CountInits < NumInits) {
5427 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005428 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005429 } else // trailing float zero.
5430 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5431 Elements.push_back(APValue(f));
5432 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005433 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005434 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005435 }
Richard Smith2d406342011-10-22 21:10:00 +00005436 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005437}
5438
Richard Smith2d406342011-10-22 21:10:00 +00005439bool
Richard Smithfddd3842011-12-30 21:15:51 +00005440VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005441 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005442 QualType EltTy = VT->getElementType();
5443 APValue ZeroElement;
5444 if (EltTy->isIntegerType())
5445 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5446 else
5447 ZeroElement =
5448 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5449
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005450 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005451 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005452}
5453
Richard Smith2d406342011-10-22 21:10:00 +00005454bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005455 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005456 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005457}
5458
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005459//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005460// Array Evaluation
5461//===----------------------------------------------------------------------===//
5462
5463namespace {
5464 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005465 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005466 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005467 APValue &Result;
5468 public:
5469
Richard Smithd62306a2011-11-10 06:34:14 +00005470 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5471 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005472
5473 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005474 assert((V.isArray() || V.isLValue()) &&
5475 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005476 Result = V;
5477 return true;
5478 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005479
Richard Smithfddd3842011-12-30 21:15:51 +00005480 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005481 const ConstantArrayType *CAT =
5482 Info.Ctx.getAsConstantArrayType(E->getType());
5483 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005484 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005485
5486 Result = APValue(APValue::UninitArray(), 0,
5487 CAT->getSize().getZExtValue());
5488 if (!Result.hasArrayFiller()) return true;
5489
Richard Smithfddd3842011-12-30 21:15:51 +00005490 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005491 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005492 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005493 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005494 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005495 }
5496
Richard Smithf3e9e432011-11-07 09:22:26 +00005497 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005498 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005499 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5500 const LValue &Subobject,
5501 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005502 };
5503} // end anonymous namespace
5504
Richard Smithd62306a2011-11-10 06:34:14 +00005505static bool EvaluateArray(const Expr *E, const LValue &This,
5506 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005507 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005508 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005509}
5510
5511bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5512 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5513 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005514 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005515
Richard Smithca2cfbf2011-12-22 01:07:19 +00005516 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5517 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005518 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005519 LValue LV;
5520 if (!EvaluateLValue(E->getInit(0), LV, Info))
5521 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005522 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005523 LV.moveInto(Val);
5524 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005525 }
5526
Richard Smith253c2a32012-01-27 01:14:48 +00005527 bool Success = true;
5528
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005529 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5530 "zero-initialized array shouldn't have any initialized elts");
5531 APValue Filler;
5532 if (Result.isArray() && Result.hasArrayFiller())
5533 Filler = Result.getArrayFiller();
5534
Richard Smith9543c5e2013-04-22 14:44:29 +00005535 unsigned NumEltsToInit = E->getNumInits();
5536 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005537 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005538
5539 // If the initializer might depend on the array index, run it for each
5540 // array element. For now, just whitelist non-class value-initialization.
5541 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5542 NumEltsToInit = NumElts;
5543
5544 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005545
5546 // If the array was previously zero-initialized, preserve the
5547 // zero-initialized values.
5548 if (!Filler.isUninit()) {
5549 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5550 Result.getArrayInitializedElt(I) = Filler;
5551 if (Result.hasArrayFiller())
5552 Result.getArrayFiller() = Filler;
5553 }
5554
Richard Smithd62306a2011-11-10 06:34:14 +00005555 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005556 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005557 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5558 const Expr *Init =
5559 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005560 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005561 Info, Subobject, Init) ||
5562 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005563 CAT->getElementType(), 1)) {
5564 if (!Info.keepEvaluatingAfterFailure())
5565 return false;
5566 Success = false;
5567 }
Richard Smithd62306a2011-11-10 06:34:14 +00005568 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005569
Richard Smith9543c5e2013-04-22 14:44:29 +00005570 if (!Result.hasArrayFiller())
5571 return Success;
5572
5573 // If we get here, we have a trivial filler, which we can just evaluate
5574 // once and splat over the rest of the array elements.
5575 assert(FillerExpr && "no array filler for incomplete init list");
5576 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5577 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005578}
5579
Richard Smith027bf112011-11-17 22:56:20 +00005580bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005581 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5582}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005583
Richard Smith9543c5e2013-04-22 14:44:29 +00005584bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5585 const LValue &Subobject,
5586 APValue *Value,
5587 QualType Type) {
5588 bool HadZeroInit = !Value->isUninit();
5589
5590 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5591 unsigned N = CAT->getSize().getZExtValue();
5592
5593 // Preserve the array filler if we had prior zero-initialization.
5594 APValue Filler =
5595 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5596 : APValue();
5597
5598 *Value = APValue(APValue::UninitArray(), N, N);
5599
5600 if (HadZeroInit)
5601 for (unsigned I = 0; I != N; ++I)
5602 Value->getArrayInitializedElt(I) = Filler;
5603
5604 // Initialize the elements.
5605 LValue ArrayElt = Subobject;
5606 ArrayElt.addArray(Info, E, CAT);
5607 for (unsigned I = 0; I != N; ++I)
5608 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5609 CAT->getElementType()) ||
5610 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5611 CAT->getElementType(), 1))
5612 return false;
5613
5614 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005615 }
Richard Smith027bf112011-11-17 22:56:20 +00005616
Richard Smith9543c5e2013-04-22 14:44:29 +00005617 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005618 return Error(E);
5619
Richard Smith027bf112011-11-17 22:56:20 +00005620 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005621
Richard Smithfddd3842011-12-30 21:15:51 +00005622 bool ZeroInit = E->requiresZeroInitialization();
5623 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005624 if (HadZeroInit)
5625 return true;
5626
Richard Smithda3f4fd2014-03-05 23:32:50 +00005627 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5628 ImplicitValueInitExpr VIE(Type);
5629 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005630 }
5631
Craig Topper36250ad2014-05-12 05:36:57 +00005632 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005633 FD->getBody(Definition);
5634
Richard Smith357362d2011-12-13 06:39:58 +00005635 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5636 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005637
Richard Smith9eae7232012-01-12 18:54:33 +00005638 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005639 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005640 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005641 return false;
5642 }
5643
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005644 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005645 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005646 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005647 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005648}
5649
Richard Smithf3e9e432011-11-07 09:22:26 +00005650//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005651// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005652//
5653// As a GNU extension, we support casting pointers to sufficiently-wide integer
5654// types and back in constant folding. Integer values are thus represented
5655// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005656//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005657
5658namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005659class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005660 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005661 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005662public:
Richard Smith2e312c82012-03-03 22:46:17 +00005663 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005664 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005665
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005666 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005667 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005668 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005669 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005670 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005671 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005672 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005673 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005674 return true;
5675 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005676 bool Success(const llvm::APSInt &SI, const Expr *E) {
5677 return Success(SI, E, Result);
5678 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005679
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005680 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005681 assert(E->getType()->isIntegralOrEnumerationType() &&
5682 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005683 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005684 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005685 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005686 Result.getInt().setIsUnsigned(
5687 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005688 return true;
5689 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005690 bool Success(const llvm::APInt &I, const Expr *E) {
5691 return Success(I, E, Result);
5692 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005693
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005694 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005695 assert(E->getType()->isIntegralOrEnumerationType() &&
5696 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005697 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005698 return true;
5699 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005700 bool Success(uint64_t Value, const Expr *E) {
5701 return Success(Value, E, Result);
5702 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005703
Ken Dyckdbc01912011-03-11 02:13:43 +00005704 bool Success(CharUnits Size, const Expr *E) {
5705 return Success(Size.getQuantity(), E);
5706 }
5707
Richard Smith2e312c82012-03-03 22:46:17 +00005708 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005709 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005710 Result = V;
5711 return true;
5712 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005713 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005714 }
Mike Stump11289f42009-09-09 15:08:12 +00005715
Richard Smithfddd3842011-12-30 21:15:51 +00005716 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005717
Peter Collingbournee9200682011-05-13 03:29:01 +00005718 //===--------------------------------------------------------------------===//
5719 // Visitor Methods
5720 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005721
Chris Lattner7174bf32008-07-12 00:38:25 +00005722 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005723 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005724 }
5725 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005726 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005727 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005728
5729 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5730 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005731 if (CheckReferencedDecl(E, E->getDecl()))
5732 return true;
5733
5734 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005735 }
5736 bool VisitMemberExpr(const MemberExpr *E) {
5737 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005738 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005739 return true;
5740 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005741
5742 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005743 }
5744
Peter Collingbournee9200682011-05-13 03:29:01 +00005745 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005746 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005747 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005748 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005749
Peter Collingbournee9200682011-05-13 03:29:01 +00005750 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005751 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005752
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005753 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005754 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005755 }
Mike Stump11289f42009-09-09 15:08:12 +00005756
Ted Kremeneke65b0862012-03-06 20:05:56 +00005757 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5758 return Success(E->getValue(), E);
5759 }
5760
Richard Smith4ce706a2011-10-11 21:43:33 +00005761 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005762 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005763 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005764 }
5765
Douglas Gregor29c42f22012-02-24 07:38:34 +00005766 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5767 return Success(E->getValue(), E);
5768 }
5769
John Wiegley6242b6a2011-04-28 00:16:57 +00005770 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5771 return Success(E->getValue(), E);
5772 }
5773
John Wiegleyf9f65842011-04-25 06:54:41 +00005774 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5775 return Success(E->getValue(), E);
5776 }
5777
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005778 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005779 bool VisitUnaryImag(const UnaryOperator *E);
5780
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005781 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005782 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005783
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005784private:
Ken Dyck160146e2010-01-27 17:10:57 +00005785 CharUnits GetAlignOfExpr(const Expr *E);
5786 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005787 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005788 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005789 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005790};
Chris Lattner05706e882008-07-11 18:11:29 +00005791} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005792
Richard Smith11562c52011-10-28 17:51:58 +00005793/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5794/// produce either the integer value or a pointer.
5795///
5796/// GCC has a heinous extension which folds casts between pointer types and
5797/// pointer-sized integral types. We support this by allowing the evaluation of
5798/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5799/// Some simple arithmetic on such values is supported (they are treated much
5800/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005801static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005802 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005803 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005804 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005805}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005806
Richard Smithf57d8cb2011-12-09 22:58:01 +00005807static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005808 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005809 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005810 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005811 if (!Val.isInt()) {
5812 // FIXME: It would be better to produce the diagnostic for casting
5813 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005814 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005815 return false;
5816 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005817 Result = Val.getInt();
5818 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005819}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005820
Richard Smithf57d8cb2011-12-09 22:58:01 +00005821/// Check whether the given declaration can be directly converted to an integral
5822/// rvalue. If not, no diagnostic is produced; there are other things we can
5823/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005824bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005825 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005826 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005827 // Check for signedness/width mismatches between E type and ECD value.
5828 bool SameSign = (ECD->getInitVal().isSigned()
5829 == E->getType()->isSignedIntegerOrEnumerationType());
5830 bool SameWidth = (ECD->getInitVal().getBitWidth()
5831 == Info.Ctx.getIntWidth(E->getType()));
5832 if (SameSign && SameWidth)
5833 return Success(ECD->getInitVal(), E);
5834 else {
5835 // Get rid of mismatch (otherwise Success assertions will fail)
5836 // by computing a new value matching the type of E.
5837 llvm::APSInt Val = ECD->getInitVal();
5838 if (!SameSign)
5839 Val.setIsSigned(!ECD->getInitVal().isSigned());
5840 if (!SameWidth)
5841 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5842 return Success(Val, E);
5843 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005844 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005845 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005846}
5847
Chris Lattner86ee2862008-10-06 06:40:35 +00005848/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5849/// as GCC.
5850static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5851 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005852 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005853 enum gcc_type_class {
5854 no_type_class = -1,
5855 void_type_class, integer_type_class, char_type_class,
5856 enumeral_type_class, boolean_type_class,
5857 pointer_type_class, reference_type_class, offset_type_class,
5858 real_type_class, complex_type_class,
5859 function_type_class, method_type_class,
5860 record_type_class, union_type_class,
5861 array_type_class, string_type_class,
5862 lang_type_class
5863 };
Mike Stump11289f42009-09-09 15:08:12 +00005864
5865 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005866 // ideal, however it is what gcc does.
5867 if (E->getNumArgs() == 0)
5868 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005869
Chris Lattner86ee2862008-10-06 06:40:35 +00005870 QualType ArgTy = E->getArg(0)->getType();
5871 if (ArgTy->isVoidType())
5872 return void_type_class;
5873 else if (ArgTy->isEnumeralType())
5874 return enumeral_type_class;
5875 else if (ArgTy->isBooleanType())
5876 return boolean_type_class;
5877 else if (ArgTy->isCharType())
5878 return string_type_class; // gcc doesn't appear to use char_type_class
5879 else if (ArgTy->isIntegerType())
5880 return integer_type_class;
5881 else if (ArgTy->isPointerType())
5882 return pointer_type_class;
5883 else if (ArgTy->isReferenceType())
5884 return reference_type_class;
5885 else if (ArgTy->isRealType())
5886 return real_type_class;
5887 else if (ArgTy->isComplexType())
5888 return complex_type_class;
5889 else if (ArgTy->isFunctionType())
5890 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005891 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005892 return record_type_class;
5893 else if (ArgTy->isUnionType())
5894 return union_type_class;
5895 else if (ArgTy->isArrayType())
5896 return array_type_class;
5897 else if (ArgTy->isUnionType())
5898 return union_type_class;
5899 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005900 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005901}
5902
Richard Smith5fab0c92011-12-28 19:48:30 +00005903/// EvaluateBuiltinConstantPForLValue - Determine the result of
5904/// __builtin_constant_p when applied to the given lvalue.
5905///
5906/// An lvalue is only "constant" if it is a pointer or reference to the first
5907/// character of a string literal.
5908template<typename LValue>
5909static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005910 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005911 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5912}
5913
5914/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5915/// GCC as we can manage.
5916static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5917 QualType ArgType = Arg->getType();
5918
5919 // __builtin_constant_p always has one operand. The rules which gcc follows
5920 // are not precisely documented, but are as follows:
5921 //
5922 // - If the operand is of integral, floating, complex or enumeration type,
5923 // and can be folded to a known value of that type, it returns 1.
5924 // - If the operand and can be folded to a pointer to the first character
5925 // of a string literal (or such a pointer cast to an integral type), it
5926 // returns 1.
5927 //
5928 // Otherwise, it returns 0.
5929 //
5930 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5931 // its support for this does not currently work.
5932 if (ArgType->isIntegralOrEnumerationType()) {
5933 Expr::EvalResult Result;
5934 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5935 return false;
5936
5937 APValue &V = Result.Val;
5938 if (V.getKind() == APValue::Int)
5939 return true;
5940
5941 return EvaluateBuiltinConstantPForLValue(V);
5942 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5943 return Arg->isEvaluatable(Ctx);
5944 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5945 LValue LV;
5946 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005947 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005948 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5949 : EvaluatePointer(Arg, LV, Info)) &&
5950 !Status.HasSideEffects)
5951 return EvaluateBuiltinConstantPForLValue(LV);
5952 }
5953
5954 // Anything else isn't considered to be sufficiently constant.
5955 return false;
5956}
5957
John McCall95007602010-05-10 23:27:23 +00005958/// Retrieves the "underlying object type" of the given expression,
5959/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005960QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5961 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5962 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005963 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005964 } else if (const Expr *E = B.get<const Expr*>()) {
5965 if (isa<CompoundLiteralExpr>(E))
5966 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005967 }
5968
5969 return QualType();
5970}
5971
Peter Collingbournee9200682011-05-13 03:29:01 +00005972bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005973 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005974
5975 {
5976 // The operand of __builtin_object_size is never evaluated for side-effects.
5977 // If there are any, but we can determine the pointed-to object anyway, then
5978 // ignore the side-effects.
5979 SpeculativeEvaluationRAII SpeculativeEval(Info);
5980 if (!EvaluatePointer(E->getArg(0), Base, Info))
5981 return false;
5982 }
John McCall95007602010-05-10 23:27:23 +00005983
5984 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005985 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005986
Richard Smithce40ad62011-11-12 22:28:03 +00005987 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005988 if (T.isNull() ||
5989 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005990 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005991 T->isVariablyModifiedType() ||
5992 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005993 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005994
5995 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5996 CharUnits Offset = Base.getLValueOffset();
5997
5998 if (!Offset.isNegative() && Offset <= Size)
5999 Size -= Offset;
6000 else
6001 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00006002 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00006003}
6004
Peter Collingbournee9200682011-05-13 03:29:01 +00006005bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006006 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006007 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006008 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006009
6010 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006011 if (TryEvaluateBuiltinObjectSize(E))
6012 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006013
Richard Smith0421ce72012-08-07 04:16:51 +00006014 // If evaluating the argument has side-effects, we can't determine the size
6015 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6016 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006017 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006018 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006019 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006020 return Success(0, E);
6021 }
Mike Stump876387b2009-10-27 22:09:17 +00006022
Richard Smith01ade172012-05-23 04:13:20 +00006023 // Expression had no side effects, but we couldn't statically determine the
6024 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006025 switch (Info.EvalMode) {
6026 case EvalInfo::EM_ConstantExpression:
6027 case EvalInfo::EM_PotentialConstantExpression:
6028 case EvalInfo::EM_ConstantFold:
6029 case EvalInfo::EM_EvaluateForOverflow:
6030 case EvalInfo::EM_IgnoreSideEffects:
6031 return Error(E);
6032 case EvalInfo::EM_ConstantExpressionUnevaluated:
6033 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6034 return Success(-1ULL, E);
6035 }
Mike Stump722cedf2009-10-26 18:35:08 +00006036 }
6037
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006038 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006039 case Builtin::BI__builtin_bswap32:
6040 case Builtin::BI__builtin_bswap64: {
6041 APSInt Val;
6042 if (!EvaluateInteger(E->getArg(0), Val, Info))
6043 return false;
6044
6045 return Success(Val.byteSwap(), E);
6046 }
6047
Richard Smith8889a3d2013-06-13 06:26:32 +00006048 case Builtin::BI__builtin_classify_type:
6049 return Success(EvaluateBuiltinClassifyType(E), E);
6050
6051 // FIXME: BI__builtin_clrsb
6052 // FIXME: BI__builtin_clrsbl
6053 // FIXME: BI__builtin_clrsbll
6054
Richard Smith80b3c8e2013-06-13 05:04:16 +00006055 case Builtin::BI__builtin_clz:
6056 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006057 case Builtin::BI__builtin_clzll:
6058 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006059 APSInt Val;
6060 if (!EvaluateInteger(E->getArg(0), Val, Info))
6061 return false;
6062 if (!Val)
6063 return Error(E);
6064
6065 return Success(Val.countLeadingZeros(), E);
6066 }
6067
Richard Smith8889a3d2013-06-13 06:26:32 +00006068 case Builtin::BI__builtin_constant_p:
6069 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6070
Richard Smith80b3c8e2013-06-13 05:04:16 +00006071 case Builtin::BI__builtin_ctz:
6072 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006073 case Builtin::BI__builtin_ctzll:
6074 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006075 APSInt Val;
6076 if (!EvaluateInteger(E->getArg(0), Val, Info))
6077 return false;
6078 if (!Val)
6079 return Error(E);
6080
6081 return Success(Val.countTrailingZeros(), E);
6082 }
6083
Richard Smith8889a3d2013-06-13 06:26:32 +00006084 case Builtin::BI__builtin_eh_return_data_regno: {
6085 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6086 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6087 return Success(Operand, E);
6088 }
6089
6090 case Builtin::BI__builtin_expect:
6091 return Visit(E->getArg(0));
6092
6093 case Builtin::BI__builtin_ffs:
6094 case Builtin::BI__builtin_ffsl:
6095 case Builtin::BI__builtin_ffsll: {
6096 APSInt Val;
6097 if (!EvaluateInteger(E->getArg(0), Val, Info))
6098 return false;
6099
6100 unsigned N = Val.countTrailingZeros();
6101 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6102 }
6103
6104 case Builtin::BI__builtin_fpclassify: {
6105 APFloat Val(0.0);
6106 if (!EvaluateFloat(E->getArg(5), Val, Info))
6107 return false;
6108 unsigned Arg;
6109 switch (Val.getCategory()) {
6110 case APFloat::fcNaN: Arg = 0; break;
6111 case APFloat::fcInfinity: Arg = 1; break;
6112 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6113 case APFloat::fcZero: Arg = 4; break;
6114 }
6115 return Visit(E->getArg(Arg));
6116 }
6117
6118 case Builtin::BI__builtin_isinf_sign: {
6119 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006120 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006121 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6122 }
6123
Richard Smithea3019d2013-10-15 19:07:14 +00006124 case Builtin::BI__builtin_isinf: {
6125 APFloat Val(0.0);
6126 return EvaluateFloat(E->getArg(0), Val, Info) &&
6127 Success(Val.isInfinity() ? 1 : 0, E);
6128 }
6129
6130 case Builtin::BI__builtin_isfinite: {
6131 APFloat Val(0.0);
6132 return EvaluateFloat(E->getArg(0), Val, Info) &&
6133 Success(Val.isFinite() ? 1 : 0, E);
6134 }
6135
6136 case Builtin::BI__builtin_isnan: {
6137 APFloat Val(0.0);
6138 return EvaluateFloat(E->getArg(0), Val, Info) &&
6139 Success(Val.isNaN() ? 1 : 0, E);
6140 }
6141
6142 case Builtin::BI__builtin_isnormal: {
6143 APFloat Val(0.0);
6144 return EvaluateFloat(E->getArg(0), Val, Info) &&
6145 Success(Val.isNormal() ? 1 : 0, E);
6146 }
6147
Richard Smith8889a3d2013-06-13 06:26:32 +00006148 case Builtin::BI__builtin_parity:
6149 case Builtin::BI__builtin_parityl:
6150 case Builtin::BI__builtin_parityll: {
6151 APSInt Val;
6152 if (!EvaluateInteger(E->getArg(0), Val, Info))
6153 return false;
6154
6155 return Success(Val.countPopulation() % 2, E);
6156 }
6157
Richard Smith80b3c8e2013-06-13 05:04:16 +00006158 case Builtin::BI__builtin_popcount:
6159 case Builtin::BI__builtin_popcountl:
6160 case Builtin::BI__builtin_popcountll: {
6161 APSInt Val;
6162 if (!EvaluateInteger(E->getArg(0), Val, Info))
6163 return false;
6164
6165 return Success(Val.countPopulation(), E);
6166 }
6167
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006168 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006169 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006170 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006171 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006172 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6173 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006174 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006175 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006176 case Builtin::BI__builtin_strlen: {
6177 // As an extension, we support __builtin_strlen() as a constant expression,
6178 // and support folding strlen() to a constant.
6179 LValue String;
6180 if (!EvaluatePointer(E->getArg(0), String, Info))
6181 return false;
6182
6183 // Fast path: if it's a string literal, search the string value.
6184 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6185 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006186 // The string literal may have embedded null characters. Find the first
6187 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006188 StringRef Str = S->getBytes();
6189 int64_t Off = String.Offset.getQuantity();
6190 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6191 S->getCharByteWidth() == 1) {
6192 Str = Str.substr(Off);
6193
6194 StringRef::size_type Pos = Str.find(0);
6195 if (Pos != StringRef::npos)
6196 Str = Str.substr(0, Pos);
6197
6198 return Success(Str.size(), E);
6199 }
6200
6201 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006202 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006203
6204 // Slow path: scan the bytes of the string looking for the terminating 0.
6205 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6206 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6207 APValue Char;
6208 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6209 !Char.isInt())
6210 return false;
6211 if (!Char.getInt())
6212 return Success(Strlen, E);
6213 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6214 return false;
6215 }
6216 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006217
Richard Smith01ba47d2012-04-13 00:45:38 +00006218 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006219 case Builtin::BI__atomic_is_lock_free:
6220 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006221 APSInt SizeVal;
6222 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6223 return false;
6224
6225 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6226 // of two less than the maximum inline atomic width, we know it is
6227 // lock-free. If the size isn't a power of two, or greater than the
6228 // maximum alignment where we promote atomics, we know it is not lock-free
6229 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6230 // the answer can only be determined at runtime; for example, 16-byte
6231 // atomics have lock-free implementations on some, but not all,
6232 // x86-64 processors.
6233
6234 // Check power-of-two.
6235 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006236 if (Size.isPowerOfTwo()) {
6237 // Check against inlining width.
6238 unsigned InlineWidthBits =
6239 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6240 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6241 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6242 Size == CharUnits::One() ||
6243 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6244 Expr::NPC_NeverValueDependent))
6245 // OK, we will inline appropriately-aligned operations of this size,
6246 // and _Atomic(T) is appropriately-aligned.
6247 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006248
Richard Smith01ba47d2012-04-13 00:45:38 +00006249 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6250 castAs<PointerType>()->getPointeeType();
6251 if (!PointeeType->isIncompleteType() &&
6252 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6253 // OK, we will inline operations on this object.
6254 return Success(1, E);
6255 }
6256 }
6257 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006258
Richard Smith01ba47d2012-04-13 00:45:38 +00006259 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6260 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006261 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006262 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006263}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006264
Richard Smith8b3497e2011-10-31 01:37:14 +00006265static bool HasSameBase(const LValue &A, const LValue &B) {
6266 if (!A.getLValueBase())
6267 return !B.getLValueBase();
6268 if (!B.getLValueBase())
6269 return false;
6270
Richard Smithce40ad62011-11-12 22:28:03 +00006271 if (A.getLValueBase().getOpaqueValue() !=
6272 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006273 const Decl *ADecl = GetLValueBaseDecl(A);
6274 if (!ADecl)
6275 return false;
6276 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006277 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006278 return false;
6279 }
6280
6281 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006282 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006283}
6284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006285namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006286
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006287/// \brief Data recursive integer evaluator of certain binary operators.
6288///
6289/// We use a data recursive algorithm for binary operators so that we are able
6290/// to handle extreme cases of chained binary operators without causing stack
6291/// overflow.
6292class DataRecursiveIntBinOpEvaluator {
6293 struct EvalResult {
6294 APValue Val;
6295 bool Failed;
6296
6297 EvalResult() : Failed(false) { }
6298
6299 void swap(EvalResult &RHS) {
6300 Val.swap(RHS.Val);
6301 Failed = RHS.Failed;
6302 RHS.Failed = false;
6303 }
6304 };
6305
6306 struct Job {
6307 const Expr *E;
6308 EvalResult LHSResult; // meaningful only for binary operator expression.
6309 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006310
6311 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006312 void startSpeculativeEval(EvalInfo &Info) {
6313 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006314 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006315 StoredInfo = &Info;
6316 }
6317 ~Job() {
6318 if (StoredInfo) {
6319 StoredInfo->EvalStatus = OldEvalStatus;
6320 }
6321 }
6322 private:
6323 EvalInfo *StoredInfo; // non-null if status changed.
6324 Expr::EvalStatus OldEvalStatus;
6325 };
6326
6327 SmallVector<Job, 16> Queue;
6328
6329 IntExprEvaluator &IntEval;
6330 EvalInfo &Info;
6331 APValue &FinalResult;
6332
6333public:
6334 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6335 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6336
6337 /// \brief True if \param E is a binary operator that we are going to handle
6338 /// data recursively.
6339 /// We handle binary operators that are comma, logical, or that have operands
6340 /// with integral or enumeration type.
6341 static bool shouldEnqueue(const BinaryOperator *E) {
6342 return E->getOpcode() == BO_Comma ||
6343 E->isLogicalOp() ||
6344 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6345 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006346 }
6347
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006348 bool Traverse(const BinaryOperator *E) {
6349 enqueue(E);
6350 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006351 while (!Queue.empty())
6352 process(PrevResult);
6353
6354 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006355
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006356 FinalResult.swap(PrevResult.Val);
6357 return true;
6358 }
6359
6360private:
6361 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6362 return IntEval.Success(Value, E, Result);
6363 }
6364 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6365 return IntEval.Success(Value, E, Result);
6366 }
6367 bool Error(const Expr *E) {
6368 return IntEval.Error(E);
6369 }
6370 bool Error(const Expr *E, diag::kind D) {
6371 return IntEval.Error(E, D);
6372 }
6373
6374 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6375 return Info.CCEDiag(E, D);
6376 }
6377
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006378 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6379 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006380 bool &SuppressRHSDiags);
6381
6382 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6383 const BinaryOperator *E, APValue &Result);
6384
6385 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6386 Result.Failed = !Evaluate(Result.Val, Info, E);
6387 if (Result.Failed)
6388 Result.Val = APValue();
6389 }
6390
Richard Trieuba4d0872012-03-21 23:30:30 +00006391 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006392
6393 void enqueue(const Expr *E) {
6394 E = E->IgnoreParens();
6395 Queue.resize(Queue.size()+1);
6396 Queue.back().E = E;
6397 Queue.back().Kind = Job::AnyExprKind;
6398 }
6399};
6400
6401}
6402
6403bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006404 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006405 bool &SuppressRHSDiags) {
6406 if (E->getOpcode() == BO_Comma) {
6407 // Ignore LHS but note if we could not evaluate it.
6408 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006409 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410 return true;
6411 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006412
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006413 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006414 bool LHSAsBool;
6415 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006416 // We were able to evaluate the LHS, see if we can get away with not
6417 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006418 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6419 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006420 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006421 }
6422 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006423 LHSResult.Failed = true;
6424
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006425 // Since we weren't able to evaluate the left hand side, it
6426 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006427 if (!Info.noteSideEffect())
6428 return false;
6429
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006430 // We can't evaluate the LHS; however, sometimes the result
6431 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6432 // Don't ignore RHS and suppress diagnostics from this arm.
6433 SuppressRHSDiags = true;
6434 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006435
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006436 return true;
6437 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006438
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006439 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6440 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006441
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006442 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006443 return false; // Ignore RHS;
6444
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006445 return true;
6446}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006447
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006448bool DataRecursiveIntBinOpEvaluator::
6449 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6450 const BinaryOperator *E, APValue &Result) {
6451 if (E->getOpcode() == BO_Comma) {
6452 if (RHSResult.Failed)
6453 return false;
6454 Result = RHSResult.Val;
6455 return true;
6456 }
6457
6458 if (E->isLogicalOp()) {
6459 bool lhsResult, rhsResult;
6460 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6461 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6462
6463 if (LHSIsOK) {
6464 if (RHSIsOK) {
6465 if (E->getOpcode() == BO_LOr)
6466 return Success(lhsResult || rhsResult, E, Result);
6467 else
6468 return Success(lhsResult && rhsResult, E, Result);
6469 }
6470 } else {
6471 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006472 // We can't evaluate the LHS; however, sometimes the result
6473 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6474 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006475 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006476 }
6477 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006478
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006479 return false;
6480 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006481
6482 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6483 E->getRHS()->getType()->isIntegralOrEnumerationType());
6484
6485 if (LHSResult.Failed || RHSResult.Failed)
6486 return false;
6487
6488 const APValue &LHSVal = LHSResult.Val;
6489 const APValue &RHSVal = RHSResult.Val;
6490
6491 // Handle cases like (unsigned long)&a + 4.
6492 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6493 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006494 CharUnits AdditionalOffset =
6495 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006496 if (E->getOpcode() == BO_Add)
6497 Result.getLValueOffset() += AdditionalOffset;
6498 else
6499 Result.getLValueOffset() -= AdditionalOffset;
6500 return true;
6501 }
6502
6503 // Handle cases like 4 + (unsigned long)&a
6504 if (E->getOpcode() == BO_Add &&
6505 RHSVal.isLValue() && LHSVal.isInt()) {
6506 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006507 Result.getLValueOffset() +=
6508 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006509 return true;
6510 }
6511
6512 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6513 // Handle (intptr_t)&&A - (intptr_t)&&B.
6514 if (!LHSVal.getLValueOffset().isZero() ||
6515 !RHSVal.getLValueOffset().isZero())
6516 return false;
6517 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6518 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6519 if (!LHSExpr || !RHSExpr)
6520 return false;
6521 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6522 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6523 if (!LHSAddrExpr || !RHSAddrExpr)
6524 return false;
6525 // Make sure both labels come from the same function.
6526 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6527 RHSAddrExpr->getLabel()->getDeclContext())
6528 return false;
6529 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6530 return true;
6531 }
Richard Smith43e77732013-05-07 04:50:00 +00006532
6533 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006534 if (!LHSVal.isInt() || !RHSVal.isInt())
6535 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006536
6537 // Set up the width and signedness manually, in case it can't be deduced
6538 // from the operation we're performing.
6539 // FIXME: Don't do this in the cases where we can deduce it.
6540 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6541 E->getType()->isUnsignedIntegerOrEnumerationType());
6542 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6543 RHSVal.getInt(), Value))
6544 return false;
6545 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006546}
6547
Richard Trieuba4d0872012-03-21 23:30:30 +00006548void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006549 Job &job = Queue.back();
6550
6551 switch (job.Kind) {
6552 case Job::AnyExprKind: {
6553 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6554 if (shouldEnqueue(Bop)) {
6555 job.Kind = Job::BinOpKind;
6556 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006557 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006558 }
6559 }
6560
6561 EvaluateExpr(job.E, Result);
6562 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006563 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006564 }
6565
6566 case Job::BinOpKind: {
6567 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006568 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006569 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006570 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006571 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006572 }
6573 if (SuppressRHSDiags)
6574 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006575 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006576 job.Kind = Job::BinOpVisitedLHSKind;
6577 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006578 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006579 }
6580
6581 case Job::BinOpVisitedLHSKind: {
6582 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6583 EvalResult RHS;
6584 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006585 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006586 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006587 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006588 }
6589 }
6590
6591 llvm_unreachable("Invalid Job::Kind!");
6592}
6593
6594bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6595 if (E->isAssignmentOp())
6596 return Error(E);
6597
6598 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6599 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006600
Anders Carlssonacc79812008-11-16 07:17:21 +00006601 QualType LHSTy = E->getLHS()->getType();
6602 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006603
6604 if (LHSTy->isAnyComplexType()) {
6605 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006606 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006607
Richard Smith253c2a32012-01-27 01:14:48 +00006608 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6609 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006610 return false;
6611
Richard Smith253c2a32012-01-27 01:14:48 +00006612 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006613 return false;
6614
6615 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006616 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006617 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006618 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006619 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6620
John McCalle3027922010-08-25 11:45:40 +00006621 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006622 return Success((CR_r == APFloat::cmpEqual &&
6623 CR_i == APFloat::cmpEqual), E);
6624 else {
John McCalle3027922010-08-25 11:45:40 +00006625 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006626 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006627 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006628 CR_r == APFloat::cmpLessThan ||
6629 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006630 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006631 CR_i == APFloat::cmpLessThan ||
6632 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006633 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006634 } else {
John McCalle3027922010-08-25 11:45:40 +00006635 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006636 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6637 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6638 else {
John McCalle3027922010-08-25 11:45:40 +00006639 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006640 "Invalid compex comparison.");
6641 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6642 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6643 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006644 }
6645 }
Mike Stump11289f42009-09-09 15:08:12 +00006646
Anders Carlssonacc79812008-11-16 07:17:21 +00006647 if (LHSTy->isRealFloatingType() &&
6648 RHSTy->isRealFloatingType()) {
6649 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006650
Richard Smith253c2a32012-01-27 01:14:48 +00006651 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6652 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006653 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006654
Richard Smith253c2a32012-01-27 01:14:48 +00006655 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006656 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006657
Anders Carlssonacc79812008-11-16 07:17:21 +00006658 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006659
Anders Carlssonacc79812008-11-16 07:17:21 +00006660 switch (E->getOpcode()) {
6661 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006662 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006663 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006664 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006665 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006666 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006667 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006668 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006669 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006670 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006671 E);
John McCalle3027922010-08-25 11:45:40 +00006672 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006673 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006674 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006675 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006676 || CR == APFloat::cmpLessThan
6677 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006678 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006679 }
Mike Stump11289f42009-09-09 15:08:12 +00006680
Eli Friedmana38da572009-04-28 19:17:36 +00006681 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006682 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006683 LValue LHSValue, RHSValue;
6684
6685 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6686 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006687 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006688
Richard Smith253c2a32012-01-27 01:14:48 +00006689 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006690 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006691
Richard Smith8b3497e2011-10-31 01:37:14 +00006692 // Reject differing bases from the normal codepath; we special-case
6693 // comparisons to null.
6694 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006695 if (E->getOpcode() == BO_Sub) {
6696 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006697 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6698 return false;
6699 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006700 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006701 if (!LHSExpr || !RHSExpr)
6702 return false;
6703 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6704 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6705 if (!LHSAddrExpr || !RHSAddrExpr)
6706 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006707 // Make sure both labels come from the same function.
6708 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6709 RHSAddrExpr->getLabel()->getDeclContext())
6710 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006711 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006712 return true;
6713 }
Richard Smith83c68212011-10-31 05:11:32 +00006714 // Inequalities and subtractions between unrelated pointers have
6715 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006716 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006717 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006718 // A constant address may compare equal to the address of a symbol.
6719 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006720 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006721 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6722 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006723 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006724 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006725 // distinct addresses. In clang, the result of such a comparison is
6726 // unspecified, so it is not a constant expression. However, we do know
6727 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006728 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6729 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006730 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006731 // We can't tell whether weak symbols will end up pointing to the same
6732 // object.
6733 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006734 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006735 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006736 // (Note that clang defaults to -fmerge-all-constants, which can
6737 // lead to inconsistent results for comparisons involving the address
6738 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006739 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006740 }
Eli Friedman64004332009-03-23 04:38:34 +00006741
Richard Smith1b470412012-02-01 08:10:20 +00006742 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6743 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6744
Richard Smith84f6dcf2012-02-02 01:16:57 +00006745 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6746 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6747
John McCalle3027922010-08-25 11:45:40 +00006748 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006749 // C++11 [expr.add]p6:
6750 // Unless both pointers point to elements of the same array object, or
6751 // one past the last element of the array object, the behavior is
6752 // undefined.
6753 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6754 !AreElementsOfSameArray(getType(LHSValue.Base),
6755 LHSDesignator, RHSDesignator))
6756 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6757
Chris Lattner882bdf22010-04-20 17:13:14 +00006758 QualType Type = E->getLHS()->getType();
6759 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006760
Richard Smithd62306a2011-11-10 06:34:14 +00006761 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006762 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006763 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006764
Richard Smith84c6b3d2013-09-10 21:34:14 +00006765 // As an extension, a type may have zero size (empty struct or union in
6766 // C, array of zero length). Pointer subtraction in such cases has
6767 // undefined behavior, so is not constant.
6768 if (ElementSize.isZero()) {
6769 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6770 << ElementType;
6771 return false;
6772 }
6773
Richard Smith1b470412012-02-01 08:10:20 +00006774 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6775 // and produce incorrect results when it overflows. Such behavior
6776 // appears to be non-conforming, but is common, so perhaps we should
6777 // assume the standard intended for such cases to be undefined behavior
6778 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006779
Richard Smith1b470412012-02-01 08:10:20 +00006780 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6781 // overflow in the final conversion to ptrdiff_t.
6782 APSInt LHS(
6783 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6784 APSInt RHS(
6785 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6786 APSInt ElemSize(
6787 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6788 APSInt TrueResult = (LHS - RHS) / ElemSize;
6789 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6790
6791 if (Result.extend(65) != TrueResult)
6792 HandleOverflow(Info, E, TrueResult, E->getType());
6793 return Success(Result, E);
6794 }
Richard Smithde21b242012-01-31 06:41:30 +00006795
6796 // C++11 [expr.rel]p3:
6797 // Pointers to void (after pointer conversions) can be compared, with a
6798 // result defined as follows: If both pointers represent the same
6799 // address or are both the null pointer value, the result is true if the
6800 // operator is <= or >= and false otherwise; otherwise the result is
6801 // unspecified.
6802 // We interpret this as applying to pointers to *cv* void.
6803 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006804 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006805 CCEDiag(E, diag::note_constexpr_void_comparison);
6806
Richard Smith84f6dcf2012-02-02 01:16:57 +00006807 // C++11 [expr.rel]p2:
6808 // - If two pointers point to non-static data members of the same object,
6809 // or to subobjects or array elements fo such members, recursively, the
6810 // pointer to the later declared member compares greater provided the
6811 // two members have the same access control and provided their class is
6812 // not a union.
6813 // [...]
6814 // - Otherwise pointer comparisons are unspecified.
6815 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6816 E->isRelationalOp()) {
6817 bool WasArrayIndex;
6818 unsigned Mismatch =
6819 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6820 RHSDesignator, WasArrayIndex);
6821 // At the point where the designators diverge, the comparison has a
6822 // specified value if:
6823 // - we are comparing array indices
6824 // - we are comparing fields of a union, or fields with the same access
6825 // Otherwise, the result is unspecified and thus the comparison is not a
6826 // constant expression.
6827 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6828 Mismatch < RHSDesignator.Entries.size()) {
6829 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6830 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6831 if (!LF && !RF)
6832 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6833 else if (!LF)
6834 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6835 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6836 << RF->getParent() << RF;
6837 else if (!RF)
6838 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6839 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6840 << LF->getParent() << LF;
6841 else if (!LF->getParent()->isUnion() &&
6842 LF->getAccess() != RF->getAccess())
6843 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6844 << LF << LF->getAccess() << RF << RF->getAccess()
6845 << LF->getParent();
6846 }
6847 }
6848
Eli Friedman6c31cb42012-04-16 04:30:08 +00006849 // The comparison here must be unsigned, and performed with the same
6850 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006851 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6852 uint64_t CompareLHS = LHSOffset.getQuantity();
6853 uint64_t CompareRHS = RHSOffset.getQuantity();
6854 assert(PtrSize <= 64 && "Unexpected pointer width");
6855 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6856 CompareLHS &= Mask;
6857 CompareRHS &= Mask;
6858
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006859 // If there is a base and this is a relational operator, we can only
6860 // compare pointers within the object in question; otherwise, the result
6861 // depends on where the object is located in memory.
6862 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6863 QualType BaseTy = getType(LHSValue.Base);
6864 if (BaseTy->isIncompleteType())
6865 return Error(E);
6866 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6867 uint64_t OffsetLimit = Size.getQuantity();
6868 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6869 return Error(E);
6870 }
6871
Richard Smith8b3497e2011-10-31 01:37:14 +00006872 switch (E->getOpcode()) {
6873 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006874 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6875 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6876 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6877 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6878 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6879 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006880 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006881 }
6882 }
Richard Smith7bb00672012-02-01 01:42:44 +00006883
6884 if (LHSTy->isMemberPointerType()) {
6885 assert(E->isEqualityOp() && "unexpected member pointer operation");
6886 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6887
6888 MemberPtr LHSValue, RHSValue;
6889
6890 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6891 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6892 return false;
6893
6894 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6895 return false;
6896
6897 // C++11 [expr.eq]p2:
6898 // If both operands are null, they compare equal. Otherwise if only one is
6899 // null, they compare unequal.
6900 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6901 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6902 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6903 }
6904
6905 // Otherwise if either is a pointer to a virtual member function, the
6906 // result is unspecified.
6907 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6908 if (MD->isVirtual())
6909 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6911 if (MD->isVirtual())
6912 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6913
6914 // Otherwise they compare equal if and only if they would refer to the
6915 // same member of the same most derived object or the same subobject if
6916 // they were dereferenced with a hypothetical object of the associated
6917 // class type.
6918 bool Equal = LHSValue == RHSValue;
6919 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6920 }
6921
Richard Smithab44d9b2012-02-14 22:35:28 +00006922 if (LHSTy->isNullPtrType()) {
6923 assert(E->isComparisonOp() && "unexpected nullptr operation");
6924 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6925 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6926 // are compared, the result is true of the operator is <=, >= or ==, and
6927 // false otherwise.
6928 BinaryOperator::Opcode Opcode = E->getOpcode();
6929 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6930 }
6931
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006932 assert((!LHSTy->isIntegralOrEnumerationType() ||
6933 !RHSTy->isIntegralOrEnumerationType()) &&
6934 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6935 // We can't continue from here for non-integral types.
6936 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006937}
6938
Ken Dyck160146e2010-01-27 17:10:57 +00006939CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Richard Smithf6d70302014-06-10 23:34:28 +00006940 // C++ [expr.alignof]p3:
6941 // When alignof is applied to a reference type, the result is the
6942 // alignment of the referenced type.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006943 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6944 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006945
6946 // __alignof is defined to return the preferred alignment.
6947 return Info.Ctx.toCharUnitsFromBits(
6948 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006949}
6950
Ken Dyck160146e2010-01-27 17:10:57 +00006951CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006952 E = E->IgnoreParens();
6953
John McCall768439e2013-05-06 07:40:34 +00006954 // The kinds of expressions that we have special-case logic here for
6955 // should be kept up to date with the special checks for those
6956 // expressions in Sema.
6957
Chris Lattner68061312009-01-24 21:53:27 +00006958 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006959 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006960 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithf6d70302014-06-10 23:34:28 +00006961 return Info.Ctx.getDeclAlign(DRE->getDecl(),
Ken Dyck160146e2010-01-27 17:10:57 +00006962 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006963
Chris Lattner68061312009-01-24 21:53:27 +00006964 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006965 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6966 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006967
Chris Lattner24aeeab2009-01-24 21:09:06 +00006968 return GetAlignOfType(E->getType());
6969}
6970
6971
Peter Collingbournee190dee2011-03-11 19:24:49 +00006972/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6973/// a result as the expression's type.
6974bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6975 const UnaryExprOrTypeTraitExpr *E) {
6976 switch(E->getKind()) {
6977 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006978 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006979 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006980 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006981 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006982 }
Eli Friedman64004332009-03-23 04:38:34 +00006983
Peter Collingbournee190dee2011-03-11 19:24:49 +00006984 case UETT_VecStep: {
6985 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006986
Peter Collingbournee190dee2011-03-11 19:24:49 +00006987 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006988 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006989
Peter Collingbournee190dee2011-03-11 19:24:49 +00006990 // The vec_step built-in functions that take a 3-component
6991 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6992 if (n == 3)
6993 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006994
Peter Collingbournee190dee2011-03-11 19:24:49 +00006995 return Success(n, E);
6996 } else
6997 return Success(1, E);
6998 }
6999
7000 case UETT_SizeOf: {
7001 QualType SrcTy = E->getTypeOfArgument();
7002 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7003 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007004 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7005 SrcTy = Ref->getPointeeType();
7006
Richard Smithd62306a2011-11-10 06:34:14 +00007007 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007008 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007009 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007010 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007011 }
7012 }
7013
7014 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007015}
7016
Peter Collingbournee9200682011-05-13 03:29:01 +00007017bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007018 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007019 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007020 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007021 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007022 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007023 for (unsigned i = 0; i != n; ++i) {
7024 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7025 switch (ON.getKind()) {
7026 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007027 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007028 APSInt IdxResult;
7029 if (!EvaluateInteger(Idx, IdxResult, Info))
7030 return false;
7031 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7032 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007033 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007034 CurrentType = AT->getElementType();
7035 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7036 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007037 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007038 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007039
Douglas Gregor882211c2010-04-28 22:16:22 +00007040 case OffsetOfExpr::OffsetOfNode::Field: {
7041 FieldDecl *MemberDecl = ON.getField();
7042 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007043 if (!RT)
7044 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007045 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007046 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007047 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007048 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007049 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007050 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007051 CurrentType = MemberDecl->getType().getNonReferenceType();
7052 break;
7053 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007054
Douglas Gregor882211c2010-04-28 22:16:22 +00007055 case OffsetOfExpr::OffsetOfNode::Identifier:
7056 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007057
Douglas Gregord1702062010-04-29 00:18:15 +00007058 case OffsetOfExpr::OffsetOfNode::Base: {
7059 CXXBaseSpecifier *BaseSpec = ON.getBase();
7060 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007061 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007062
7063 // Find the layout of the class whose base we are looking into.
7064 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007065 if (!RT)
7066 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007067 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007068 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007069 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7070
7071 // Find the base class itself.
7072 CurrentType = BaseSpec->getType();
7073 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7074 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007075 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007076
7077 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007078 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007079 break;
7080 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007081 }
7082 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007083 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007084}
7085
Chris Lattnere13042c2008-07-11 19:10:17 +00007086bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007087 switch (E->getOpcode()) {
7088 default:
7089 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7090 // See C99 6.6p3.
7091 return Error(E);
7092 case UO_Extension:
7093 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7094 // If so, we could clear the diagnostic ID.
7095 return Visit(E->getSubExpr());
7096 case UO_Plus:
7097 // The result is just the value.
7098 return Visit(E->getSubExpr());
7099 case UO_Minus: {
7100 if (!Visit(E->getSubExpr()))
7101 return false;
7102 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007103 const APSInt &Value = Result.getInt();
7104 if (Value.isSigned() && Value.isMinSignedValue())
7105 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7106 E->getType());
7107 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007108 }
7109 case UO_Not: {
7110 if (!Visit(E->getSubExpr()))
7111 return false;
7112 if (!Result.isInt()) return Error(E);
7113 return Success(~Result.getInt(), E);
7114 }
7115 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007116 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007117 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007118 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007119 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007120 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007121 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007122}
Mike Stump11289f42009-09-09 15:08:12 +00007123
Chris Lattner477c4be2008-07-12 01:15:53 +00007124/// HandleCast - This is used to evaluate implicit or explicit casts where the
7125/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007126bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7127 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007128 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007129 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007130
Eli Friedmanc757de22011-03-25 00:43:55 +00007131 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007132 case CK_BaseToDerived:
7133 case CK_DerivedToBase:
7134 case CK_UncheckedDerivedToBase:
7135 case CK_Dynamic:
7136 case CK_ToUnion:
7137 case CK_ArrayToPointerDecay:
7138 case CK_FunctionToPointerDecay:
7139 case CK_NullToPointer:
7140 case CK_NullToMemberPointer:
7141 case CK_BaseToDerivedMemberPointer:
7142 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007143 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007144 case CK_ConstructorConversion:
7145 case CK_IntegralToPointer:
7146 case CK_ToVoid:
7147 case CK_VectorSplat:
7148 case CK_IntegralToFloating:
7149 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007150 case CK_CPointerToObjCPointerCast:
7151 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007152 case CK_AnyPointerToBlockPointerCast:
7153 case CK_ObjCObjectLValueCast:
7154 case CK_FloatingRealToComplex:
7155 case CK_FloatingComplexToReal:
7156 case CK_FloatingComplexCast:
7157 case CK_FloatingComplexToIntegralComplex:
7158 case CK_IntegralRealToComplex:
7159 case CK_IntegralComplexCast:
7160 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007161 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007162 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007163 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007164 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007165 llvm_unreachable("invalid cast kind for integral value");
7166
Eli Friedman9faf2f92011-03-25 19:07:11 +00007167 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007168 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007169 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007170 case CK_ARCProduceObject:
7171 case CK_ARCConsumeObject:
7172 case CK_ARCReclaimReturnedObject:
7173 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007174 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007175 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007176
Richard Smith4ef685b2012-01-17 21:17:26 +00007177 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007178 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007179 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007180 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007181 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007182
7183 case CK_MemberPointerToBoolean:
7184 case CK_PointerToBoolean:
7185 case CK_IntegralToBoolean:
7186 case CK_FloatingToBoolean:
7187 case CK_FloatingComplexToBoolean:
7188 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007189 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007190 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007191 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007192 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007193 }
7194
Eli Friedmanc757de22011-03-25 00:43:55 +00007195 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007196 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007197 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007198
Eli Friedman742421e2009-02-20 01:15:07 +00007199 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007200 // Allow casts of address-of-label differences if they are no-ops
7201 // or narrowing. (The narrowing case isn't actually guaranteed to
7202 // be constant-evaluatable except in some narrow cases which are hard
7203 // to detect here. We let it through on the assumption the user knows
7204 // what they are doing.)
7205 if (Result.isAddrLabelDiff())
7206 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007207 // Only allow casts of lvalues if they are lossless.
7208 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7209 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007210
Richard Smith911e1422012-01-30 22:27:01 +00007211 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7212 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007213 }
Mike Stump11289f42009-09-09 15:08:12 +00007214
Eli Friedmanc757de22011-03-25 00:43:55 +00007215 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007216 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7217
John McCall45d55e42010-05-07 21:00:08 +00007218 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007219 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007220 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007221
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007222 if (LV.getLValueBase()) {
7223 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007224 // FIXME: Allow a larger integer size than the pointer size, and allow
7225 // narrowing back down to pointer width in subsequent integral casts.
7226 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007227 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007228 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007229
Richard Smithcf74da72011-11-16 07:18:12 +00007230 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007231 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007232 return true;
7233 }
7234
Ken Dyck02990832010-01-15 12:37:54 +00007235 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7236 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007237 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007238 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007239
Eli Friedmanc757de22011-03-25 00:43:55 +00007240 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007241 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007242 if (!EvaluateComplex(SubExpr, C, Info))
7243 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007244 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007245 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007246
Eli Friedmanc757de22011-03-25 00:43:55 +00007247 case CK_FloatingToIntegral: {
7248 APFloat F(0.0);
7249 if (!EvaluateFloat(SubExpr, F, Info))
7250 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007251
Richard Smith357362d2011-12-13 06:39:58 +00007252 APSInt Value;
7253 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7254 return false;
7255 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007256 }
7257 }
Mike Stump11289f42009-09-09 15:08:12 +00007258
Eli Friedmanc757de22011-03-25 00:43:55 +00007259 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007260}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007261
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007262bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7263 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007264 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007265 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7266 return false;
7267 if (!LV.isComplexInt())
7268 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007269 return Success(LV.getComplexIntReal(), E);
7270 }
7271
7272 return Visit(E->getSubExpr());
7273}
7274
Eli Friedman4e7a2412009-02-27 04:45:43 +00007275bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007276 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007277 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007278 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7279 return false;
7280 if (!LV.isComplexInt())
7281 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007282 return Success(LV.getComplexIntImag(), E);
7283 }
7284
Richard Smith4a678122011-10-24 18:44:57 +00007285 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007286 return Success(0, E);
7287}
7288
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007289bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7290 return Success(E->getPackLength(), E);
7291}
7292
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007293bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7294 return Success(E->getValue(), E);
7295}
7296
Chris Lattner05706e882008-07-11 18:11:29 +00007297//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007298// Float Evaluation
7299//===----------------------------------------------------------------------===//
7300
7301namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007302class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007303 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007304 APFloat &Result;
7305public:
7306 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007307 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007308
Richard Smith2e312c82012-03-03 22:46:17 +00007309 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007310 Result = V.getFloat();
7311 return true;
7312 }
Eli Friedman24c01542008-08-22 00:06:13 +00007313
Richard Smithfddd3842011-12-30 21:15:51 +00007314 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007315 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7316 return true;
7317 }
7318
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007319 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007320
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007321 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007322 bool VisitBinaryOperator(const BinaryOperator *E);
7323 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007324 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007325
John McCallb1fb0d32010-05-07 22:08:54 +00007326 bool VisitUnaryReal(const UnaryOperator *E);
7327 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007328
Richard Smithfddd3842011-12-30 21:15:51 +00007329 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007330};
7331} // end anonymous namespace
7332
7333static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007334 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007335 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007336}
7337
Jay Foad39c79802011-01-12 09:06:06 +00007338static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007339 QualType ResultTy,
7340 const Expr *Arg,
7341 bool SNaN,
7342 llvm::APFloat &Result) {
7343 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7344 if (!S) return false;
7345
7346 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7347
7348 llvm::APInt fill;
7349
7350 // Treat empty strings as if they were zero.
7351 if (S->getString().empty())
7352 fill = llvm::APInt(32, 0);
7353 else if (S->getString().getAsInteger(0, fill))
7354 return false;
7355
7356 if (SNaN)
7357 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7358 else
7359 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7360 return true;
7361}
7362
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007363bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007364 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007365 default:
7366 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7367
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007368 case Builtin::BI__builtin_huge_val:
7369 case Builtin::BI__builtin_huge_valf:
7370 case Builtin::BI__builtin_huge_vall:
7371 case Builtin::BI__builtin_inf:
7372 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007373 case Builtin::BI__builtin_infl: {
7374 const llvm::fltSemantics &Sem =
7375 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007376 Result = llvm::APFloat::getInf(Sem);
7377 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007378 }
Mike Stump11289f42009-09-09 15:08:12 +00007379
John McCall16291492010-02-28 13:00:19 +00007380 case Builtin::BI__builtin_nans:
7381 case Builtin::BI__builtin_nansf:
7382 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007383 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7384 true, Result))
7385 return Error(E);
7386 return true;
John McCall16291492010-02-28 13:00:19 +00007387
Chris Lattner0b7282e2008-10-06 06:31:58 +00007388 case Builtin::BI__builtin_nan:
7389 case Builtin::BI__builtin_nanf:
7390 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007391 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007392 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007393 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7394 false, Result))
7395 return Error(E);
7396 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007397
7398 case Builtin::BI__builtin_fabs:
7399 case Builtin::BI__builtin_fabsf:
7400 case Builtin::BI__builtin_fabsl:
7401 if (!EvaluateFloat(E->getArg(0), Result, Info))
7402 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007403
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007404 if (Result.isNegative())
7405 Result.changeSign();
7406 return true;
7407
Richard Smith8889a3d2013-06-13 06:26:32 +00007408 // FIXME: Builtin::BI__builtin_powi
7409 // FIXME: Builtin::BI__builtin_powif
7410 // FIXME: Builtin::BI__builtin_powil
7411
Mike Stump11289f42009-09-09 15:08:12 +00007412 case Builtin::BI__builtin_copysign:
7413 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007414 case Builtin::BI__builtin_copysignl: {
7415 APFloat RHS(0.);
7416 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7417 !EvaluateFloat(E->getArg(1), RHS, Info))
7418 return false;
7419 Result.copySign(RHS);
7420 return true;
7421 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007422 }
7423}
7424
John McCallb1fb0d32010-05-07 22:08:54 +00007425bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007426 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7427 ComplexValue CV;
7428 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7429 return false;
7430 Result = CV.FloatReal;
7431 return true;
7432 }
7433
7434 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007435}
7436
7437bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007438 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7439 ComplexValue CV;
7440 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7441 return false;
7442 Result = CV.FloatImag;
7443 return true;
7444 }
7445
Richard Smith4a678122011-10-24 18:44:57 +00007446 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007447 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7448 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007449 return true;
7450}
7451
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007452bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007453 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007454 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007455 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007456 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007457 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007458 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7459 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007460 Result.changeSign();
7461 return true;
7462 }
7463}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007464
Eli Friedman24c01542008-08-22 00:06:13 +00007465bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007466 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7467 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007468
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007469 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007470 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7471 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007472 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007473 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7474 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007475}
7476
7477bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7478 Result = E->getValue();
7479 return true;
7480}
7481
Peter Collingbournee9200682011-05-13 03:29:01 +00007482bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7483 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007484
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007485 switch (E->getCastKind()) {
7486 default:
Richard Smith11562c52011-10-28 17:51:58 +00007487 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007488
7489 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007490 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007491 return EvaluateInteger(SubExpr, IntResult, Info) &&
7492 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7493 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007494 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007495
7496 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007497 if (!Visit(SubExpr))
7498 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007499 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7500 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007501 }
John McCalld7646252010-11-14 08:17:51 +00007502
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007503 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007504 ComplexValue V;
7505 if (!EvaluateComplex(SubExpr, V, Info))
7506 return false;
7507 Result = V.getComplexFloatReal();
7508 return true;
7509 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007510 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007511}
7512
Eli Friedman24c01542008-08-22 00:06:13 +00007513//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007514// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007515//===----------------------------------------------------------------------===//
7516
7517namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007518class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007519 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007520 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007521
Anders Carlsson537969c2008-11-16 20:27:53 +00007522public:
John McCall93d91dc2010-05-07 17:22:02 +00007523 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007524 : ExprEvaluatorBaseTy(info), Result(Result) {}
7525
Richard Smith2e312c82012-03-03 22:46:17 +00007526 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007527 Result.setFrom(V);
7528 return true;
7529 }
Mike Stump11289f42009-09-09 15:08:12 +00007530
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007531 bool ZeroInitialization(const Expr *E);
7532
Anders Carlsson537969c2008-11-16 20:27:53 +00007533 //===--------------------------------------------------------------------===//
7534 // Visitor Methods
7535 //===--------------------------------------------------------------------===//
7536
Peter Collingbournee9200682011-05-13 03:29:01 +00007537 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007538 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007539 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007540 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007541 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007542};
7543} // end anonymous namespace
7544
John McCall93d91dc2010-05-07 17:22:02 +00007545static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7546 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007547 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007548 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007549}
7550
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007551bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007552 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007553 if (ElemTy->isRealFloatingType()) {
7554 Result.makeComplexFloat();
7555 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7556 Result.FloatReal = Zero;
7557 Result.FloatImag = Zero;
7558 } else {
7559 Result.makeComplexInt();
7560 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7561 Result.IntReal = Zero;
7562 Result.IntImag = Zero;
7563 }
7564 return true;
7565}
7566
Peter Collingbournee9200682011-05-13 03:29:01 +00007567bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7568 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007569
7570 if (SubExpr->getType()->isRealFloatingType()) {
7571 Result.makeComplexFloat();
7572 APFloat &Imag = Result.FloatImag;
7573 if (!EvaluateFloat(SubExpr, Imag, Info))
7574 return false;
7575
7576 Result.FloatReal = APFloat(Imag.getSemantics());
7577 return true;
7578 } else {
7579 assert(SubExpr->getType()->isIntegerType() &&
7580 "Unexpected imaginary literal.");
7581
7582 Result.makeComplexInt();
7583 APSInt &Imag = Result.IntImag;
7584 if (!EvaluateInteger(SubExpr, Imag, Info))
7585 return false;
7586
7587 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7588 return true;
7589 }
7590}
7591
Peter Collingbournee9200682011-05-13 03:29:01 +00007592bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007593
John McCallfcef3cf2010-12-14 17:51:41 +00007594 switch (E->getCastKind()) {
7595 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007596 case CK_BaseToDerived:
7597 case CK_DerivedToBase:
7598 case CK_UncheckedDerivedToBase:
7599 case CK_Dynamic:
7600 case CK_ToUnion:
7601 case CK_ArrayToPointerDecay:
7602 case CK_FunctionToPointerDecay:
7603 case CK_NullToPointer:
7604 case CK_NullToMemberPointer:
7605 case CK_BaseToDerivedMemberPointer:
7606 case CK_DerivedToBaseMemberPointer:
7607 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007608 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007609 case CK_ConstructorConversion:
7610 case CK_IntegralToPointer:
7611 case CK_PointerToIntegral:
7612 case CK_PointerToBoolean:
7613 case CK_ToVoid:
7614 case CK_VectorSplat:
7615 case CK_IntegralCast:
7616 case CK_IntegralToBoolean:
7617 case CK_IntegralToFloating:
7618 case CK_FloatingToIntegral:
7619 case CK_FloatingToBoolean:
7620 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007621 case CK_CPointerToObjCPointerCast:
7622 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007623 case CK_AnyPointerToBlockPointerCast:
7624 case CK_ObjCObjectLValueCast:
7625 case CK_FloatingComplexToReal:
7626 case CK_FloatingComplexToBoolean:
7627 case CK_IntegralComplexToReal:
7628 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007629 case CK_ARCProduceObject:
7630 case CK_ARCConsumeObject:
7631 case CK_ARCReclaimReturnedObject:
7632 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007633 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007634 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007635 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007636 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007637 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007638 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007639
John McCallfcef3cf2010-12-14 17:51:41 +00007640 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007641 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007642 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007643 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007644
7645 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007646 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007647 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007648 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007649
7650 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007651 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007652 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007653 return false;
7654
John McCallfcef3cf2010-12-14 17:51:41 +00007655 Result.makeComplexFloat();
7656 Result.FloatImag = APFloat(Real.getSemantics());
7657 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007658 }
7659
John McCallfcef3cf2010-12-14 17:51:41 +00007660 case CK_FloatingComplexCast: {
7661 if (!Visit(E->getSubExpr()))
7662 return false;
7663
7664 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7665 QualType From
7666 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7667
Richard Smith357362d2011-12-13 06:39:58 +00007668 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7669 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007670 }
7671
7672 case CK_FloatingComplexToIntegralComplex: {
7673 if (!Visit(E->getSubExpr()))
7674 return false;
7675
7676 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7677 QualType From
7678 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7679 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007680 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7681 To, Result.IntReal) &&
7682 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7683 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007684 }
7685
7686 case CK_IntegralRealToComplex: {
7687 APSInt &Real = Result.IntReal;
7688 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7689 return false;
7690
7691 Result.makeComplexInt();
7692 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7693 return true;
7694 }
7695
7696 case CK_IntegralComplexCast: {
7697 if (!Visit(E->getSubExpr()))
7698 return false;
7699
7700 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7701 QualType From
7702 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7703
Richard Smith911e1422012-01-30 22:27:01 +00007704 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7705 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007706 return true;
7707 }
7708
7709 case CK_IntegralComplexToFloatingComplex: {
7710 if (!Visit(E->getSubExpr()))
7711 return false;
7712
Ted Kremenek28831752012-08-23 20:46:57 +00007713 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007714 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007715 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007716 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007717 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7718 To, Result.FloatReal) &&
7719 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7720 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007721 }
7722 }
7723
7724 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007725}
7726
John McCall93d91dc2010-05-07 17:22:02 +00007727bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007728 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007729 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7730
Richard Smith253c2a32012-01-27 01:14:48 +00007731 bool LHSOK = Visit(E->getLHS());
7732 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007733 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007734
John McCall93d91dc2010-05-07 17:22:02 +00007735 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007736 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007737 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007738
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007739 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7740 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007741 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007742 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007743 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007744 if (Result.isComplexFloat()) {
7745 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7746 APFloat::rmNearestTiesToEven);
7747 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7748 APFloat::rmNearestTiesToEven);
7749 } else {
7750 Result.getComplexIntReal() += RHS.getComplexIntReal();
7751 Result.getComplexIntImag() += RHS.getComplexIntImag();
7752 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007753 break;
John McCalle3027922010-08-25 11:45:40 +00007754 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007755 if (Result.isComplexFloat()) {
7756 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7757 APFloat::rmNearestTiesToEven);
7758 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7759 APFloat::rmNearestTiesToEven);
7760 } else {
7761 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7762 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7763 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007764 break;
John McCalle3027922010-08-25 11:45:40 +00007765 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007766 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007767 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007768 APFloat &LHS_r = LHS.getComplexFloatReal();
7769 APFloat &LHS_i = LHS.getComplexFloatImag();
7770 APFloat &RHS_r = RHS.getComplexFloatReal();
7771 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007772
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007773 APFloat Tmp = LHS_r;
7774 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7775 Result.getComplexFloatReal() = Tmp;
7776 Tmp = LHS_i;
7777 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7778 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7779
7780 Tmp = LHS_r;
7781 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7782 Result.getComplexFloatImag() = Tmp;
7783 Tmp = LHS_i;
7784 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7785 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7786 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007787 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007788 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007789 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7790 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007791 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007792 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7793 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7794 }
7795 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007796 case BO_Div:
7797 if (Result.isComplexFloat()) {
7798 ComplexValue LHS = Result;
7799 APFloat &LHS_r = LHS.getComplexFloatReal();
7800 APFloat &LHS_i = LHS.getComplexFloatImag();
7801 APFloat &RHS_r = RHS.getComplexFloatReal();
7802 APFloat &RHS_i = RHS.getComplexFloatImag();
7803 APFloat &Res_r = Result.getComplexFloatReal();
7804 APFloat &Res_i = Result.getComplexFloatImag();
7805
7806 APFloat Den = RHS_r;
7807 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7808 APFloat Tmp = RHS_i;
7809 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7810 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7811
7812 Res_r = LHS_r;
7813 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7814 Tmp = LHS_i;
7815 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7816 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7817 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7818
7819 Res_i = LHS_i;
7820 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7821 Tmp = LHS_r;
7822 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7823 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7824 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7825 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007826 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7827 return Error(E, diag::note_expr_divide_by_zero);
7828
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007829 ComplexValue LHS = Result;
7830 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7831 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7832 Result.getComplexIntReal() =
7833 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7834 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7835 Result.getComplexIntImag() =
7836 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7837 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7838 }
7839 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007840 }
7841
John McCall93d91dc2010-05-07 17:22:02 +00007842 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007843}
7844
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007845bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7846 // Get the operand value into 'Result'.
7847 if (!Visit(E->getSubExpr()))
7848 return false;
7849
7850 switch (E->getOpcode()) {
7851 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007852 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007853 case UO_Extension:
7854 return true;
7855 case UO_Plus:
7856 // The result is always just the subexpr.
7857 return true;
7858 case UO_Minus:
7859 if (Result.isComplexFloat()) {
7860 Result.getComplexFloatReal().changeSign();
7861 Result.getComplexFloatImag().changeSign();
7862 }
7863 else {
7864 Result.getComplexIntReal() = -Result.getComplexIntReal();
7865 Result.getComplexIntImag() = -Result.getComplexIntImag();
7866 }
7867 return true;
7868 case UO_Not:
7869 if (Result.isComplexFloat())
7870 Result.getComplexFloatImag().changeSign();
7871 else
7872 Result.getComplexIntImag() = -Result.getComplexIntImag();
7873 return true;
7874 }
7875}
7876
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007877bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7878 if (E->getNumInits() == 2) {
7879 if (E->getType()->isComplexType()) {
7880 Result.makeComplexFloat();
7881 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7882 return false;
7883 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7884 return false;
7885 } else {
7886 Result.makeComplexInt();
7887 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7888 return false;
7889 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7890 return false;
7891 }
7892 return true;
7893 }
7894 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7895}
7896
Anders Carlsson537969c2008-11-16 20:27:53 +00007897//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007898// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7899// implicit conversion.
7900//===----------------------------------------------------------------------===//
7901
7902namespace {
7903class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007904 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007905 APValue &Result;
7906public:
7907 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7908 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7909
7910 bool Success(const APValue &V, const Expr *E) {
7911 Result = V;
7912 return true;
7913 }
7914
7915 bool ZeroInitialization(const Expr *E) {
7916 ImplicitValueInitExpr VIE(
7917 E->getType()->castAs<AtomicType>()->getValueType());
7918 return Evaluate(Result, Info, &VIE);
7919 }
7920
7921 bool VisitCastExpr(const CastExpr *E) {
7922 switch (E->getCastKind()) {
7923 default:
7924 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7925 case CK_NonAtomicToAtomic:
7926 return Evaluate(Result, Info, E->getSubExpr());
7927 }
7928 }
7929};
7930} // end anonymous namespace
7931
7932static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7933 assert(E->isRValue() && E->getType()->isAtomicType());
7934 return AtomicExprEvaluator(Info, Result).Visit(E);
7935}
7936
7937//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007938// Void expression evaluation, primarily for a cast to void on the LHS of a
7939// comma operator
7940//===----------------------------------------------------------------------===//
7941
7942namespace {
7943class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007944 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007945public:
7946 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7947
Richard Smith2e312c82012-03-03 22:46:17 +00007948 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007949
7950 bool VisitCastExpr(const CastExpr *E) {
7951 switch (E->getCastKind()) {
7952 default:
7953 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7954 case CK_ToVoid:
7955 VisitIgnoredValue(E->getSubExpr());
7956 return true;
7957 }
7958 }
Hal Finkela8443c32014-07-17 14:49:58 +00007959
7960 bool VisitCallExpr(const CallExpr *E) {
7961 switch (E->getBuiltinCallee()) {
7962 default:
7963 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7964 case Builtin::BI__assume:
7965 // The argument is not evaluated!
7966 return true;
7967 }
7968 }
Richard Smith42d3af92011-12-07 00:43:50 +00007969};
7970} // end anonymous namespace
7971
7972static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7973 assert(E->isRValue() && E->getType()->isVoidType());
7974 return VoidExprEvaluator(Info).Visit(E);
7975}
7976
7977//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007978// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007979//===----------------------------------------------------------------------===//
7980
Richard Smith2e312c82012-03-03 22:46:17 +00007981static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007982 // In C, function designators are not lvalues, but we evaluate them as if they
7983 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007984 QualType T = E->getType();
7985 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007986 LValue LV;
7987 if (!EvaluateLValue(E, LV, Info))
7988 return false;
7989 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007990 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007991 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007992 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007993 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007994 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007995 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007996 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007997 LValue LV;
7998 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007999 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008000 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008001 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008002 llvm::APFloat F(0.0);
8003 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008004 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008005 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008006 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008007 ComplexValue C;
8008 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008009 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008010 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008011 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008012 MemberPtr P;
8013 if (!EvaluateMemberPointer(E, P, Info))
8014 return false;
8015 P.moveInto(Result);
8016 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008017 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008018 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008019 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008020 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8021 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008022 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008023 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008024 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008025 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008026 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008027 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8028 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008029 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008030 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008031 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008032 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008033 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008034 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008035 if (!EvaluateVoid(E, Info))
8036 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008037 } else if (T->isAtomicType()) {
8038 if (!EvaluateAtomic(E, Result, Info))
8039 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008040 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008041 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008042 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008043 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008044 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008045 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008046 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008047
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008048 return true;
8049}
8050
Richard Smithb228a862012-02-15 02:18:13 +00008051/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8052/// cases, the in-place evaluation is essential, since later initializers for
8053/// an object can indirectly refer to subobjects which were initialized earlier.
8054static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008055 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008056 assert(!E->isValueDependent());
8057
Richard Smith7525ff62013-05-09 07:14:00 +00008058 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008059 return false;
8060
8061 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008062 // Evaluate arrays and record types in-place, so that later initializers can
8063 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008064 if (E->getType()->isArrayType())
8065 return EvaluateArray(E, This, Result, Info);
8066 else if (E->getType()->isRecordType())
8067 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008068 }
8069
8070 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008071 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008072}
8073
Richard Smithf57d8cb2011-12-09 22:58:01 +00008074/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8075/// lvalue-to-rvalue cast if it is an lvalue.
8076static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008077 if (E->getType().isNull())
8078 return false;
8079
Richard Smithfddd3842011-12-30 21:15:51 +00008080 if (!CheckLiteralType(Info, E))
8081 return false;
8082
Richard Smith2e312c82012-03-03 22:46:17 +00008083 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008084 return false;
8085
8086 if (E->isGLValue()) {
8087 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008088 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008089 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008090 return false;
8091 }
8092
Richard Smith2e312c82012-03-03 22:46:17 +00008093 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008094 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008095}
Richard Smith11562c52011-10-28 17:51:58 +00008096
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008097static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8098 const ASTContext &Ctx, bool &IsConst) {
8099 // Fast-path evaluations of integer literals, since we sometimes see files
8100 // containing vast quantities of these.
8101 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8102 Result.Val = APValue(APSInt(L->getValue(),
8103 L->getType()->isUnsignedIntegerType()));
8104 IsConst = true;
8105 return true;
8106 }
James Dennett0492ef02014-03-14 17:44:10 +00008107
8108 // This case should be rare, but we need to check it before we check on
8109 // the type below.
8110 if (Exp->getType().isNull()) {
8111 IsConst = false;
8112 return true;
8113 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008114
8115 // FIXME: Evaluating values of large array and record types can cause
8116 // performance problems. Only do so in C++11 for now.
8117 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8118 Exp->getType()->isRecordType()) &&
8119 !Ctx.getLangOpts().CPlusPlus11) {
8120 IsConst = false;
8121 return true;
8122 }
8123 return false;
8124}
8125
8126
Richard Smith7b553f12011-10-29 00:50:52 +00008127/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008128/// any crazy technique (that has nothing to do with language standards) that
8129/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008130/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8131/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008132bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008133 bool IsConst;
8134 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8135 return IsConst;
8136
Richard Smith6d4c6582013-11-05 22:18:15 +00008137 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008138 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008139}
8140
Jay Foad39c79802011-01-12 09:06:06 +00008141bool Expr::EvaluateAsBooleanCondition(bool &Result,
8142 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008143 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008144 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008145 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008146}
8147
Richard Smith5fab0c92011-12-28 19:48:30 +00008148bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8149 SideEffectsKind AllowSideEffects) const {
8150 if (!getType()->isIntegralOrEnumerationType())
8151 return false;
8152
Richard Smith11562c52011-10-28 17:51:58 +00008153 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008154 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8155 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008156 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008157
Richard Smith11562c52011-10-28 17:51:58 +00008158 Result = ExprResult.Val.getInt();
8159 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008160}
8161
Jay Foad39c79802011-01-12 09:06:06 +00008162bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008163 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008164
John McCall45d55e42010-05-07 21:00:08 +00008165 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008166 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8167 !CheckLValueConstantExpression(Info, getExprLoc(),
8168 Ctx.getLValueReferenceType(getType()), LV))
8169 return false;
8170
Richard Smith2e312c82012-03-03 22:46:17 +00008171 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008172 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008173}
8174
Richard Smithd0b4dd62011-12-19 06:19:21 +00008175bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8176 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008177 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008178 // FIXME: Evaluating initializers for large array and record types can cause
8179 // performance problems. Only do so in C++11 for now.
8180 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008181 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008182 return false;
8183
Richard Smithd0b4dd62011-12-19 06:19:21 +00008184 Expr::EvalStatus EStatus;
8185 EStatus.Diag = &Notes;
8186
Richard Smith6d4c6582013-11-05 22:18:15 +00008187 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008188 InitInfo.setEvaluatingDecl(VD, Value);
8189
8190 LValue LVal;
8191 LVal.set(VD);
8192
Richard Smithfddd3842011-12-30 21:15:51 +00008193 // C++11 [basic.start.init]p2:
8194 // Variables with static storage duration or thread storage duration shall be
8195 // zero-initialized before any other initialization takes place.
8196 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008197 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008198 !VD->getType()->isReferenceType()) {
8199 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008200 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008201 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008202 return false;
8203 }
8204
Richard Smith7525ff62013-05-09 07:14:00 +00008205 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8206 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008207 EStatus.HasSideEffects)
8208 return false;
8209
8210 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8211 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008212}
8213
Richard Smith7b553f12011-10-29 00:50:52 +00008214/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8215/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008216bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008217 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008218 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008219}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008220
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008221APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008222 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008223 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008224 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008225 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008226 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008227 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008228 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008229
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008230 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008231}
John McCall864e3962010-05-07 05:32:02 +00008232
Richard Smithe9ff7702013-11-05 22:23:30 +00008233void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008234 bool IsConst;
8235 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008236 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008237 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008238 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8239 }
8240}
8241
Richard Smithe6c01442013-06-05 00:46:14 +00008242bool Expr::EvalResult::isGlobalLValue() const {
8243 assert(Val.isLValue());
8244 return IsGlobalLValue(Val.getLValueBase());
8245}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008246
8247
John McCall864e3962010-05-07 05:32:02 +00008248/// isIntegerConstantExpr - this recursive routine will test if an expression is
8249/// an integer constant expression.
8250
8251/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8252/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008253
8254// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008255// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8256// and a (possibly null) SourceLocation indicating the location of the problem.
8257//
John McCall864e3962010-05-07 05:32:02 +00008258// Note that to reduce code duplication, this helper does no evaluation
8259// itself; the caller checks whether the expression is evaluatable, and
8260// in the rare cases where CheckICE actually cares about the evaluated
8261// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008262
Dan Gohman28ade552010-07-26 21:25:24 +00008263namespace {
8264
Richard Smith9e575da2012-12-28 13:25:52 +00008265enum ICEKind {
8266 /// This expression is an ICE.
8267 IK_ICE,
8268 /// This expression is not an ICE, but if it isn't evaluated, it's
8269 /// a legal subexpression for an ICE. This return value is used to handle
8270 /// the comma operator in C99 mode, and non-constant subexpressions.
8271 IK_ICEIfUnevaluated,
8272 /// This expression is not an ICE, and is not a legal subexpression for one.
8273 IK_NotICE
8274};
8275
John McCall864e3962010-05-07 05:32:02 +00008276struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008277 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008278 SourceLocation Loc;
8279
Richard Smith9e575da2012-12-28 13:25:52 +00008280 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008281};
8282
Dan Gohman28ade552010-07-26 21:25:24 +00008283}
8284
Richard Smith9e575da2012-12-28 13:25:52 +00008285static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8286
8287static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008288
Craig Toppera31a8822013-08-22 07:09:37 +00008289static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008290 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008291 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008292 !EVResult.Val.isInt())
8293 return ICEDiag(IK_NotICE, E->getLocStart());
8294
John McCall864e3962010-05-07 05:32:02 +00008295 return NoDiag();
8296}
8297
Craig Toppera31a8822013-08-22 07:09:37 +00008298static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008299 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008300 if (!E->getType()->isIntegralOrEnumerationType())
8301 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008302
8303 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008304#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008305#define STMT(Node, Base) case Expr::Node##Class:
8306#define EXPR(Node, Base)
8307#include "clang/AST/StmtNodes.inc"
8308 case Expr::PredefinedExprClass:
8309 case Expr::FloatingLiteralClass:
8310 case Expr::ImaginaryLiteralClass:
8311 case Expr::StringLiteralClass:
8312 case Expr::ArraySubscriptExprClass:
8313 case Expr::MemberExprClass:
8314 case Expr::CompoundAssignOperatorClass:
8315 case Expr::CompoundLiteralExprClass:
8316 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008317 case Expr::DesignatedInitExprClass:
8318 case Expr::ImplicitValueInitExprClass:
8319 case Expr::ParenListExprClass:
8320 case Expr::VAArgExprClass:
8321 case Expr::AddrLabelExprClass:
8322 case Expr::StmtExprClass:
8323 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008324 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008325 case Expr::CXXDynamicCastExprClass:
8326 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008327 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008328 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008329 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008330 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008331 case Expr::CXXThisExprClass:
8332 case Expr::CXXThrowExprClass:
8333 case Expr::CXXNewExprClass:
8334 case Expr::CXXDeleteExprClass:
8335 case Expr::CXXPseudoDestructorExprClass:
8336 case Expr::UnresolvedLookupExprClass:
8337 case Expr::DependentScopeDeclRefExprClass:
8338 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008339 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008340 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008341 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008342 case Expr::CXXTemporaryObjectExprClass:
8343 case Expr::CXXUnresolvedConstructExprClass:
8344 case Expr::CXXDependentScopeMemberExprClass:
8345 case Expr::UnresolvedMemberExprClass:
8346 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008347 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008348 case Expr::ObjCArrayLiteralClass:
8349 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008350 case Expr::ObjCEncodeExprClass:
8351 case Expr::ObjCMessageExprClass:
8352 case Expr::ObjCSelectorExprClass:
8353 case Expr::ObjCProtocolExprClass:
8354 case Expr::ObjCIvarRefExprClass:
8355 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008356 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008357 case Expr::ObjCIsaExprClass:
8358 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008359 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008360 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008361 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008362 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008363 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008364 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008365 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008366 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008367 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008368 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008369 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008370 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008371 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008372 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008373
Richard Smithf137f932014-01-25 20:50:08 +00008374 case Expr::InitListExprClass: {
8375 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8376 // form "T x = { a };" is equivalent to "T x = a;".
8377 // Unless we're initializing a reference, T is a scalar as it is known to be
8378 // of integral or enumeration type.
8379 if (E->isRValue())
8380 if (cast<InitListExpr>(E)->getNumInits() == 1)
8381 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8382 return ICEDiag(IK_NotICE, E->getLocStart());
8383 }
8384
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008385 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008386 case Expr::GNUNullExprClass:
8387 // GCC considers the GNU __null value to be an integral constant expression.
8388 return NoDiag();
8389
John McCall7c454bb2011-07-15 05:09:51 +00008390 case Expr::SubstNonTypeTemplateParmExprClass:
8391 return
8392 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8393
John McCall864e3962010-05-07 05:32:02 +00008394 case Expr::ParenExprClass:
8395 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008396 case Expr::GenericSelectionExprClass:
8397 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008398 case Expr::IntegerLiteralClass:
8399 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008400 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008401 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008402 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008403 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008404 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008405 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008406 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008407 return NoDiag();
8408 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008409 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008410 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8411 // constant expressions, but they can never be ICEs because an ICE cannot
8412 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008413 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008414 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008415 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008416 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008417 }
Richard Smith6365c912012-02-24 22:12:32 +00008418 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008419 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8420 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008421 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008422 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008423 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008424 // Parameter variables are never constants. Without this check,
8425 // getAnyInitializer() can find a default argument, which leads
8426 // to chaos.
8427 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008428 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008429
8430 // C++ 7.1.5.1p2
8431 // A variable of non-volatile const-qualified integral or enumeration
8432 // type initialized by an ICE can be used in ICEs.
8433 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008434 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008435 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008436
Richard Smithd0b4dd62011-12-19 06:19:21 +00008437 const VarDecl *VD;
8438 // Look for a declaration of this variable that has an initializer, and
8439 // check whether it is an ICE.
8440 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8441 return NoDiag();
8442 else
Richard Smith9e575da2012-12-28 13:25:52 +00008443 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008444 }
8445 }
Richard Smith9e575da2012-12-28 13:25:52 +00008446 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008447 }
John McCall864e3962010-05-07 05:32:02 +00008448 case Expr::UnaryOperatorClass: {
8449 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8450 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008451 case UO_PostInc:
8452 case UO_PostDec:
8453 case UO_PreInc:
8454 case UO_PreDec:
8455 case UO_AddrOf:
8456 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008457 // C99 6.6/3 allows increment and decrement within unevaluated
8458 // subexpressions of constant expressions, but they can never be ICEs
8459 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008460 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008461 case UO_Extension:
8462 case UO_LNot:
8463 case UO_Plus:
8464 case UO_Minus:
8465 case UO_Not:
8466 case UO_Real:
8467 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008468 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008469 }
Richard Smith9e575da2012-12-28 13:25:52 +00008470
John McCall864e3962010-05-07 05:32:02 +00008471 // OffsetOf falls through here.
8472 }
8473 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008474 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8475 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8476 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8477 // compliance: we should warn earlier for offsetof expressions with
8478 // array subscripts that aren't ICEs, and if the array subscripts
8479 // are ICEs, the value of the offsetof must be an integer constant.
8480 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008481 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008482 case Expr::UnaryExprOrTypeTraitExprClass: {
8483 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8484 if ((Exp->getKind() == UETT_SizeOf) &&
8485 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008486 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008487 return NoDiag();
8488 }
8489 case Expr::BinaryOperatorClass: {
8490 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8491 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008492 case BO_PtrMemD:
8493 case BO_PtrMemI:
8494 case BO_Assign:
8495 case BO_MulAssign:
8496 case BO_DivAssign:
8497 case BO_RemAssign:
8498 case BO_AddAssign:
8499 case BO_SubAssign:
8500 case BO_ShlAssign:
8501 case BO_ShrAssign:
8502 case BO_AndAssign:
8503 case BO_XorAssign:
8504 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008505 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8506 // constant expressions, but they can never be ICEs because an ICE cannot
8507 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008508 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008509
John McCalle3027922010-08-25 11:45:40 +00008510 case BO_Mul:
8511 case BO_Div:
8512 case BO_Rem:
8513 case BO_Add:
8514 case BO_Sub:
8515 case BO_Shl:
8516 case BO_Shr:
8517 case BO_LT:
8518 case BO_GT:
8519 case BO_LE:
8520 case BO_GE:
8521 case BO_EQ:
8522 case BO_NE:
8523 case BO_And:
8524 case BO_Xor:
8525 case BO_Or:
8526 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008527 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8528 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008529 if (Exp->getOpcode() == BO_Div ||
8530 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008531 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008532 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008533 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008534 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008535 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008536 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008537 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008538 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008539 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008540 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008541 }
8542 }
8543 }
John McCalle3027922010-08-25 11:45:40 +00008544 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008545 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008546 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8547 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008548 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8549 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008550 } else {
8551 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008552 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008553 }
8554 }
Richard Smith9e575da2012-12-28 13:25:52 +00008555 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008556 }
John McCalle3027922010-08-25 11:45:40 +00008557 case BO_LAnd:
8558 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008559 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8560 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008561 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008562 // Rare case where the RHS has a comma "side-effect"; we need
8563 // to actually check the condition to see whether the side
8564 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008565 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008566 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008567 return RHSResult;
8568 return NoDiag();
8569 }
8570
Richard Smith9e575da2012-12-28 13:25:52 +00008571 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008572 }
8573 }
8574 }
8575 case Expr::ImplicitCastExprClass:
8576 case Expr::CStyleCastExprClass:
8577 case Expr::CXXFunctionalCastExprClass:
8578 case Expr::CXXStaticCastExprClass:
8579 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008580 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008581 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008582 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008583 if (isa<ExplicitCastExpr>(E)) {
8584 if (const FloatingLiteral *FL
8585 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8586 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8587 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8588 APSInt IgnoredVal(DestWidth, !DestSigned);
8589 bool Ignored;
8590 // If the value does not fit in the destination type, the behavior is
8591 // undefined, so we are not required to treat it as a constant
8592 // expression.
8593 if (FL->getValue().convertToInteger(IgnoredVal,
8594 llvm::APFloat::rmTowardZero,
8595 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008596 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008597 return NoDiag();
8598 }
8599 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008600 switch (cast<CastExpr>(E)->getCastKind()) {
8601 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008602 case CK_AtomicToNonAtomic:
8603 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008604 case CK_NoOp:
8605 case CK_IntegralToBoolean:
8606 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008607 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008608 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008609 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008610 }
John McCall864e3962010-05-07 05:32:02 +00008611 }
John McCallc07a0c72011-02-17 10:25:35 +00008612 case Expr::BinaryConditionalOperatorClass: {
8613 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8614 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008615 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008616 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008617 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8618 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8619 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008620 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008621 return FalseResult;
8622 }
John McCall864e3962010-05-07 05:32:02 +00008623 case Expr::ConditionalOperatorClass: {
8624 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8625 // If the condition (ignoring parens) is a __builtin_constant_p call,
8626 // then only the true side is actually considered in an integer constant
8627 // expression, and it is fully evaluated. This is an important GNU
8628 // extension. See GCC PR38377 for discussion.
8629 if (const CallExpr *CallCE
8630 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008631 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008632 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008633 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008634 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008635 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008636
Richard Smithf57d8cb2011-12-09 22:58:01 +00008637 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8638 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008639
Richard Smith9e575da2012-12-28 13:25:52 +00008640 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008641 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008642 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008643 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008644 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008645 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008646 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008647 return NoDiag();
8648 // Rare case where the diagnostics depend on which side is evaluated
8649 // Note that if we get here, CondResult is 0, and at least one of
8650 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008651 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008652 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008653 return TrueResult;
8654 }
8655 case Expr::CXXDefaultArgExprClass:
8656 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008657 case Expr::CXXDefaultInitExprClass:
8658 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008659 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008660 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008661 }
8662 }
8663
David Blaikiee4d798f2012-01-20 21:50:17 +00008664 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008665}
8666
Richard Smithf57d8cb2011-12-09 22:58:01 +00008667/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008668static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008669 const Expr *E,
8670 llvm::APSInt *Value,
8671 SourceLocation *Loc) {
8672 if (!E->getType()->isIntegralOrEnumerationType()) {
8673 if (Loc) *Loc = E->getExprLoc();
8674 return false;
8675 }
8676
Richard Smith66e05fe2012-01-18 05:21:49 +00008677 APValue Result;
8678 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008679 return false;
8680
Richard Smith66e05fe2012-01-18 05:21:49 +00008681 assert(Result.isInt() && "pointer cast to int is not an ICE");
8682 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008683 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008684}
8685
Craig Toppera31a8822013-08-22 07:09:37 +00008686bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8687 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008688 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008689 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008690
Richard Smith9e575da2012-12-28 13:25:52 +00008691 ICEDiag D = CheckICE(this, Ctx);
8692 if (D.Kind != IK_ICE) {
8693 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008694 return false;
8695 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008696 return true;
8697}
8698
Craig Toppera31a8822013-08-22 07:09:37 +00008699bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008700 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008701 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008702 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8703
8704 if (!isIntegerConstantExpr(Ctx, Loc))
8705 return false;
8706 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008707 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008708 return true;
8709}
Richard Smith66e05fe2012-01-18 05:21:49 +00008710
Craig Toppera31a8822013-08-22 07:09:37 +00008711bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008712 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008713}
8714
Craig Toppera31a8822013-08-22 07:09:37 +00008715bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008716 SourceLocation *Loc) const {
8717 // We support this checking in C++98 mode in order to diagnose compatibility
8718 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008719 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008720
Richard Smith98a0a492012-02-14 21:38:30 +00008721 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008722 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008723 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008724 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008725 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008726
8727 APValue Scratch;
8728 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8729
8730 if (!Diags.empty()) {
8731 IsConstExpr = false;
8732 if (Loc) *Loc = Diags[0].first;
8733 } else if (!IsConstExpr) {
8734 // FIXME: This shouldn't happen.
8735 if (Loc) *Loc = getExprLoc();
8736 }
8737
8738 return IsConstExpr;
8739}
Richard Smith253c2a32012-01-27 01:14:48 +00008740
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008741bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8742 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00008743 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008744 Expr::EvalStatus Status;
8745 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8746
8747 ArgVector ArgValues(Args.size());
8748 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8749 I != E; ++I) {
8750 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8751 // If evaluation fails, throw away the argument entirely.
8752 ArgValues[I - Args.begin()] = APValue();
8753 if (Info.EvalStatus.HasSideEffects)
8754 return false;
8755 }
8756
8757 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00008758 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008759 ArgValues.data());
8760 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8761}
8762
Richard Smith253c2a32012-01-27 01:14:48 +00008763bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008764 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008765 PartialDiagnosticAt> &Diags) {
8766 // FIXME: It would be useful to check constexpr function templates, but at the
8767 // moment the constant expression evaluator cannot cope with the non-rigorous
8768 // ASTs which we build for dependent expressions.
8769 if (FD->isDependentContext())
8770 return true;
8771
8772 Expr::EvalStatus Status;
8773 Status.Diag = &Diags;
8774
Richard Smith6d4c6582013-11-05 22:18:15 +00008775 EvalInfo Info(FD->getASTContext(), Status,
8776 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008777
8778 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00008779 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00008780
Richard Smith7525ff62013-05-09 07:14:00 +00008781 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008782 // is a temporary being used as the 'this' pointer.
8783 LValue This;
8784 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008785 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008786
Richard Smith253c2a32012-01-27 01:14:48 +00008787 ArrayRef<const Expr*> Args;
8788
8789 SourceLocation Loc = FD->getLocation();
8790
Richard Smith2e312c82012-03-03 22:46:17 +00008791 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008792 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8793 // Evaluate the call as a constant initializer, to allow the construction
8794 // of objects of non-literal types.
8795 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008796 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008797 } else
Craig Topper36250ad2014-05-12 05:36:57 +00008798 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00008799 Args, FD->getBody(), Info, Scratch);
8800
8801 return Diags.empty();
8802}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008803
8804bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8805 const FunctionDecl *FD,
8806 SmallVectorImpl<
8807 PartialDiagnosticAt> &Diags) {
8808 Expr::EvalStatus Status;
8809 Status.Diag = &Diags;
8810
8811 EvalInfo Info(FD->getASTContext(), Status,
8812 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8813
8814 // Fabricate a call stack frame to give the arguments a plausible cover story.
8815 ArrayRef<const Expr*> Args;
8816 ArgVector ArgValues(0);
8817 bool Success = EvaluateArgs(Args, ArgValues, Info);
8818 (void)Success;
8819 assert(Success &&
8820 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00008821 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008822
8823 APValue ResultScratch;
8824 Evaluate(ResultScratch, Info, E);
8825 return Diags.empty();
8826}