blob: c57a802512be8ed21e9d0d969905149d09517d45 [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 {
204 if (IsOnePastTheEnd)
205 return true;
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208 return true;
209 return false;
210 }
211
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
214 if (Invalid)
215 return false;
216 return !isOnePastTheEnd();
217 }
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000227
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000240
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
246 }
Richard Smith96e0c102011-11-04 02:25:55 +0000247 }
Richard Smith66c96992012-02-18 22:04:06 +0000248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
250 PathEntry Entry;
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
253
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
259 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith96e0c102011-11-04 02:25:55 +0000270 return;
271 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
279 else if (N != 0) {
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 }
Richard Smith96e0c102011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smith254a73d2011-10-28 22:34:42 +0000286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
288 EvalInfo &Info;
289
290 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000292
Richard Smithf6f003a2011-12-16 19:06:07 +0000293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
295
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
298
Richard Smithb228a862012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smithd62306a2011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000305 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000308
Eli Friedman4830ec82012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
314 MapTy Temporaries;
315
Richard Smithf6f003a2011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000320
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000323 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000324 }
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000326 };
327
Richard Smith852c9db2013-04-20 22:23:05 +0000328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
330 public:
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
333 if (Enable)
334 Frame.This = NewThis;
335 }
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
338 }
339 private:
340 CallStackFrame &Frame;
341 const LValue *OldThis;
342 };
343
Richard Smith92b1ce02011-12-12 09:28:41 +0000344 /// A partial diagnostic which we might know in advance that we are not going
345 /// to emit.
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
348
349 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
351 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000352
353 template<typename T>
354 OptionalDiagnostic &operator<<(const T &v) {
355 if (Diag)
356 *Diag << v;
357 return *this;
358 }
Richard Smithfe800032012-01-31 04:08:20 +0000359
360 OptionalDiagnostic &operator<<(const APSInt &I) {
361 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000362 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000363 I.toString(Buffer);
364 *Diag << StringRef(Buffer.data(), Buffer.size());
365 }
366 return *this;
367 }
368
369 OptionalDiagnostic &operator<<(const APFloat &F) {
370 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000371 // FIXME: Force the precision of the source value down so we don't
372 // print digits which are usually useless (we don't really care here if
373 // we truncate a digit by accident in edge cases). Ideally,
374 // APFloat::toString would automatically print the shortest
375 // representation which rounds to the correct value, but it's a bit
376 // tricky to implement.
377 unsigned precision =
378 llvm::APFloat::semanticsPrecision(F.getSemantics());
379 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000380 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000381 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000382 *Diag << StringRef(Buffer.data(), Buffer.size());
383 }
384 return *this;
385 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000386 };
387
Richard Smith08d6a2c2013-07-24 07:11:57 +0000388 /// A cleanup, and a flag indicating whether it is lifetime-extended.
389 class Cleanup {
390 llvm::PointerIntPair<APValue*, 1, bool> Value;
391
392 public:
393 Cleanup(APValue *Val, bool IsLifetimeExtended)
394 : Value(Val, IsLifetimeExtended) {}
395
396 bool isLifetimeExtended() const { return Value.getInt(); }
397 void endLifetime() {
398 *Value.getPointer() = APValue();
399 }
400 };
401
Richard Smithb228a862012-02-15 02:18:13 +0000402 /// EvalInfo - This is a private struct used by the evaluator to capture
403 /// information about a subexpression as it is folded. It retains information
404 /// about the AST context, but also maintains information about the folded
405 /// expression.
406 ///
407 /// If an expression could be evaluated, it is still possible it is not a C
408 /// "integer constant expression" or constant expression. If not, this struct
409 /// captures information about how and why not.
410 ///
411 /// One bit of information passed *into* the request for constant folding
412 /// indicates whether the subexpression is "evaluated" or not according to C
413 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
414 /// evaluate the expression regardless of what the RHS is, but C only allows
415 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000416 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000417 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000418
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 /// EvalStatus - Contains information about the evaluation.
420 Expr::EvalStatus &EvalStatus;
421
422 /// CurrentCall - The top of the constexpr call stack.
423 CallStackFrame *CurrentCall;
424
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000425 /// CallStackDepth - The number of calls in the call stack right now.
426 unsigned CallStackDepth;
427
Richard Smithb228a862012-02-15 02:18:13 +0000428 /// NextCallIndex - The next call index to assign.
429 unsigned NextCallIndex;
430
Richard Smitha3d3bd22013-05-08 02:12:03 +0000431 /// StepsLeft - The remaining number of evaluation steps we're permitted
432 /// to perform. This is essentially a limit for the number of statements
433 /// we will evaluate.
434 unsigned StepsLeft;
435
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000437 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000438 CallStackFrame BottomFrame;
439
Richard Smith08d6a2c2013-07-24 07:11:57 +0000440 /// A stack of values whose lifetimes end at the end of some surrounding
441 /// evaluation frame.
442 llvm::SmallVector<Cleanup, 16> CleanupStack;
443
Richard Smithd62306a2011-11-10 06:34:14 +0000444 /// EvaluatingDecl - This is the declaration whose initializer is being
445 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000446 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000447
448 /// EvaluatingDeclValue - This is the value being constructed for the
449 /// declaration whose initializer is being evaluated, if any.
450 APValue *EvaluatingDeclValue;
451
Richard Smith357362d2011-12-13 06:39:58 +0000452 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
453 /// notes attached to it will also be stored, otherwise they will not be.
454 bool HasActiveDiagnostic;
455
Richard Smith6d4c6582013-11-05 22:18:15 +0000456 enum EvaluationMode {
457 /// Evaluate as a constant expression. Stop if we find that the expression
458 /// is not a constant expression.
459 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460
Richard Smith6d4c6582013-11-05 22:18:15 +0000461 /// Evaluate as a potential constant expression. Keep going if we hit a
462 /// construct that we can't evaluate yet (because we don't yet know the
463 /// value of something) but stop if we hit something that could never be
464 /// a constant expression.
465 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000466
Richard Smith6d4c6582013-11-05 22:18:15 +0000467 /// Fold the expression to a constant. Stop if we hit a side-effect that
468 /// we can't model.
469 EM_ConstantFold,
470
471 /// Evaluate the expression looking for integer overflow and similar
472 /// issues. Don't worry about side-effects, and try to visit all
473 /// subexpressions.
474 EM_EvaluateForOverflow,
475
476 /// Evaluate in any way we know how. Don't worry about side-effects that
477 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000478 EM_IgnoreSideEffects,
479
480 /// Evaluate as a constant expression. Stop if we find that the expression
481 /// is not a constant expression. Some expressions can be retried in the
482 /// optimizer if we don't constant fold them here, but in an unevaluated
483 /// context we try to fold them immediately since the optimizer never
484 /// gets a chance to look at it.
485 EM_ConstantExpressionUnevaluated,
486
487 /// Evaluate as a potential constant expression. Keep going if we hit a
488 /// construct that we can't evaluate yet (because we don't yet know the
489 /// value of something) but stop if we hit something that could never be
490 /// a constant expression. Some expressions can be retried in the
491 /// optimizer if we don't constant fold them here, but in an unevaluated
492 /// context we try to fold them immediately since the optimizer never
493 /// gets a chance to look at it.
494 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000495 } EvalMode;
496
497 /// Are we checking whether the expression is a potential constant
498 /// expression?
499 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000500 return EvalMode == EM_PotentialConstantExpression ||
501 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000502 }
503
504 /// Are we checking an expression for overflow?
505 // FIXME: We should check for any kind of undefined or suspicious behavior
506 // in such constructs, not just overflow.
507 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
508
509 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000510 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000511 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000512 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000513 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
514 EvaluatingDecl((const ValueDecl *)nullptr),
515 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
516 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000517
Richard Smith7525ff62013-05-09 07:14:00 +0000518 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
519 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000520 EvaluatingDeclValue = &Value;
521 }
522
David Blaikiebbafb8a2012-03-11 07:00:24 +0000523 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000524
Richard Smith357362d2011-12-13 06:39:58 +0000525 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000526 // Don't perform any constexpr calls (other than the call we're checking)
527 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000528 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000529 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000530 if (NextCallIndex == 0) {
531 // NextCallIndex has wrapped around.
532 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
533 return false;
534 }
Richard Smith357362d2011-12-13 06:39:58 +0000535 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
536 return true;
537 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
538 << getLangOpts().ConstexprCallDepth;
539 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000540 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000541
Richard Smithb228a862012-02-15 02:18:13 +0000542 CallStackFrame *getCallFrame(unsigned CallIndex) {
543 assert(CallIndex && "no call index in getCallFrame");
544 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
545 // be null in this loop.
546 CallStackFrame *Frame = CurrentCall;
547 while (Frame->Index > CallIndex)
548 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000549 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000550 }
551
Richard Smitha3d3bd22013-05-08 02:12:03 +0000552 bool nextStep(const Stmt *S) {
553 if (!StepsLeft) {
554 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
555 return false;
556 }
557 --StepsLeft;
558 return true;
559 }
560
Richard Smith357362d2011-12-13 06:39:58 +0000561 private:
562 /// Add a diagnostic to the diagnostics list.
563 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
564 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
565 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
566 return EvalStatus.Diag->back().second;
567 }
568
Richard Smithf6f003a2011-12-16 19:06:07 +0000569 /// Add notes containing a call stack to the current point of evaluation.
570 void addCallStack(unsigned Limit);
571
Richard Smith357362d2011-12-13 06:39:58 +0000572 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000573 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000574 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
575 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000576 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000577 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000578 // If we have a prior diagnostic, it will be noting that the expression
579 // isn't a constant expression. This diagnostic is more important,
580 // unless we require this evaluation to produce a constant expression.
581 //
582 // FIXME: We might want to show both diagnostics to the user in
583 // EM_ConstantFold mode.
584 if (!EvalStatus.Diag->empty()) {
585 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000586 case EM_ConstantFold:
587 case EM_IgnoreSideEffects:
588 case EM_EvaluateForOverflow:
589 if (!EvalStatus.HasSideEffects)
590 break;
591 // We've had side-effects; we want the diagnostic from them, not
592 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000593 case EM_ConstantExpression:
594 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000595 case EM_ConstantExpressionUnevaluated:
596 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000597 HasActiveDiagnostic = false;
598 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000599 }
600 }
601
Richard Smithf6f003a2011-12-16 19:06:07 +0000602 unsigned CallStackNotes = CallStackDepth - 1;
603 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
604 if (Limit)
605 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000606 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000607 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000608
Richard Smith357362d2011-12-13 06:39:58 +0000609 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000610 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000611 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
612 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000613 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000614 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 }
Richard Smith357362d2011-12-13 06:39:58 +0000617 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000618 return OptionalDiagnostic();
619 }
620
Richard Smithce1ec5e2012-03-15 04:53:45 +0000621 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
622 = diag::note_invalid_subexpr_in_const_expr,
623 unsigned ExtraNotes = 0) {
624 if (EvalStatus.Diag)
625 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
626 HasActiveDiagnostic = false;
627 return OptionalDiagnostic();
628 }
629
Richard Smith92b1ce02011-12-12 09:28:41 +0000630 /// Diagnose that the evaluation does not produce a C++11 core constant
631 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 ///
633 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
634 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000635 template<typename LocArg>
636 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000637 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000638 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000639 // Don't override a previous diagnostic. Don't bother collecting
640 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000641 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000642 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000643 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000644 }
Richard Smith357362d2011-12-13 06:39:58 +0000645 return Diag(Loc, DiagId, ExtraNotes);
646 }
647
648 /// Add a note to a prior diagnostic.
649 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
650 if (!HasActiveDiagnostic)
651 return OptionalDiagnostic();
652 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000653 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000654
655 /// Add a stack of notes to a prior diagnostic.
656 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
657 if (HasActiveDiagnostic) {
658 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
659 Diags.begin(), Diags.end());
660 }
661 }
Richard Smith253c2a32012-01-27 01:14:48 +0000662
Richard Smith6d4c6582013-11-05 22:18:15 +0000663 /// Should we continue evaluation after encountering a side-effect that we
664 /// couldn't model?
665 bool keepEvaluatingAfterSideEffect() {
666 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000667 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000668 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000669 case EM_EvaluateForOverflow:
670 case EM_IgnoreSideEffects:
671 return true;
672
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000674 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000675 case EM_ConstantFold:
676 return false;
677 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000678 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000679 }
680
681 /// Note that we have had a side-effect, and determine whether we should
682 /// keep evaluating.
683 bool noteSideEffect() {
684 EvalStatus.HasSideEffects = true;
685 return keepEvaluatingAfterSideEffect();
686 }
687
Richard Smith253c2a32012-01-27 01:14:48 +0000688 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000689 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000690 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000691 if (!StepsLeft)
692 return false;
693
694 switch (EvalMode) {
695 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000696 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000697 case EM_EvaluateForOverflow:
698 return true;
699
700 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000701 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 case EM_ConstantFold:
703 case EM_IgnoreSideEffects:
704 return false;
705 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000706 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000707 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000708 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000709
710 /// Object used to treat all foldable expressions as constant expressions.
711 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000713 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000714 bool HadNoPriorDiags;
715 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000716
Richard Smith6d4c6582013-11-05 22:18:15 +0000717 explicit FoldConstant(EvalInfo &Info, bool Enabled)
718 : Info(Info),
719 Enabled(Enabled),
720 HadNoPriorDiags(Info.EvalStatus.Diag &&
721 Info.EvalStatus.Diag->empty() &&
722 !Info.EvalStatus.HasSideEffects),
723 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000724 if (Enabled &&
725 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
726 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000728 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 void keepDiagnostics() { Enabled = false; }
730 ~FoldConstant() {
731 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000732 !Info.EvalStatus.HasSideEffects)
733 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000735 }
736 };
Richard Smith17100ba2012-02-16 02:46:34 +0000737
738 /// RAII object used to suppress diagnostics and side-effects from a
739 /// speculative evaluation.
740 class SpeculativeEvaluationRAII {
741 EvalInfo &Info;
742 Expr::EvalStatus Old;
743
744 public:
745 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000746 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000747 : Info(Info), Old(Info.EvalStatus) {
748 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000749 // If we're speculatively evaluating, we may have skipped over some
750 // evaluations and missed out a side effect.
751 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000752 }
753 ~SpeculativeEvaluationRAII() {
754 Info.EvalStatus = Old;
755 }
756 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000757
758 /// RAII object wrapping a full-expression or block scope, and handling
759 /// the ending of the lifetime of temporaries created within it.
760 template<bool IsFullExpression>
761 class ScopeRAII {
762 EvalInfo &Info;
763 unsigned OldStackSize;
764 public:
765 ScopeRAII(EvalInfo &Info)
766 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
767 ~ScopeRAII() {
768 // Body moved to a static method to encourage the compiler to inline away
769 // instances of this class.
770 cleanup(Info, OldStackSize);
771 }
772 private:
773 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
774 unsigned NewEnd = OldStackSize;
775 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
776 I != N; ++I) {
777 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
778 // Full-expression cleanup of a lifetime-extended temporary: nothing
779 // to do, just move this cleanup to the right place in the stack.
780 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
781 ++NewEnd;
782 } else {
783 // End the lifetime of the object.
784 Info.CleanupStack[I].endLifetime();
785 }
786 }
787 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
788 Info.CleanupStack.end());
789 }
790 };
791 typedef ScopeRAII<false> BlockScopeRAII;
792 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000793}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000794
Richard Smitha8105bc2012-01-06 16:39:00 +0000795bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
796 CheckSubobjectKind CSK) {
797 if (Invalid)
798 return false;
799 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000800 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000801 << CSK;
802 setInvalid();
803 return false;
804 }
805 return true;
806}
807
808void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
809 const Expr *E, uint64_t N) {
810 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000811 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000812 << static_cast<int>(N) << /*array*/ 0
813 << static_cast<unsigned>(MostDerivedArraySize);
814 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000815 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000816 << static_cast<int>(N) << /*non-array*/ 1;
817 setInvalid();
818}
819
Richard Smithf6f003a2011-12-16 19:06:07 +0000820CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
821 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000822 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000824 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000825 Info.CurrentCall = this;
826 ++Info.CallStackDepth;
827}
828
829CallStackFrame::~CallStackFrame() {
830 assert(Info.CurrentCall == this && "calls retired out of order");
831 --Info.CallStackDepth;
832 Info.CurrentCall = Caller;
833}
834
Richard Smith08d6a2c2013-07-24 07:11:57 +0000835APValue &CallStackFrame::createTemporary(const void *Key,
836 bool IsLifetimeExtended) {
837 APValue &Result = Temporaries[Key];
838 assert(Result.isUninit() && "temporary created multiple times");
839 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
840 return Result;
841}
842
Richard Smith84401042013-06-03 05:03:02 +0000843static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000844
845void EvalInfo::addCallStack(unsigned Limit) {
846 // Determine which calls to skip, if any.
847 unsigned ActiveCalls = CallStackDepth - 1;
848 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
849 if (Limit && Limit < ActiveCalls) {
850 SkipStart = Limit / 2 + Limit % 2;
851 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000852 }
853
Richard Smithf6f003a2011-12-16 19:06:07 +0000854 // Walk the call stack and add the diagnostics.
855 unsigned CallIdx = 0;
856 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
857 Frame = Frame->Caller, ++CallIdx) {
858 // Skip this call?
859 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
860 if (CallIdx == SkipStart) {
861 // Note that we're skipping calls.
862 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
863 << unsigned(ActiveCalls - Limit);
864 }
865 continue;
866 }
867
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000868 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000869 llvm::raw_svector_ostream Out(Buffer);
870 describeCall(Frame, Out);
871 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
872 }
873}
874
875namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000876 struct ComplexValue {
877 private:
878 bool IsInt;
879
880 public:
881 APSInt IntReal, IntImag;
882 APFloat FloatReal, FloatImag;
883
884 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
885
886 void makeComplexFloat() { IsInt = false; }
887 bool isComplexFloat() const { return !IsInt; }
888 APFloat &getComplexFloatReal() { return FloatReal; }
889 APFloat &getComplexFloatImag() { return FloatImag; }
890
891 void makeComplexInt() { IsInt = true; }
892 bool isComplexInt() const { return IsInt; }
893 APSInt &getComplexIntReal() { return IntReal; }
894 APSInt &getComplexIntImag() { return IntImag; }
895
Richard Smith2e312c82012-03-03 22:46:17 +0000896 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000897 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000898 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000899 else
Richard Smith2e312c82012-03-03 22:46:17 +0000900 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000901 }
Richard Smith2e312c82012-03-03 22:46:17 +0000902 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000903 assert(v.isComplexFloat() || v.isComplexInt());
904 if (v.isComplexFloat()) {
905 makeComplexFloat();
906 FloatReal = v.getComplexFloatReal();
907 FloatImag = v.getComplexFloatImag();
908 } else {
909 makeComplexInt();
910 IntReal = v.getComplexIntReal();
911 IntImag = v.getComplexIntImag();
912 }
913 }
John McCall93d91dc2010-05-07 17:22:02 +0000914 };
John McCall45d55e42010-05-07 21:00:08 +0000915
916 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000917 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000918 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000919 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000920 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000921
Richard Smithce40ad62011-11-12 22:28:03 +0000922 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000923 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000924 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000925 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000926 SubobjectDesignator &getLValueDesignator() { return Designator; }
927 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000928
Richard Smith2e312c82012-03-03 22:46:17 +0000929 void moveInto(APValue &V) const {
930 if (Designator.Invalid)
931 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
932 else
933 V = APValue(Base, Offset, Designator.Entries,
934 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000935 }
Richard Smith2e312c82012-03-03 22:46:17 +0000936 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000937 assert(V.isLValue());
938 Base = V.getLValueBase();
939 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000940 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000941 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000942 }
943
Richard Smithb228a862012-02-15 02:18:13 +0000944 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000945 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000946 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000947 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000948 Designator = SubobjectDesignator(getType(B));
949 }
950
951 // Check that this LValue is not based on a null pointer. If it is, produce
952 // a diagnostic and mark the designator as invalid.
953 bool checkNullPointer(EvalInfo &Info, const Expr *E,
954 CheckSubobjectKind CSK) {
955 if (Designator.Invalid)
956 return false;
957 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000958 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000959 << CSK;
960 Designator.setInvalid();
961 return false;
962 }
963 return true;
964 }
965
966 // Check this LValue refers to an object. If not, set the designator to be
967 // invalid and emit a diagnostic.
968 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000969 // Outside C++11, do not build a designator referring to a subobject of
970 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000971 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000972 Designator.setInvalid();
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000973 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000974 Designator.checkSubobject(Info, E, CSK);
975 }
976
977 void addDecl(EvalInfo &Info, const Expr *E,
978 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000979 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
980 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000981 }
982 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000983 if (checkSubobject(Info, E, CSK_ArrayToPointer))
984 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000985 }
Richard Smith66c96992012-02-18 22:04:06 +0000986 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000987 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
988 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000989 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000990 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000991 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +0000992 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000993 }
John McCall45d55e42010-05-07 21:00:08 +0000994 };
Richard Smith027bf112011-11-17 22:56:20 +0000995
996 struct MemberPtr {
997 MemberPtr() {}
998 explicit MemberPtr(const ValueDecl *Decl) :
999 DeclAndIsDerivedMember(Decl, false), Path() {}
1000
1001 /// The member or (direct or indirect) field referred to by this member
1002 /// pointer, or 0 if this is a null member pointer.
1003 const ValueDecl *getDecl() const {
1004 return DeclAndIsDerivedMember.getPointer();
1005 }
1006 /// Is this actually a member of some type derived from the relevant class?
1007 bool isDerivedMember() const {
1008 return DeclAndIsDerivedMember.getInt();
1009 }
1010 /// Get the class which the declaration actually lives in.
1011 const CXXRecordDecl *getContainingRecord() const {
1012 return cast<CXXRecordDecl>(
1013 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1014 }
1015
Richard Smith2e312c82012-03-03 22:46:17 +00001016 void moveInto(APValue &V) const {
1017 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001018 }
Richard Smith2e312c82012-03-03 22:46:17 +00001019 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001020 assert(V.isMemberPointer());
1021 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1022 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1023 Path.clear();
1024 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1025 Path.insert(Path.end(), P.begin(), P.end());
1026 }
1027
1028 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1029 /// whether the member is a member of some class derived from the class type
1030 /// of the member pointer.
1031 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1032 /// Path - The path of base/derived classes from the member declaration's
1033 /// class (exclusive) to the class type of the member pointer (inclusive).
1034 SmallVector<const CXXRecordDecl*, 4> Path;
1035
1036 /// Perform a cast towards the class of the Decl (either up or down the
1037 /// hierarchy).
1038 bool castBack(const CXXRecordDecl *Class) {
1039 assert(!Path.empty());
1040 const CXXRecordDecl *Expected;
1041 if (Path.size() >= 2)
1042 Expected = Path[Path.size() - 2];
1043 else
1044 Expected = getContainingRecord();
1045 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1046 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1047 // if B does not contain the original member and is not a base or
1048 // derived class of the class containing the original member, the result
1049 // of the cast is undefined.
1050 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1051 // (D::*). We consider that to be a language defect.
1052 return false;
1053 }
1054 Path.pop_back();
1055 return true;
1056 }
1057 /// Perform a base-to-derived member pointer cast.
1058 bool castToDerived(const CXXRecordDecl *Derived) {
1059 if (!getDecl())
1060 return true;
1061 if (!isDerivedMember()) {
1062 Path.push_back(Derived);
1063 return true;
1064 }
1065 if (!castBack(Derived))
1066 return false;
1067 if (Path.empty())
1068 DeclAndIsDerivedMember.setInt(false);
1069 return true;
1070 }
1071 /// Perform a derived-to-base member pointer cast.
1072 bool castToBase(const CXXRecordDecl *Base) {
1073 if (!getDecl())
1074 return true;
1075 if (Path.empty())
1076 DeclAndIsDerivedMember.setInt(true);
1077 if (isDerivedMember()) {
1078 Path.push_back(Base);
1079 return true;
1080 }
1081 return castBack(Base);
1082 }
1083 };
Richard Smith357362d2011-12-13 06:39:58 +00001084
Richard Smith7bb00672012-02-01 01:42:44 +00001085 /// Compare two member pointers, which are assumed to be of the same type.
1086 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1087 if (!LHS.getDecl() || !RHS.getDecl())
1088 return !LHS.getDecl() && !RHS.getDecl();
1089 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1090 return false;
1091 return LHS.Path == RHS.Path;
1092 }
John McCall93d91dc2010-05-07 17:22:02 +00001093}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001094
Richard Smith2e312c82012-03-03 22:46:17 +00001095static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001096static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1097 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001098 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001099static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1100static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001101static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1102 EvalInfo &Info);
1103static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001104static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001105static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001106 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001107static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001108static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001109static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001110
1111//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001112// Misc utilities
1113//===----------------------------------------------------------------------===//
1114
Richard Smith84401042013-06-03 05:03:02 +00001115/// Produce a string describing the given constexpr call.
1116static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1117 unsigned ArgIndex = 0;
1118 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1119 !isa<CXXConstructorDecl>(Frame->Callee) &&
1120 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1121
1122 if (!IsMemberCall)
1123 Out << *Frame->Callee << '(';
1124
1125 if (Frame->This && IsMemberCall) {
1126 APValue Val;
1127 Frame->This->moveInto(Val);
1128 Val.printPretty(Out, Frame->Info.Ctx,
1129 Frame->This->Designator.MostDerivedType);
1130 // FIXME: Add parens around Val if needed.
1131 Out << "->" << *Frame->Callee << '(';
1132 IsMemberCall = false;
1133 }
1134
1135 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1136 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1137 if (ArgIndex > (unsigned)IsMemberCall)
1138 Out << ", ";
1139
1140 const ParmVarDecl *Param = *I;
1141 const APValue &Arg = Frame->Arguments[ArgIndex];
1142 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1143
1144 if (ArgIndex == 0 && IsMemberCall)
1145 Out << "->" << *Frame->Callee << '(';
1146 }
1147
1148 Out << ')';
1149}
1150
Richard Smithd9f663b2013-04-22 15:31:51 +00001151/// Evaluate an expression to see if it had side-effects, and discard its
1152/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001153/// \return \c true if the caller should keep evaluating.
1154static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001155 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001156 if (!Evaluate(Scratch, Info, E))
1157 // We don't need the value, but we might have skipped a side effect here.
1158 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001159 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001160}
1161
Richard Smith861b5b52013-05-07 23:34:45 +00001162/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1163/// return its existing value.
1164static int64_t getExtValue(const APSInt &Value) {
1165 return Value.isSigned() ? Value.getSExtValue()
1166 : static_cast<int64_t>(Value.getZExtValue());
1167}
1168
Richard Smithd62306a2011-11-10 06:34:14 +00001169/// Should this call expression be treated as a string literal?
1170static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001171 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001172 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1173 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1174}
1175
Richard Smithce40ad62011-11-12 22:28:03 +00001176static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001177 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1178 // constant expression of pointer type that evaluates to...
1179
1180 // ... a null pointer value, or a prvalue core constant expression of type
1181 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001182 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001183
Richard Smithce40ad62011-11-12 22:28:03 +00001184 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1185 // ... the address of an object with static storage duration,
1186 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1187 return VD->hasGlobalStorage();
1188 // ... the address of a function,
1189 return isa<FunctionDecl>(D);
1190 }
1191
1192 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001193 switch (E->getStmtClass()) {
1194 default:
1195 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001196 case Expr::CompoundLiteralExprClass: {
1197 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1198 return CLE->isFileScope() && CLE->isLValue();
1199 }
Richard Smithe6c01442013-06-05 00:46:14 +00001200 case Expr::MaterializeTemporaryExprClass:
1201 // A materialized temporary might have been lifetime-extended to static
1202 // storage duration.
1203 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001204 // A string literal has static storage duration.
1205 case Expr::StringLiteralClass:
1206 case Expr::PredefinedExprClass:
1207 case Expr::ObjCStringLiteralClass:
1208 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001209 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001210 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001211 return true;
1212 case Expr::CallExprClass:
1213 return IsStringLiteralCall(cast<CallExpr>(E));
1214 // For GCC compatibility, &&label has static storage duration.
1215 case Expr::AddrLabelExprClass:
1216 return true;
1217 // A Block literal expression may be used as the initialization value for
1218 // Block variables at global or local static scope.
1219 case Expr::BlockExprClass:
1220 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001221 case Expr::ImplicitValueInitExprClass:
1222 // FIXME:
1223 // We can never form an lvalue with an implicit value initialization as its
1224 // base through expression evaluation, so these only appear in one case: the
1225 // implicit variable declaration we invent when checking whether a constexpr
1226 // constructor can produce a constant expression. We must assume that such
1227 // an expression might be a global lvalue.
1228 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001229 }
John McCall95007602010-05-10 23:27:23 +00001230}
1231
Richard Smithb228a862012-02-15 02:18:13 +00001232static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1233 assert(Base && "no location for a null lvalue");
1234 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1235 if (VD)
1236 Info.Note(VD->getLocation(), diag::note_declared_at);
1237 else
Ted Kremenek28831752012-08-23 20:46:57 +00001238 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001239 diag::note_constexpr_temporary_here);
1240}
1241
Richard Smith80815602011-11-07 05:07:52 +00001242/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001243/// value for an address or reference constant expression. Return true if we
1244/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001245static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1246 QualType Type, const LValue &LVal) {
1247 bool IsReferenceType = Type->isReferenceType();
1248
Richard Smith357362d2011-12-13 06:39:58 +00001249 APValue::LValueBase Base = LVal.getLValueBase();
1250 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1251
Richard Smith0dea49e2012-02-18 04:58:18 +00001252 // Check that the object is a global. Note that the fake 'this' object we
1253 // manufacture when checking potential constant expressions is conservatively
1254 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001255 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001256 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001258 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1259 << IsReferenceType << !Designator.Entries.empty()
1260 << !!VD << VD;
1261 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001262 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001263 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001264 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001265 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001266 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001267 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001268 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001269 LVal.getLValueCallIndex() == 0) &&
1270 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001271
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001272 // Check if this is a thread-local variable.
1273 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001275 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001276 return false;
1277 }
1278 }
1279
Richard Smitha8105bc2012-01-06 16:39:00 +00001280 // Allow address constant expressions to be past-the-end pointers. This is
1281 // an extension: the standard requires them to point to an object.
1282 if (!IsReferenceType)
1283 return true;
1284
1285 // A reference constant expression must refer to an object.
1286 if (!Base) {
1287 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001288 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001289 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001290 }
1291
Richard Smith357362d2011-12-13 06:39:58 +00001292 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001293 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001294 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001295 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001296 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001297 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001298 }
1299
Richard Smith80815602011-11-07 05:07:52 +00001300 return true;
1301}
1302
Richard Smithfddd3842011-12-30 21:15:51 +00001303/// Check that this core constant expression is of literal type, and if not,
1304/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001305static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001306 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001307 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001308 return true;
1309
Richard Smith7525ff62013-05-09 07:14:00 +00001310 // C++1y: A constant initializer for an object o [...] may also invoke
1311 // constexpr constructors for o and its subobjects even if those objects
1312 // are of non-literal class types.
1313 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001314 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001315 return true;
1316
Richard Smithfddd3842011-12-30 21:15:51 +00001317 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001318 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001319 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001320 << E->getType();
1321 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001322 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001323 return false;
1324}
1325
Richard Smith0b0a0b62011-10-29 20:57:55 +00001326/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001327/// constant expression. If not, report an appropriate diagnostic. Does not
1328/// check that the expression is of literal type.
1329static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1330 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001331 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001332 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1333 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001334 return false;
1335 }
1336
Richard Smithb228a862012-02-15 02:18:13 +00001337 // Core issue 1454: For a literal constant expression of array or class type,
1338 // each subobject of its value shall have been initialized by a constant
1339 // expression.
1340 if (Value.isArray()) {
1341 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1342 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1343 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1344 Value.getArrayInitializedElt(I)))
1345 return false;
1346 }
1347 if (!Value.hasArrayFiller())
1348 return true;
1349 return CheckConstantExpression(Info, DiagLoc, EltTy,
1350 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001351 }
Richard Smithb228a862012-02-15 02:18:13 +00001352 if (Value.isUnion() && Value.getUnionField()) {
1353 return CheckConstantExpression(Info, DiagLoc,
1354 Value.getUnionField()->getType(),
1355 Value.getUnionValue());
1356 }
1357 if (Value.isStruct()) {
1358 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1359 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1360 unsigned BaseIndex = 0;
1361 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1362 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1363 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1364 Value.getStructBase(BaseIndex)))
1365 return false;
1366 }
1367 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001368 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001369 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1370 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001371 return false;
1372 }
1373 }
1374
1375 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001376 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001377 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001378 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1379 }
1380
1381 // Everything else is fine.
1382 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001383}
1384
Richard Smith83c68212011-10-31 05:11:32 +00001385const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001386 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001387}
1388
1389static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001390 if (Value.CallIndex)
1391 return false;
1392 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1393 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001394}
1395
Richard Smithcecf1842011-11-01 21:06:14 +00001396static bool IsWeakLValue(const LValue &Value) {
1397 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001398 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001399}
1400
Richard Smith2e312c82012-03-03 22:46:17 +00001401static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001402 // A null base expression indicates a null pointer. These are always
1403 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001404 if (!Value.getLValueBase()) {
1405 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001406 return true;
1407 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001408
Richard Smith027bf112011-11-17 22:56:20 +00001409 // We have a non-null base. These are generally known to be true, but if it's
1410 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001411 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001412 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001413 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001414}
1415
Richard Smith2e312c82012-03-03 22:46:17 +00001416static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001417 switch (Val.getKind()) {
1418 case APValue::Uninitialized:
1419 return false;
1420 case APValue::Int:
1421 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001422 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001423 case APValue::Float:
1424 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001425 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001426 case APValue::ComplexInt:
1427 Result = Val.getComplexIntReal().getBoolValue() ||
1428 Val.getComplexIntImag().getBoolValue();
1429 return true;
1430 case APValue::ComplexFloat:
1431 Result = !Val.getComplexFloatReal().isZero() ||
1432 !Val.getComplexFloatImag().isZero();
1433 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001434 case APValue::LValue:
1435 return EvalPointerValueAsBool(Val, Result);
1436 case APValue::MemberPointer:
1437 Result = Val.getMemberPointerDecl();
1438 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001439 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001440 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001441 case APValue::Struct:
1442 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001443 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001444 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001445 }
1446
Richard Smith11562c52011-10-28 17:51:58 +00001447 llvm_unreachable("unknown APValue kind");
1448}
1449
1450static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1451 EvalInfo &Info) {
1452 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001453 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001454 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001455 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001456 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001457}
1458
Richard Smith357362d2011-12-13 06:39:58 +00001459template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001460static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001461 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001462 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001463 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001464}
1465
1466static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1467 QualType SrcType, const APFloat &Value,
1468 QualType DestType, APSInt &Result) {
1469 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001470 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001471 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001472
Richard Smith357362d2011-12-13 06:39:58 +00001473 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001474 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001475 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1476 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001477 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001478 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001479}
1480
Richard Smith357362d2011-12-13 06:39:58 +00001481static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1482 QualType SrcType, QualType DestType,
1483 APFloat &Result) {
1484 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001485 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001486 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1487 APFloat::rmNearestTiesToEven, &ignored)
1488 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001489 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001490 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001491}
1492
Richard Smith911e1422012-01-30 22:27:01 +00001493static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1494 QualType DestType, QualType SrcType,
1495 APSInt &Value) {
1496 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001497 APSInt Result = Value;
1498 // Figure out if this is a truncate, extend or noop cast.
1499 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001500 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001501 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001502 return Result;
1503}
1504
Richard Smith357362d2011-12-13 06:39:58 +00001505static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1506 QualType SrcType, const APSInt &Value,
1507 QualType DestType, APFloat &Result) {
1508 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1509 if (Result.convertFromAPInt(Value, Value.isSigned(),
1510 APFloat::rmNearestTiesToEven)
1511 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001512 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001513 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001514}
1515
Richard Smith49ca8aa2013-08-06 07:09:20 +00001516static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1517 APValue &Value, const FieldDecl *FD) {
1518 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1519
1520 if (!Value.isInt()) {
1521 // Trying to store a pointer-cast-to-integer into a bitfield.
1522 // FIXME: In this case, we should provide the diagnostic for casting
1523 // a pointer to an integer.
1524 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1525 Info.Diag(E);
1526 return false;
1527 }
1528
1529 APSInt &Int = Value.getInt();
1530 unsigned OldBitWidth = Int.getBitWidth();
1531 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1532 if (NewBitWidth < OldBitWidth)
1533 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1534 return true;
1535}
1536
Eli Friedman803acb32011-12-22 03:51:45 +00001537static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1538 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001539 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001540 if (!Evaluate(SVal, Info, E))
1541 return false;
1542 if (SVal.isInt()) {
1543 Res = SVal.getInt();
1544 return true;
1545 }
1546 if (SVal.isFloat()) {
1547 Res = SVal.getFloat().bitcastToAPInt();
1548 return true;
1549 }
1550 if (SVal.isVector()) {
1551 QualType VecTy = E->getType();
1552 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1553 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1554 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1555 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1556 Res = llvm::APInt::getNullValue(VecSize);
1557 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1558 APValue &Elt = SVal.getVectorElt(i);
1559 llvm::APInt EltAsInt;
1560 if (Elt.isInt()) {
1561 EltAsInt = Elt.getInt();
1562 } else if (Elt.isFloat()) {
1563 EltAsInt = Elt.getFloat().bitcastToAPInt();
1564 } else {
1565 // Don't try to handle vectors of anything other than int or float
1566 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001567 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001568 return false;
1569 }
1570 unsigned BaseEltSize = EltAsInt.getBitWidth();
1571 if (BigEndian)
1572 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1573 else
1574 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1575 }
1576 return true;
1577 }
1578 // Give up if the input isn't an int, float, or vector. For example, we
1579 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001580 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001581 return false;
1582}
1583
Richard Smith43e77732013-05-07 04:50:00 +00001584/// Perform the given integer operation, which is known to need at most BitWidth
1585/// bits, and check for overflow in the original type (if that type was not an
1586/// unsigned type).
1587template<typename Operation>
1588static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1589 const APSInt &LHS, const APSInt &RHS,
1590 unsigned BitWidth, Operation Op) {
1591 if (LHS.isUnsigned())
1592 return Op(LHS, RHS);
1593
1594 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1595 APSInt Result = Value.trunc(LHS.getBitWidth());
1596 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001597 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001598 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1599 diag::warn_integer_constant_overflow)
1600 << Result.toString(10) << E->getType();
1601 else
1602 HandleOverflow(Info, E, Value, E->getType());
1603 }
1604 return Result;
1605}
1606
1607/// Perform the given binary integer operation.
1608static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1609 BinaryOperatorKind Opcode, APSInt RHS,
1610 APSInt &Result) {
1611 switch (Opcode) {
1612 default:
1613 Info.Diag(E);
1614 return false;
1615 case BO_Mul:
1616 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1617 std::multiplies<APSInt>());
1618 return true;
1619 case BO_Add:
1620 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1621 std::plus<APSInt>());
1622 return true;
1623 case BO_Sub:
1624 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1625 std::minus<APSInt>());
1626 return true;
1627 case BO_And: Result = LHS & RHS; return true;
1628 case BO_Xor: Result = LHS ^ RHS; return true;
1629 case BO_Or: Result = LHS | RHS; return true;
1630 case BO_Div:
1631 case BO_Rem:
1632 if (RHS == 0) {
1633 Info.Diag(E, diag::note_expr_divide_by_zero);
1634 return false;
1635 }
1636 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1637 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1638 LHS.isSigned() && LHS.isMinSignedValue())
1639 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1640 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1641 return true;
1642 case BO_Shl: {
1643 if (Info.getLangOpts().OpenCL)
1644 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1645 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1646 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1647 RHS.isUnsigned());
1648 else if (RHS.isSigned() && RHS.isNegative()) {
1649 // During constant-folding, a negative shift is an opposite shift. Such
1650 // a shift is not a constant expression.
1651 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1652 RHS = -RHS;
1653 goto shift_right;
1654 }
1655 shift_left:
1656 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1657 // the shifted type.
1658 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1659 if (SA != RHS) {
1660 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1661 << RHS << E->getType() << LHS.getBitWidth();
1662 } else if (LHS.isSigned()) {
1663 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1664 // operand, and must not overflow the corresponding unsigned type.
1665 if (LHS.isNegative())
1666 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1667 else if (LHS.countLeadingZeros() < SA)
1668 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1669 }
1670 Result = LHS << SA;
1671 return true;
1672 }
1673 case BO_Shr: {
1674 if (Info.getLangOpts().OpenCL)
1675 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1676 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1677 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1678 RHS.isUnsigned());
1679 else if (RHS.isSigned() && RHS.isNegative()) {
1680 // During constant-folding, a negative shift is an opposite shift. Such a
1681 // shift is not a constant expression.
1682 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1683 RHS = -RHS;
1684 goto shift_left;
1685 }
1686 shift_right:
1687 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1688 // shifted type.
1689 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1690 if (SA != RHS)
1691 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1692 << RHS << E->getType() << LHS.getBitWidth();
1693 Result = LHS >> SA;
1694 return true;
1695 }
1696
1697 case BO_LT: Result = LHS < RHS; return true;
1698 case BO_GT: Result = LHS > RHS; return true;
1699 case BO_LE: Result = LHS <= RHS; return true;
1700 case BO_GE: Result = LHS >= RHS; return true;
1701 case BO_EQ: Result = LHS == RHS; return true;
1702 case BO_NE: Result = LHS != RHS; return true;
1703 }
1704}
1705
Richard Smith861b5b52013-05-07 23:34:45 +00001706/// Perform the given binary floating-point operation, in-place, on LHS.
1707static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1708 APFloat &LHS, BinaryOperatorKind Opcode,
1709 const APFloat &RHS) {
1710 switch (Opcode) {
1711 default:
1712 Info.Diag(E);
1713 return false;
1714 case BO_Mul:
1715 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1716 break;
1717 case BO_Add:
1718 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1719 break;
1720 case BO_Sub:
1721 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1722 break;
1723 case BO_Div:
1724 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1725 break;
1726 }
1727
1728 if (LHS.isInfinity() || LHS.isNaN())
1729 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1730 return true;
1731}
1732
Richard Smitha8105bc2012-01-06 16:39:00 +00001733/// Cast an lvalue referring to a base subobject to a derived class, by
1734/// truncating the lvalue's path to the given length.
1735static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1736 const RecordDecl *TruncatedType,
1737 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001738 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001739
1740 // Check we actually point to a derived class object.
1741 if (TruncatedElements == D.Entries.size())
1742 return true;
1743 assert(TruncatedElements >= D.MostDerivedPathLength &&
1744 "not casting to a derived class");
1745 if (!Result.checkSubobject(Info, E, CSK_Derived))
1746 return false;
1747
1748 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001749 const RecordDecl *RD = TruncatedType;
1750 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001751 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001752 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1753 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001754 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001755 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001756 else
Richard Smithd62306a2011-11-10 06:34:14 +00001757 Result.Offset -= Layout.getBaseClassOffset(Base);
1758 RD = Base;
1759 }
Richard Smith027bf112011-11-17 22:56:20 +00001760 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001761 return true;
1762}
1763
John McCalld7bca762012-05-01 00:38:49 +00001764static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001765 const CXXRecordDecl *Derived,
1766 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001767 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001768 if (!RL) {
1769 if (Derived->isInvalidDecl()) return false;
1770 RL = &Info.Ctx.getASTRecordLayout(Derived);
1771 }
1772
Richard Smithd62306a2011-11-10 06:34:14 +00001773 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001774 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001775 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001776}
1777
Richard Smitha8105bc2012-01-06 16:39:00 +00001778static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001779 const CXXRecordDecl *DerivedDecl,
1780 const CXXBaseSpecifier *Base) {
1781 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1782
John McCalld7bca762012-05-01 00:38:49 +00001783 if (!Base->isVirtual())
1784 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001785
Richard Smitha8105bc2012-01-06 16:39:00 +00001786 SubobjectDesignator &D = Obj.Designator;
1787 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001788 return false;
1789
Richard Smitha8105bc2012-01-06 16:39:00 +00001790 // Extract most-derived object and corresponding type.
1791 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1792 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1793 return false;
1794
1795 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001796 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001797 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1798 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001799 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001800 return true;
1801}
1802
Richard Smith84401042013-06-03 05:03:02 +00001803static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1804 QualType Type, LValue &Result) {
1805 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1806 PathE = E->path_end();
1807 PathI != PathE; ++PathI) {
1808 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1809 *PathI))
1810 return false;
1811 Type = (*PathI)->getType();
1812 }
1813 return true;
1814}
1815
Richard Smithd62306a2011-11-10 06:34:14 +00001816/// Update LVal to refer to the given field, which must be a member of the type
1817/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001818static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001819 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001820 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001821 if (!RL) {
1822 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001823 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001824 }
Richard Smithd62306a2011-11-10 06:34:14 +00001825
1826 unsigned I = FD->getFieldIndex();
1827 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001828 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001829 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001830}
1831
Richard Smith1b78b3d2012-01-25 22:15:11 +00001832/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001833static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001834 LValue &LVal,
1835 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001836 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001837 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001838 return false;
1839 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001840}
1841
Richard Smithd62306a2011-11-10 06:34:14 +00001842/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001843static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1844 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001845 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1846 // extension.
1847 if (Type->isVoidType() || Type->isFunctionType()) {
1848 Size = CharUnits::One();
1849 return true;
1850 }
1851
1852 if (!Type->isConstantSizeType()) {
1853 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001854 // FIXME: Better diagnostic.
1855 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001856 return false;
1857 }
1858
1859 Size = Info.Ctx.getTypeSizeInChars(Type);
1860 return true;
1861}
1862
1863/// Update a pointer value to model pointer arithmetic.
1864/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001865/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001866/// \param LVal - The pointer value to be updated.
1867/// \param EltTy - The pointee type represented by LVal.
1868/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001869static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1870 LValue &LVal, QualType EltTy,
1871 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001872 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001873 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001874 return false;
1875
1876 // Compute the new offset in the appropriate width.
1877 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001878 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001879 return true;
1880}
1881
Richard Smith66c96992012-02-18 22:04:06 +00001882/// Update an lvalue to refer to a component of a complex number.
1883/// \param Info - Information about the ongoing evaluation.
1884/// \param LVal - The lvalue to be updated.
1885/// \param EltTy - The complex number's component type.
1886/// \param Imag - False for the real component, true for the imaginary.
1887static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1888 LValue &LVal, QualType EltTy,
1889 bool Imag) {
1890 if (Imag) {
1891 CharUnits SizeOfComponent;
1892 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1893 return false;
1894 LVal.Offset += SizeOfComponent;
1895 }
1896 LVal.addComplex(Info, E, EltTy, Imag);
1897 return true;
1898}
1899
Richard Smith27908702011-10-24 17:54:18 +00001900/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001901///
1902/// \param Info Information about the ongoing evaluation.
1903/// \param E An expression to be used when printing diagnostics.
1904/// \param VD The variable whose initializer should be obtained.
1905/// \param Frame The frame in which the variable was created. Must be null
1906/// if this variable is not local to the evaluation.
1907/// \param Result Filled in with a pointer to the value of the variable.
1908static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1909 const VarDecl *VD, CallStackFrame *Frame,
1910 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001911 // If this is a parameter to an active constexpr function call, perform
1912 // argument substitution.
1913 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001914 // Assume arguments of a potential constant expression are unknown
1915 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001916 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001917 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001918 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001919 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001920 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001921 }
Richard Smith3229b742013-05-05 21:17:10 +00001922 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001923 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001924 }
Richard Smith27908702011-10-24 17:54:18 +00001925
Richard Smithd9f663b2013-04-22 15:31:51 +00001926 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001927 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001928 Result = Frame->getTemporary(VD);
1929 assert(Result && "missing value for local variable");
1930 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001931 }
1932
Richard Smithd0b4dd62011-12-19 06:19:21 +00001933 // Dig out the initializer, and use the declaration which it's attached to.
1934 const Expr *Init = VD->getAnyInitializer(VD);
1935 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001936 // If we're checking a potential constant expression, the variable could be
1937 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001938 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001939 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001940 return false;
1941 }
1942
Richard Smithd62306a2011-11-10 06:34:14 +00001943 // If we're currently evaluating the initializer of this declaration, use that
1944 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001945 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001946 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001947 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001948 }
1949
Richard Smithcecf1842011-11-01 21:06:14 +00001950 // Never evaluate the initializer of a weak variable. We can't be sure that
1951 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001952 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001953 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001954 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001955 }
Richard Smithcecf1842011-11-01 21:06:14 +00001956
Richard Smithd0b4dd62011-12-19 06:19:21 +00001957 // Check that we can fold the initializer. In C++, we will have already done
1958 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001959 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001960 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001961 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001962 Notes.size() + 1) << VD;
1963 Info.Note(VD->getLocation(), diag::note_declared_at);
1964 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001965 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001966 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001967 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001968 Notes.size() + 1) << VD;
1969 Info.Note(VD->getLocation(), diag::note_declared_at);
1970 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001971 }
Richard Smith27908702011-10-24 17:54:18 +00001972
Richard Smith3229b742013-05-05 21:17:10 +00001973 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001974 return true;
Richard Smith27908702011-10-24 17:54:18 +00001975}
1976
Richard Smith11562c52011-10-28 17:51:58 +00001977static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001978 Qualifiers Quals = T.getQualifiers();
1979 return Quals.hasConst() && !Quals.hasVolatile();
1980}
1981
Richard Smithe97cbd72011-11-11 04:05:33 +00001982/// Get the base index of the given base class within an APValue representing
1983/// the given derived class.
1984static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1985 const CXXRecordDecl *Base) {
1986 Base = Base->getCanonicalDecl();
1987 unsigned Index = 0;
1988 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1989 E = Derived->bases_end(); I != E; ++I, ++Index) {
1990 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1991 return Index;
1992 }
1993
1994 llvm_unreachable("base class missing from derived class's bases list");
1995}
1996
Richard Smith3da88fa2013-04-26 14:36:30 +00001997/// Extract the value of a character from a string literal.
1998static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1999 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00002000 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00002001 const StringLiteral *S = cast<StringLiteral>(Lit);
2002 const ConstantArrayType *CAT =
2003 Info.Ctx.getAsConstantArrayType(S->getType());
2004 assert(CAT && "string literal isn't an array");
2005 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002006 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002007
2008 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002009 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002010 if (Index < S->getLength())
2011 Value = S->getCodeUnit(Index);
2012 return Value;
2013}
2014
Richard Smith3da88fa2013-04-26 14:36:30 +00002015// Expand a string literal into an array of characters.
2016static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2017 APValue &Result) {
2018 const StringLiteral *S = cast<StringLiteral>(Lit);
2019 const ConstantArrayType *CAT =
2020 Info.Ctx.getAsConstantArrayType(S->getType());
2021 assert(CAT && "string literal isn't an array");
2022 QualType CharType = CAT->getElementType();
2023 assert(CharType->isIntegerType() && "unexpected character type");
2024
2025 unsigned Elts = CAT->getSize().getZExtValue();
2026 Result = APValue(APValue::UninitArray(),
2027 std::min(S->getLength(), Elts), Elts);
2028 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2029 CharType->isUnsignedIntegerType());
2030 if (Result.hasArrayFiller())
2031 Result.getArrayFiller() = APValue(Value);
2032 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2033 Value = S->getCodeUnit(I);
2034 Result.getArrayInitializedElt(I) = APValue(Value);
2035 }
2036}
2037
2038// Expand an array so that it has more than Index filled elements.
2039static void expandArray(APValue &Array, unsigned Index) {
2040 unsigned Size = Array.getArraySize();
2041 assert(Index < Size);
2042
2043 // Always at least double the number of elements for which we store a value.
2044 unsigned OldElts = Array.getArrayInitializedElts();
2045 unsigned NewElts = std::max(Index+1, OldElts * 2);
2046 NewElts = std::min(Size, std::max(NewElts, 8u));
2047
2048 // Copy the data across.
2049 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2050 for (unsigned I = 0; I != OldElts; ++I)
2051 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2052 for (unsigned I = OldElts; I != NewElts; ++I)
2053 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2054 if (NewValue.hasArrayFiller())
2055 NewValue.getArrayFiller() = Array.getArrayFiller();
2056 Array.swap(NewValue);
2057}
2058
Richard Smith861b5b52013-05-07 23:34:45 +00002059/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002060enum AccessKinds {
2061 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002062 AK_Assign,
2063 AK_Increment,
2064 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002065};
2066
Richard Smith3229b742013-05-05 21:17:10 +00002067/// A handle to a complete object (an object that is not a subobject of
2068/// another object).
2069struct CompleteObject {
2070 /// The value of the complete object.
2071 APValue *Value;
2072 /// The type of the complete object.
2073 QualType Type;
2074
Craig Topper36250ad2014-05-12 05:36:57 +00002075 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002076 CompleteObject(APValue *Value, QualType Type)
2077 : Value(Value), Type(Type) {
2078 assert(Value && "missing value for complete object");
2079 }
2080
David Blaikie7d170102013-05-15 07:37:26 +00002081 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002082};
2083
Richard Smith3da88fa2013-04-26 14:36:30 +00002084/// Find the designated sub-object of an rvalue.
2085template<typename SubobjectHandler>
2086typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002087findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002088 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002089 if (Sub.Invalid)
2090 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002091 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002092 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002093 if (Info.getLangOpts().CPlusPlus11)
2094 Info.Diag(E, diag::note_constexpr_access_past_end)
2095 << handler.AccessKind;
2096 else
2097 Info.Diag(E);
2098 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002099 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002100
Richard Smith3229b742013-05-05 21:17:10 +00002101 APValue *O = Obj.Value;
2102 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002103 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002104
Richard Smithd62306a2011-11-10 06:34:14 +00002105 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002106 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2107 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002108 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002109 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2110 return handler.failed();
2111 }
2112
Richard Smith49ca8aa2013-08-06 07:09:20 +00002113 if (I == N) {
2114 if (!handler.found(*O, ObjType))
2115 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002116
Richard Smith49ca8aa2013-08-06 07:09:20 +00002117 // If we modified a bit-field, truncate it to the right width.
2118 if (handler.AccessKind != AK_Read &&
2119 LastField && LastField->isBitField() &&
2120 !truncateBitfieldValue(Info, E, *O, LastField))
2121 return false;
2122
2123 return true;
2124 }
2125
Craig Topper36250ad2014-05-12 05:36:57 +00002126 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002127 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002128 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002129 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002130 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002131 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002132 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002133 // Note, it should not be possible to form a pointer with a valid
2134 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002135 if (Info.getLangOpts().CPlusPlus11)
2136 Info.Diag(E, diag::note_constexpr_access_past_end)
2137 << handler.AccessKind;
2138 else
2139 Info.Diag(E);
2140 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002141 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002142
2143 ObjType = CAT->getElementType();
2144
Richard Smith14a94132012-02-17 03:35:37 +00002145 // An array object is represented as either an Array APValue or as an
2146 // LValue which refers to a string literal.
2147 if (O->isLValue()) {
2148 assert(I == N - 1 && "extracting subobject of character?");
2149 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002150 if (handler.AccessKind != AK_Read)
2151 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2152 *O);
2153 else
2154 return handler.foundString(*O, ObjType, Index);
2155 }
2156
2157 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002158 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002159 else if (handler.AccessKind != AK_Read) {
2160 expandArray(*O, Index);
2161 O = &O->getArrayInitializedElt(Index);
2162 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002163 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002164 } else if (ObjType->isAnyComplexType()) {
2165 // Next subobject is a complex number.
2166 uint64_t Index = Sub.Entries[I].ArrayIndex;
2167 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002168 if (Info.getLangOpts().CPlusPlus11)
2169 Info.Diag(E, diag::note_constexpr_access_past_end)
2170 << handler.AccessKind;
2171 else
2172 Info.Diag(E);
2173 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002174 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002175
2176 bool WasConstQualified = ObjType.isConstQualified();
2177 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2178 if (WasConstQualified)
2179 ObjType.addConst();
2180
Richard Smith66c96992012-02-18 22:04:06 +00002181 assert(I == N - 1 && "extracting subobject of scalar?");
2182 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002183 return handler.found(Index ? O->getComplexIntImag()
2184 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002185 } else {
2186 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002187 return handler.found(Index ? O->getComplexFloatImag()
2188 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002189 }
Richard Smithd62306a2011-11-10 06:34:14 +00002190 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002191 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002192 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002193 << Field;
2194 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002195 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002196 }
2197
Richard Smithd62306a2011-11-10 06:34:14 +00002198 // Next subobject is a class, struct or union field.
2199 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2200 if (RD->isUnion()) {
2201 const FieldDecl *UnionField = O->getUnionField();
2202 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002203 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002204 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2205 << handler.AccessKind << Field << !UnionField << UnionField;
2206 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002207 }
Richard Smithd62306a2011-11-10 06:34:14 +00002208 O = &O->getUnionValue();
2209 } else
2210 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002211
2212 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002213 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002214 if (WasConstQualified && !Field->isMutable())
2215 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002216
2217 if (ObjType.isVolatileQualified()) {
2218 if (Info.getLangOpts().CPlusPlus) {
2219 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002220 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2221 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002222 Info.Note(Field->getLocation(), diag::note_declared_at);
2223 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002224 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002225 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002226 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002227 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002228
2229 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002230 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002231 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002232 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2233 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2234 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002235
2236 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002237 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002238 if (WasConstQualified)
2239 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002240 }
2241 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002242}
2243
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002244namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002245struct ExtractSubobjectHandler {
2246 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002247 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002248
2249 static const AccessKinds AccessKind = AK_Read;
2250
2251 typedef bool result_type;
2252 bool failed() { return false; }
2253 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002254 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002255 return true;
2256 }
2257 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002258 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002259 return true;
2260 }
2261 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002262 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002263 return true;
2264 }
2265 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002266 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002267 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2268 return true;
2269 }
2270};
Richard Smith3229b742013-05-05 21:17:10 +00002271} // end anonymous namespace
2272
Richard Smith3da88fa2013-04-26 14:36:30 +00002273const AccessKinds ExtractSubobjectHandler::AccessKind;
2274
2275/// Extract the designated sub-object of an rvalue.
2276static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002277 const CompleteObject &Obj,
2278 const SubobjectDesignator &Sub,
2279 APValue &Result) {
2280 ExtractSubobjectHandler Handler = { Info, Result };
2281 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002282}
2283
Richard Smith3229b742013-05-05 21:17:10 +00002284namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002285struct ModifySubobjectHandler {
2286 EvalInfo &Info;
2287 APValue &NewVal;
2288 const Expr *E;
2289
2290 typedef bool result_type;
2291 static const AccessKinds AccessKind = AK_Assign;
2292
2293 bool checkConst(QualType QT) {
2294 // Assigning to a const object has undefined behavior.
2295 if (QT.isConstQualified()) {
2296 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2297 return false;
2298 }
2299 return true;
2300 }
2301
2302 bool failed() { return false; }
2303 bool found(APValue &Subobj, QualType SubobjType) {
2304 if (!checkConst(SubobjType))
2305 return false;
2306 // We've been given ownership of NewVal, so just swap it in.
2307 Subobj.swap(NewVal);
2308 return true;
2309 }
2310 bool found(APSInt &Value, QualType SubobjType) {
2311 if (!checkConst(SubobjType))
2312 return false;
2313 if (!NewVal.isInt()) {
2314 // Maybe trying to write a cast pointer value into a complex?
2315 Info.Diag(E);
2316 return false;
2317 }
2318 Value = NewVal.getInt();
2319 return true;
2320 }
2321 bool found(APFloat &Value, QualType SubobjType) {
2322 if (!checkConst(SubobjType))
2323 return false;
2324 Value = NewVal.getFloat();
2325 return true;
2326 }
2327 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2328 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2329 }
2330};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002331} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002332
Richard Smith3229b742013-05-05 21:17:10 +00002333const AccessKinds ModifySubobjectHandler::AccessKind;
2334
Richard Smith3da88fa2013-04-26 14:36:30 +00002335/// Update the designated sub-object of an rvalue to the given value.
2336static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002337 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002338 const SubobjectDesignator &Sub,
2339 APValue &NewVal) {
2340 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002341 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002342}
2343
Richard Smith84f6dcf2012-02-02 01:16:57 +00002344/// Find the position where two subobject designators diverge, or equivalently
2345/// the length of the common initial subsequence.
2346static unsigned FindDesignatorMismatch(QualType ObjType,
2347 const SubobjectDesignator &A,
2348 const SubobjectDesignator &B,
2349 bool &WasArrayIndex) {
2350 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2351 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002352 if (!ObjType.isNull() &&
2353 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002354 // Next subobject is an array element.
2355 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2356 WasArrayIndex = true;
2357 return I;
2358 }
Richard Smith66c96992012-02-18 22:04:06 +00002359 if (ObjType->isAnyComplexType())
2360 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2361 else
2362 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002363 } else {
2364 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2365 WasArrayIndex = false;
2366 return I;
2367 }
2368 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2369 // Next subobject is a field.
2370 ObjType = FD->getType();
2371 else
2372 // Next subobject is a base class.
2373 ObjType = QualType();
2374 }
2375 }
2376 WasArrayIndex = false;
2377 return I;
2378}
2379
2380/// Determine whether the given subobject designators refer to elements of the
2381/// same array object.
2382static bool AreElementsOfSameArray(QualType ObjType,
2383 const SubobjectDesignator &A,
2384 const SubobjectDesignator &B) {
2385 if (A.Entries.size() != B.Entries.size())
2386 return false;
2387
2388 bool IsArray = A.MostDerivedArraySize != 0;
2389 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2390 // A is a subobject of the array element.
2391 return false;
2392
2393 // If A (and B) designates an array element, the last entry will be the array
2394 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2395 // of length 1' case, and the entire path must match.
2396 bool WasArrayIndex;
2397 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2398 return CommonLength >= A.Entries.size() - IsArray;
2399}
2400
Richard Smith3229b742013-05-05 21:17:10 +00002401/// Find the complete object to which an LValue refers.
2402CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2403 const LValue &LVal, QualType LValType) {
2404 if (!LVal.Base) {
2405 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2406 return CompleteObject();
2407 }
2408
Craig Topper36250ad2014-05-12 05:36:57 +00002409 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002410 if (LVal.CallIndex) {
2411 Frame = Info.getCallFrame(LVal.CallIndex);
2412 if (!Frame) {
2413 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2414 << AK << LVal.Base.is<const ValueDecl*>();
2415 NoteLValueLocation(Info, LVal.Base);
2416 return CompleteObject();
2417 }
Richard Smith3229b742013-05-05 21:17:10 +00002418 }
2419
2420 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2421 // is not a constant expression (even if the object is non-volatile). We also
2422 // apply this rule to C++98, in order to conform to the expected 'volatile'
2423 // semantics.
2424 if (LValType.isVolatileQualified()) {
2425 if (Info.getLangOpts().CPlusPlus)
2426 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2427 << AK << LValType;
2428 else
2429 Info.Diag(E);
2430 return CompleteObject();
2431 }
2432
2433 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002434 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002435 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002436
2437 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2438 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2439 // In C++11, constexpr, non-volatile variables initialized with constant
2440 // expressions are constant expressions too. Inside constexpr functions,
2441 // parameters are constant expressions even if they're non-const.
2442 // In C++1y, objects local to a constant expression (those with a Frame) are
2443 // both readable and writable inside constant expressions.
2444 // In C, such things can also be folded, although they are not ICEs.
2445 const VarDecl *VD = dyn_cast<VarDecl>(D);
2446 if (VD) {
2447 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2448 VD = VDef;
2449 }
2450 if (!VD || VD->isInvalidDecl()) {
2451 Info.Diag(E);
2452 return CompleteObject();
2453 }
2454
2455 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002456 if (BaseType.isVolatileQualified()) {
2457 if (Info.getLangOpts().CPlusPlus) {
2458 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2459 << AK << 1 << VD;
2460 Info.Note(VD->getLocation(), diag::note_declared_at);
2461 } else {
2462 Info.Diag(E);
2463 }
2464 return CompleteObject();
2465 }
2466
2467 // Unless we're looking at a local variable or argument in a constexpr call,
2468 // the variable we're reading must be const.
2469 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002470 if (Info.getLangOpts().CPlusPlus1y &&
2471 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2472 // OK, we can read and modify an object if we're in the process of
2473 // evaluating its initializer, because its lifetime began in this
2474 // evaluation.
2475 } else if (AK != AK_Read) {
2476 // All the remaining cases only permit reading.
2477 Info.Diag(E, diag::note_constexpr_modify_global);
2478 return CompleteObject();
2479 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002480 // OK, we can read this variable.
2481 } else if (BaseType->isIntegralOrEnumerationType()) {
2482 if (!BaseType.isConstQualified()) {
2483 if (Info.getLangOpts().CPlusPlus) {
2484 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2485 Info.Note(VD->getLocation(), diag::note_declared_at);
2486 } else {
2487 Info.Diag(E);
2488 }
2489 return CompleteObject();
2490 }
2491 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2492 // We support folding of const floating-point types, in order to make
2493 // static const data members of such types (supported as an extension)
2494 // more useful.
2495 if (Info.getLangOpts().CPlusPlus11) {
2496 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2497 Info.Note(VD->getLocation(), diag::note_declared_at);
2498 } else {
2499 Info.CCEDiag(E);
2500 }
2501 } else {
2502 // FIXME: Allow folding of values of any literal type in all languages.
2503 if (Info.getLangOpts().CPlusPlus11) {
2504 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2505 Info.Note(VD->getLocation(), diag::note_declared_at);
2506 } else {
2507 Info.Diag(E);
2508 }
2509 return CompleteObject();
2510 }
2511 }
2512
2513 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2514 return CompleteObject();
2515 } else {
2516 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2517
2518 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002519 if (const MaterializeTemporaryExpr *MTE =
2520 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2521 assert(MTE->getStorageDuration() == SD_Static &&
2522 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002523
Richard Smithe6c01442013-06-05 00:46:14 +00002524 // Per C++1y [expr.const]p2:
2525 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2526 // - a [...] glvalue of integral or enumeration type that refers to
2527 // a non-volatile const object [...]
2528 // [...]
2529 // - a [...] glvalue of literal type that refers to a non-volatile
2530 // object whose lifetime began within the evaluation of e.
2531 //
2532 // C++11 misses the 'began within the evaluation of e' check and
2533 // instead allows all temporaries, including things like:
2534 // int &&r = 1;
2535 // int x = ++r;
2536 // constexpr int k = r;
2537 // Therefore we use the C++1y rules in C++11 too.
2538 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2539 const ValueDecl *ED = MTE->getExtendingDecl();
2540 if (!(BaseType.isConstQualified() &&
2541 BaseType->isIntegralOrEnumerationType()) &&
2542 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2543 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2544 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2545 return CompleteObject();
2546 }
2547
2548 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2549 assert(BaseVal && "got reference to unevaluated temporary");
2550 } else {
2551 Info.Diag(E);
2552 return CompleteObject();
2553 }
2554 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002555 BaseVal = Frame->getTemporary(Base);
2556 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002557 }
Richard Smith3229b742013-05-05 21:17:10 +00002558
2559 // Volatile temporary objects cannot be accessed in constant expressions.
2560 if (BaseType.isVolatileQualified()) {
2561 if (Info.getLangOpts().CPlusPlus) {
2562 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563 << AK << 0;
2564 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2565 } else {
2566 Info.Diag(E);
2567 }
2568 return CompleteObject();
2569 }
2570 }
2571
Richard Smith7525ff62013-05-09 07:14:00 +00002572 // During the construction of an object, it is not yet 'const'.
2573 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2574 // and this doesn't do quite the right thing for const subobjects of the
2575 // object under construction.
2576 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2577 BaseType = Info.Ctx.getCanonicalType(BaseType);
2578 BaseType.removeLocalConst();
2579 }
2580
Richard Smith6d4c6582013-11-05 22:18:15 +00002581 // In C++1y, we can't safely access any mutable state when we might be
2582 // evaluating after an unmodeled side effect or an evaluation failure.
2583 //
2584 // FIXME: Not all local state is mutable. Allow local constant subobjects
2585 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002586 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002587 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002588 return CompleteObject();
2589
2590 return CompleteObject(BaseVal, BaseType);
2591}
2592
Richard Smith243ef902013-05-05 23:31:59 +00002593/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2594/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2595/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002596///
2597/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002598/// \param Conv - The expression for which we are performing the conversion.
2599/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002600/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2601/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002602/// \param LVal - The glvalue on which we are attempting to perform this action.
2603/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002604static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002605 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002606 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002607 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002608 return false;
2609
Richard Smith3229b742013-05-05 21:17:10 +00002610 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002611 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002612 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2613 !Type.isVolatileQualified()) {
2614 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2615 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2616 // initializer until now for such expressions. Such an expression can't be
2617 // an ICE in C, so this only matters for fold.
2618 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2619 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002620 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002621 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002622 }
Richard Smith3229b742013-05-05 21:17:10 +00002623 APValue Lit;
2624 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2625 return false;
2626 CompleteObject LitObj(&Lit, Base->getType());
2627 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2628 } else if (isa<StringLiteral>(Base)) {
2629 // We represent a string literal array as an lvalue pointing at the
2630 // corresponding expression, rather than building an array of chars.
2631 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2632 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2633 CompleteObject StrObj(&Str, Base->getType());
2634 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002635 }
Richard Smith11562c52011-10-28 17:51:58 +00002636 }
2637
Richard Smith3229b742013-05-05 21:17:10 +00002638 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2639 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002640}
2641
2642/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002643static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002644 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002645 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002646 return false;
2647
Richard Smith3229b742013-05-05 21:17:10 +00002648 if (!Info.getLangOpts().CPlusPlus1y) {
2649 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002650 return false;
2651 }
2652
Richard Smith3229b742013-05-05 21:17:10 +00002653 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2654 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002655}
2656
Richard Smith243ef902013-05-05 23:31:59 +00002657static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2658 return T->isSignedIntegerType() &&
2659 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2660}
2661
2662namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002663struct CompoundAssignSubobjectHandler {
2664 EvalInfo &Info;
2665 const Expr *E;
2666 QualType PromotedLHSType;
2667 BinaryOperatorKind Opcode;
2668 const APValue &RHS;
2669
2670 static const AccessKinds AccessKind = AK_Assign;
2671
2672 typedef bool result_type;
2673
2674 bool checkConst(QualType QT) {
2675 // Assigning to a const object has undefined behavior.
2676 if (QT.isConstQualified()) {
2677 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2678 return false;
2679 }
2680 return true;
2681 }
2682
2683 bool failed() { return false; }
2684 bool found(APValue &Subobj, QualType SubobjType) {
2685 switch (Subobj.getKind()) {
2686 case APValue::Int:
2687 return found(Subobj.getInt(), SubobjType);
2688 case APValue::Float:
2689 return found(Subobj.getFloat(), SubobjType);
2690 case APValue::ComplexInt:
2691 case APValue::ComplexFloat:
2692 // FIXME: Implement complex compound assignment.
2693 Info.Diag(E);
2694 return false;
2695 case APValue::LValue:
2696 return foundPointer(Subobj, SubobjType);
2697 default:
2698 // FIXME: can this happen?
2699 Info.Diag(E);
2700 return false;
2701 }
2702 }
2703 bool found(APSInt &Value, QualType SubobjType) {
2704 if (!checkConst(SubobjType))
2705 return false;
2706
2707 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2708 // We don't support compound assignment on integer-cast-to-pointer
2709 // values.
2710 Info.Diag(E);
2711 return false;
2712 }
2713
2714 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2715 SubobjType, Value);
2716 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2717 return false;
2718 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2719 return true;
2720 }
2721 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002722 return checkConst(SubobjType) &&
2723 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2724 Value) &&
2725 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2726 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002727 }
2728 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2729 if (!checkConst(SubobjType))
2730 return false;
2731
2732 QualType PointeeType;
2733 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2734 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002735
2736 if (PointeeType.isNull() || !RHS.isInt() ||
2737 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002738 Info.Diag(E);
2739 return false;
2740 }
2741
Richard Smith861b5b52013-05-07 23:34:45 +00002742 int64_t Offset = getExtValue(RHS.getInt());
2743 if (Opcode == BO_Sub)
2744 Offset = -Offset;
2745
2746 LValue LVal;
2747 LVal.setFrom(Info.Ctx, Subobj);
2748 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2749 return false;
2750 LVal.moveInto(Subobj);
2751 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002752 }
2753 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2754 llvm_unreachable("shouldn't encounter string elements here");
2755 }
2756};
2757} // end anonymous namespace
2758
2759const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2760
2761/// Perform a compound assignment of LVal <op>= RVal.
2762static bool handleCompoundAssignment(
2763 EvalInfo &Info, const Expr *E,
2764 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2765 BinaryOperatorKind Opcode, const APValue &RVal) {
2766 if (LVal.Designator.Invalid)
2767 return false;
2768
2769 if (!Info.getLangOpts().CPlusPlus1y) {
2770 Info.Diag(E);
2771 return false;
2772 }
2773
2774 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2775 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2776 RVal };
2777 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2778}
2779
2780namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002781struct IncDecSubobjectHandler {
2782 EvalInfo &Info;
2783 const Expr *E;
2784 AccessKinds AccessKind;
2785 APValue *Old;
2786
2787 typedef bool result_type;
2788
2789 bool checkConst(QualType QT) {
2790 // Assigning to a const object has undefined behavior.
2791 if (QT.isConstQualified()) {
2792 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2793 return false;
2794 }
2795 return true;
2796 }
2797
2798 bool failed() { return false; }
2799 bool found(APValue &Subobj, QualType SubobjType) {
2800 // Stash the old value. Also clear Old, so we don't clobber it later
2801 // if we're post-incrementing a complex.
2802 if (Old) {
2803 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002804 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002805 }
2806
2807 switch (Subobj.getKind()) {
2808 case APValue::Int:
2809 return found(Subobj.getInt(), SubobjType);
2810 case APValue::Float:
2811 return found(Subobj.getFloat(), SubobjType);
2812 case APValue::ComplexInt:
2813 return found(Subobj.getComplexIntReal(),
2814 SubobjType->castAs<ComplexType>()->getElementType()
2815 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2816 case APValue::ComplexFloat:
2817 return found(Subobj.getComplexFloatReal(),
2818 SubobjType->castAs<ComplexType>()->getElementType()
2819 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2820 case APValue::LValue:
2821 return foundPointer(Subobj, SubobjType);
2822 default:
2823 // FIXME: can this happen?
2824 Info.Diag(E);
2825 return false;
2826 }
2827 }
2828 bool found(APSInt &Value, QualType SubobjType) {
2829 if (!checkConst(SubobjType))
2830 return false;
2831
2832 if (!SubobjType->isIntegerType()) {
2833 // We don't support increment / decrement on integer-cast-to-pointer
2834 // values.
2835 Info.Diag(E);
2836 return false;
2837 }
2838
2839 if (Old) *Old = APValue(Value);
2840
2841 // bool arithmetic promotes to int, and the conversion back to bool
2842 // doesn't reduce mod 2^n, so special-case it.
2843 if (SubobjType->isBooleanType()) {
2844 if (AccessKind == AK_Increment)
2845 Value = 1;
2846 else
2847 Value = !Value;
2848 return true;
2849 }
2850
2851 bool WasNegative = Value.isNegative();
2852 if (AccessKind == AK_Increment) {
2853 ++Value;
2854
2855 if (!WasNegative && Value.isNegative() &&
2856 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2857 APSInt ActualValue(Value, /*IsUnsigned*/true);
2858 HandleOverflow(Info, E, ActualValue, SubobjType);
2859 }
2860 } else {
2861 --Value;
2862
2863 if (WasNegative && !Value.isNegative() &&
2864 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2865 unsigned BitWidth = Value.getBitWidth();
2866 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2867 ActualValue.setBit(BitWidth);
2868 HandleOverflow(Info, E, ActualValue, SubobjType);
2869 }
2870 }
2871 return true;
2872 }
2873 bool found(APFloat &Value, QualType SubobjType) {
2874 if (!checkConst(SubobjType))
2875 return false;
2876
2877 if (Old) *Old = APValue(Value);
2878
2879 APFloat One(Value.getSemantics(), 1);
2880 if (AccessKind == AK_Increment)
2881 Value.add(One, APFloat::rmNearestTiesToEven);
2882 else
2883 Value.subtract(One, APFloat::rmNearestTiesToEven);
2884 return true;
2885 }
2886 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2887 if (!checkConst(SubobjType))
2888 return false;
2889
2890 QualType PointeeType;
2891 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2892 PointeeType = PT->getPointeeType();
2893 else {
2894 Info.Diag(E);
2895 return false;
2896 }
2897
2898 LValue LVal;
2899 LVal.setFrom(Info.Ctx, Subobj);
2900 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2901 AccessKind == AK_Increment ? 1 : -1))
2902 return false;
2903 LVal.moveInto(Subobj);
2904 return true;
2905 }
2906 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2907 llvm_unreachable("shouldn't encounter string elements here");
2908 }
2909};
2910} // end anonymous namespace
2911
2912/// Perform an increment or decrement on LVal.
2913static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2914 QualType LValType, bool IsIncrement, APValue *Old) {
2915 if (LVal.Designator.Invalid)
2916 return false;
2917
2918 if (!Info.getLangOpts().CPlusPlus1y) {
2919 Info.Diag(E);
2920 return false;
2921 }
2922
2923 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2924 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2925 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2926 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2927}
2928
Richard Smithe97cbd72011-11-11 04:05:33 +00002929/// Build an lvalue for the object argument of a member function call.
2930static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2931 LValue &This) {
2932 if (Object->getType()->isPointerType())
2933 return EvaluatePointer(Object, This, Info);
2934
2935 if (Object->isGLValue())
2936 return EvaluateLValue(Object, This, Info);
2937
Richard Smithd9f663b2013-04-22 15:31:51 +00002938 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002939 return EvaluateTemporary(Object, This, Info);
2940
Richard Smith3e79a572014-06-11 19:53:12 +00002941 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002942 return false;
2943}
2944
2945/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2946/// lvalue referring to the result.
2947///
2948/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002949/// \param LV - An lvalue referring to the base of the member pointer.
2950/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002951/// \param IncludeMember - Specifies whether the member itself is included in
2952/// the resulting LValue subobject designator. This is not possible when
2953/// creating a bound member function.
2954/// \return The field or method declaration to which the member pointer refers,
2955/// or 0 if evaluation fails.
2956static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002957 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002958 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002959 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002960 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002961 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002962 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00002963 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00002964
2965 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2966 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002967 if (!MemPtr.getDecl()) {
2968 // FIXME: Specific diagnostic.
2969 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002970 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002971 }
Richard Smith253c2a32012-01-27 01:14:48 +00002972
Richard Smith027bf112011-11-17 22:56:20 +00002973 if (MemPtr.isDerivedMember()) {
2974 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002975 // The end of the derived-to-base path for the base object must match the
2976 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002977 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002978 LV.Designator.Entries.size()) {
2979 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002980 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002981 }
Richard Smith027bf112011-11-17 22:56:20 +00002982 unsigned PathLengthToMember =
2983 LV.Designator.Entries.size() - MemPtr.Path.size();
2984 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2985 const CXXRecordDecl *LVDecl = getAsBaseClass(
2986 LV.Designator.Entries[PathLengthToMember + I]);
2987 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002988 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2989 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002990 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002991 }
Richard Smith027bf112011-11-17 22:56:20 +00002992 }
2993
2994 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002995 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002996 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00002997 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00002998 } else if (!MemPtr.Path.empty()) {
2999 // Extend the LValue path with the member pointer's path.
3000 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3001 MemPtr.Path.size() + IncludeMember);
3002
3003 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003004 if (const PointerType *PT = LVType->getAs<PointerType>())
3005 LVType = PT->getPointeeType();
3006 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3007 assert(RD && "member pointer access on non-class-type expression");
3008 // The first class in the path is that of the lvalue.
3009 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3010 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003011 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003012 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003013 RD = Base;
3014 }
3015 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003016 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3017 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003018 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003019 }
3020
3021 // Add the member. Note that we cannot build bound member functions here.
3022 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003023 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003024 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003025 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003026 } else if (const IndirectFieldDecl *IFD =
3027 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003028 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003029 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003030 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003031 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003032 }
Richard Smith027bf112011-11-17 22:56:20 +00003033 }
3034
3035 return MemPtr.getDecl();
3036}
3037
Richard Smith84401042013-06-03 05:03:02 +00003038static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3039 const BinaryOperator *BO,
3040 LValue &LV,
3041 bool IncludeMember = true) {
3042 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3043
3044 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3045 if (Info.keepEvaluatingAfterFailure()) {
3046 MemberPtr MemPtr;
3047 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3048 }
Craig Topper36250ad2014-05-12 05:36:57 +00003049 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003050 }
3051
3052 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3053 BO->getRHS(), IncludeMember);
3054}
3055
Richard Smith027bf112011-11-17 22:56:20 +00003056/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3057/// the provided lvalue, which currently refers to the base object.
3058static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3059 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003060 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003061 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003062 return false;
3063
Richard Smitha8105bc2012-01-06 16:39:00 +00003064 QualType TargetQT = E->getType();
3065 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3066 TargetQT = PT->getPointeeType();
3067
3068 // Check this cast lands within the final derived-to-base subobject path.
3069 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003070 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003071 << D.MostDerivedType << TargetQT;
3072 return false;
3073 }
3074
Richard Smith027bf112011-11-17 22:56:20 +00003075 // Check the type of the final cast. We don't need to check the path,
3076 // since a cast can only be formed if the path is unique.
3077 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003078 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3079 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003080 if (NewEntriesSize == D.MostDerivedPathLength)
3081 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3082 else
Richard Smith027bf112011-11-17 22:56:20 +00003083 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003084 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003085 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003086 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003087 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003088 }
Richard Smith027bf112011-11-17 22:56:20 +00003089
3090 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003091 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003092}
3093
Mike Stump876387b2009-10-27 22:09:17 +00003094namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003095enum EvalStmtResult {
3096 /// Evaluation failed.
3097 ESR_Failed,
3098 /// Hit a 'return' statement.
3099 ESR_Returned,
3100 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003101 ESR_Succeeded,
3102 /// Hit a 'continue' statement.
3103 ESR_Continue,
3104 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003105 ESR_Break,
3106 /// Still scanning for 'case' or 'default' statement.
3107 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003108};
3109}
3110
Richard Smithd9f663b2013-04-22 15:31:51 +00003111static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3112 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3113 // We don't need to evaluate the initializer for a static local.
3114 if (!VD->hasLocalStorage())
3115 return true;
3116
3117 LValue Result;
3118 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003119 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003120
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003121 const Expr *InitE = VD->getInit();
3122 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003123 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3124 << false << VD->getType();
3125 Val = APValue();
3126 return false;
3127 }
3128
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003129 if (InitE->isValueDependent())
3130 return false;
3131
3132 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003133 // Wipe out any partially-computed value, to allow tracking that this
3134 // evaluation failed.
3135 Val = APValue();
3136 return false;
3137 }
3138 }
3139
3140 return true;
3141}
3142
Richard Smith4e18ca52013-05-06 05:56:11 +00003143/// Evaluate a condition (either a variable declaration or an expression).
3144static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3145 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003146 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003147 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3148 return false;
3149 return EvaluateAsBooleanCondition(Cond, Result, Info);
3150}
3151
3152static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003153 const Stmt *S,
3154 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003155
3156/// Evaluate the body of a loop, and translate the result as appropriate.
3157static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003158 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003159 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003160 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003161 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003162 case ESR_Break:
3163 return ESR_Succeeded;
3164 case ESR_Succeeded:
3165 case ESR_Continue:
3166 return ESR_Continue;
3167 case ESR_Failed:
3168 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003169 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003170 return ESR;
3171 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003172 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003173}
3174
Richard Smith496ddcf2013-05-12 17:32:42 +00003175/// Evaluate a switch statement.
3176static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3177 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003178 BlockScopeRAII Scope(Info);
3179
Richard Smith496ddcf2013-05-12 17:32:42 +00003180 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003181 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003182 {
3183 FullExpressionRAII Scope(Info);
3184 if (SS->getConditionVariable() &&
3185 !EvaluateDecl(Info, SS->getConditionVariable()))
3186 return ESR_Failed;
3187 if (!EvaluateInteger(SS->getCond(), Value, Info))
3188 return ESR_Failed;
3189 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003190
3191 // Find the switch case corresponding to the value of the condition.
3192 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003193 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003194 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3195 SC = SC->getNextSwitchCase()) {
3196 if (isa<DefaultStmt>(SC)) {
3197 Found = SC;
3198 continue;
3199 }
3200
3201 const CaseStmt *CS = cast<CaseStmt>(SC);
3202 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3203 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3204 : LHS;
3205 if (LHS <= Value && Value <= RHS) {
3206 Found = SC;
3207 break;
3208 }
3209 }
3210
3211 if (!Found)
3212 return ESR_Succeeded;
3213
3214 // Search the switch body for the switch case and evaluate it from there.
3215 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3216 case ESR_Break:
3217 return ESR_Succeeded;
3218 case ESR_Succeeded:
3219 case ESR_Continue:
3220 case ESR_Failed:
3221 case ESR_Returned:
3222 return ESR;
3223 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003224 // This can only happen if the switch case is nested within a statement
3225 // expression. We have no intention of supporting that.
3226 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3227 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003228 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003229 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003230}
3231
Richard Smith254a73d2011-10-28 22:34:42 +00003232// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003233static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003234 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003235 if (!Info.nextStep(S))
3236 return ESR_Failed;
3237
Richard Smith496ddcf2013-05-12 17:32:42 +00003238 // If we're hunting down a 'case' or 'default' label, recurse through
3239 // substatements until we hit the label.
3240 if (Case) {
3241 // FIXME: We don't start the lifetime of objects whose initialization we
3242 // jump over. However, such objects must be of class type with a trivial
3243 // default constructor that initialize all subobjects, so must be empty,
3244 // so this almost never matters.
3245 switch (S->getStmtClass()) {
3246 case Stmt::CompoundStmtClass:
3247 // FIXME: Precompute which substatement of a compound statement we
3248 // would jump to, and go straight there rather than performing a
3249 // linear scan each time.
3250 case Stmt::LabelStmtClass:
3251 case Stmt::AttributedStmtClass:
3252 case Stmt::DoStmtClass:
3253 break;
3254
3255 case Stmt::CaseStmtClass:
3256 case Stmt::DefaultStmtClass:
3257 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003258 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003259 break;
3260
3261 case Stmt::IfStmtClass: {
3262 // FIXME: Precompute which side of an 'if' we would jump to, and go
3263 // straight there rather than scanning both sides.
3264 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003265
3266 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3267 // preceded by our switch label.
3268 BlockScopeRAII Scope(Info);
3269
Richard Smith496ddcf2013-05-12 17:32:42 +00003270 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3271 if (ESR != ESR_CaseNotFound || !IS->getElse())
3272 return ESR;
3273 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3274 }
3275
3276 case Stmt::WhileStmtClass: {
3277 EvalStmtResult ESR =
3278 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3279 if (ESR != ESR_Continue)
3280 return ESR;
3281 break;
3282 }
3283
3284 case Stmt::ForStmtClass: {
3285 const ForStmt *FS = cast<ForStmt>(S);
3286 EvalStmtResult ESR =
3287 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3288 if (ESR != ESR_Continue)
3289 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003290 if (FS->getInc()) {
3291 FullExpressionRAII IncScope(Info);
3292 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3293 return ESR_Failed;
3294 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003295 break;
3296 }
3297
3298 case Stmt::DeclStmtClass:
3299 // FIXME: If the variable has initialization that can't be jumped over,
3300 // bail out of any immediately-surrounding compound-statement too.
3301 default:
3302 return ESR_CaseNotFound;
3303 }
3304 }
3305
Richard Smith254a73d2011-10-28 22:34:42 +00003306 switch (S->getStmtClass()) {
3307 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003308 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003309 // Don't bother evaluating beyond an expression-statement which couldn't
3310 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003311 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003312 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003313 return ESR_Failed;
3314 return ESR_Succeeded;
3315 }
3316
3317 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003318 return ESR_Failed;
3319
3320 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003321 return ESR_Succeeded;
3322
Richard Smithd9f663b2013-04-22 15:31:51 +00003323 case Stmt::DeclStmtClass: {
3324 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003325 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003326 // Each declaration initialization is its own full-expression.
3327 // FIXME: This isn't quite right; if we're performing aggregate
3328 // initialization, each braced subexpression is its own full-expression.
3329 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003330 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003331 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003332 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003333 return ESR_Succeeded;
3334 }
3335
Richard Smith357362d2011-12-13 06:39:58 +00003336 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003337 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003338 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003339 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003340 return ESR_Failed;
3341 return ESR_Returned;
3342 }
Richard Smith254a73d2011-10-28 22:34:42 +00003343
3344 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003345 BlockScopeRAII Scope(Info);
3346
Richard Smith254a73d2011-10-28 22:34:42 +00003347 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003348 for (const auto *BI : CS->body()) {
3349 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003350 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003351 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003352 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003353 return ESR;
3354 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003355 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003356 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003357
3358 case Stmt::IfStmtClass: {
3359 const IfStmt *IS = cast<IfStmt>(S);
3360
3361 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003362 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003363 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003364 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003365 return ESR_Failed;
3366
3367 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3368 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3369 if (ESR != ESR_Succeeded)
3370 return ESR;
3371 }
3372 return ESR_Succeeded;
3373 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003374
3375 case Stmt::WhileStmtClass: {
3376 const WhileStmt *WS = cast<WhileStmt>(S);
3377 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003378 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003379 bool Continue;
3380 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3381 Continue))
3382 return ESR_Failed;
3383 if (!Continue)
3384 break;
3385
3386 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3387 if (ESR != ESR_Continue)
3388 return ESR;
3389 }
3390 return ESR_Succeeded;
3391 }
3392
3393 case Stmt::DoStmtClass: {
3394 const DoStmt *DS = cast<DoStmt>(S);
3395 bool Continue;
3396 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003397 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003398 if (ESR != ESR_Continue)
3399 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003400 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003401
Richard Smith08d6a2c2013-07-24 07:11:57 +00003402 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003403 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3404 return ESR_Failed;
3405 } while (Continue);
3406 return ESR_Succeeded;
3407 }
3408
3409 case Stmt::ForStmtClass: {
3410 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003411 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003412 if (FS->getInit()) {
3413 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3414 if (ESR != ESR_Succeeded)
3415 return ESR;
3416 }
3417 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003418 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003419 bool Continue = true;
3420 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3421 FS->getCond(), Continue))
3422 return ESR_Failed;
3423 if (!Continue)
3424 break;
3425
3426 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3427 if (ESR != ESR_Continue)
3428 return ESR;
3429
Richard Smith08d6a2c2013-07-24 07:11:57 +00003430 if (FS->getInc()) {
3431 FullExpressionRAII IncScope(Info);
3432 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3433 return ESR_Failed;
3434 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003435 }
3436 return ESR_Succeeded;
3437 }
3438
Richard Smith896e0d72013-05-06 06:51:17 +00003439 case Stmt::CXXForRangeStmtClass: {
3440 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003441 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003442
3443 // Initialize the __range variable.
3444 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3445 if (ESR != ESR_Succeeded)
3446 return ESR;
3447
3448 // Create the __begin and __end iterators.
3449 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3450 if (ESR != ESR_Succeeded)
3451 return ESR;
3452
3453 while (true) {
3454 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003455 {
3456 bool Continue = true;
3457 FullExpressionRAII CondExpr(Info);
3458 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3459 return ESR_Failed;
3460 if (!Continue)
3461 break;
3462 }
Richard Smith896e0d72013-05-06 06:51:17 +00003463
3464 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003465 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003466 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3467 if (ESR != ESR_Succeeded)
3468 return ESR;
3469
3470 // Loop body.
3471 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3472 if (ESR != ESR_Continue)
3473 return ESR;
3474
3475 // Increment: ++__begin
3476 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3477 return ESR_Failed;
3478 }
3479
3480 return ESR_Succeeded;
3481 }
3482
Richard Smith496ddcf2013-05-12 17:32:42 +00003483 case Stmt::SwitchStmtClass:
3484 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3485
Richard Smith4e18ca52013-05-06 05:56:11 +00003486 case Stmt::ContinueStmtClass:
3487 return ESR_Continue;
3488
3489 case Stmt::BreakStmtClass:
3490 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003491
3492 case Stmt::LabelStmtClass:
3493 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3494
3495 case Stmt::AttributedStmtClass:
3496 // As a general principle, C++11 attributes can be ignored without
3497 // any semantic impact.
3498 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3499 Case);
3500
3501 case Stmt::CaseStmtClass:
3502 case Stmt::DefaultStmtClass:
3503 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003504 }
3505}
3506
Richard Smithcc36f692011-12-22 02:22:31 +00003507/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3508/// default constructor. If so, we'll fold it whether or not it's marked as
3509/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3510/// so we need special handling.
3511static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003512 const CXXConstructorDecl *CD,
3513 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003514 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3515 return false;
3516
Richard Smith66e05fe2012-01-18 05:21:49 +00003517 // Value-initialization does not call a trivial default constructor, so such a
3518 // call is a core constant expression whether or not the constructor is
3519 // constexpr.
3520 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003521 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003522 // FIXME: If DiagDecl is an implicitly-declared special member function,
3523 // we should be much more explicit about why it's not constexpr.
3524 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3525 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3526 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003527 } else {
3528 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3529 }
3530 }
3531 return true;
3532}
3533
Richard Smith357362d2011-12-13 06:39:58 +00003534/// CheckConstexprFunction - Check that a function can be called in a constant
3535/// expression.
3536static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3537 const FunctionDecl *Declaration,
3538 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003539 // Potential constant expressions can contain calls to declared, but not yet
3540 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003541 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003542 Declaration->isConstexpr())
3543 return false;
3544
Richard Smith0838f3a2013-05-14 05:18:44 +00003545 // Bail out with no diagnostic if the function declaration itself is invalid.
3546 // We will have produced a relevant diagnostic while parsing it.
3547 if (Declaration->isInvalidDecl())
3548 return false;
3549
Richard Smith357362d2011-12-13 06:39:58 +00003550 // Can we evaluate this function call?
3551 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3552 return true;
3553
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003554 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003555 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003556 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3557 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003558 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3559 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3560 << DiagDecl;
3561 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3562 } else {
3563 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3564 }
3565 return false;
3566}
3567
Richard Smithd62306a2011-11-10 06:34:14 +00003568namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003569typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003570}
3571
3572/// EvaluateArgs - Evaluate the arguments to a function call.
3573static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3574 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003575 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003576 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003577 I != E; ++I) {
3578 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3579 // If we're checking for a potential constant expression, evaluate all
3580 // initializers even if some of them fail.
3581 if (!Info.keepEvaluatingAfterFailure())
3582 return false;
3583 Success = false;
3584 }
3585 }
3586 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003587}
3588
Richard Smith254a73d2011-10-28 22:34:42 +00003589/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003590static bool HandleFunctionCall(SourceLocation CallLoc,
3591 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003592 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003593 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003594 ArgVector ArgValues(Args.size());
3595 if (!EvaluateArgs(Args, ArgValues, Info))
3596 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003597
Richard Smith253c2a32012-01-27 01:14:48 +00003598 if (!Info.CheckCallLimit(CallLoc))
3599 return false;
3600
3601 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003602
3603 // For a trivial copy or move assignment, perform an APValue copy. This is
3604 // essential for unions, where the operations performed by the assignment
3605 // operator cannot be represented as statements.
3606 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3607 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3608 assert(This &&
3609 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3610 LValue RHS;
3611 RHS.setFrom(Info.Ctx, ArgValues[0]);
3612 APValue RHSValue;
3613 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3614 RHS, RHSValue))
3615 return false;
3616 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3617 RHSValue))
3618 return false;
3619 This->moveInto(Result);
3620 return true;
3621 }
3622
Richard Smithd9f663b2013-04-22 15:31:51 +00003623 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003624 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003625 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003626 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003627 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003628 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003629 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003630}
3631
Richard Smithd62306a2011-11-10 06:34:14 +00003632/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003633static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003634 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003635 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003636 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003637 ArgVector ArgValues(Args.size());
3638 if (!EvaluateArgs(Args, ArgValues, Info))
3639 return false;
3640
Richard Smith253c2a32012-01-27 01:14:48 +00003641 if (!Info.CheckCallLimit(CallLoc))
3642 return false;
3643
Richard Smith3607ffe2012-02-13 03:54:03 +00003644 const CXXRecordDecl *RD = Definition->getParent();
3645 if (RD->getNumVBases()) {
3646 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3647 return false;
3648 }
3649
Richard Smith253c2a32012-01-27 01:14:48 +00003650 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003651
3652 // If it's a delegating constructor, just delegate.
3653 if (Definition->isDelegatingConstructor()) {
3654 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003655 {
3656 FullExpressionRAII InitScope(Info);
3657 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3658 return false;
3659 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003660 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003661 }
3662
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003663 // For a trivial copy or move constructor, perform an APValue copy. This is
3664 // essential for unions, where the operations performed by the constructor
3665 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003666 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003667 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3668 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003669 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003670 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003671 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003672 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003673 }
3674
3675 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003676 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003677 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003678 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003679
John McCalld7bca762012-05-01 00:38:49 +00003680 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003681 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3682
Richard Smith08d6a2c2013-07-24 07:11:57 +00003683 // A scope for temporaries lifetime-extended by reference members.
3684 BlockScopeRAII LifetimeExtendedScope(Info);
3685
Richard Smith253c2a32012-01-27 01:14:48 +00003686 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003687 unsigned BasesSeen = 0;
3688#ifndef NDEBUG
3689 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3690#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003691 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003692 LValue Subobject = This;
3693 APValue *Value = &Result;
3694
3695 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003696 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003697 if (I->isBaseInitializer()) {
3698 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003699#ifndef NDEBUG
3700 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003701 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003702 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3703 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3704 "base class initializers not in expected order");
3705 ++BaseIt;
3706#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003707 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003708 BaseType->getAsCXXRecordDecl(), &Layout))
3709 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003710 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003711 } else if ((FD = I->getMember())) {
3712 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003713 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003714 if (RD->isUnion()) {
3715 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003716 Value = &Result.getUnionValue();
3717 } else {
3718 Value = &Result.getStructField(FD->getFieldIndex());
3719 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003720 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003721 // Walk the indirect field decl's chain to find the object to initialize,
3722 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003723 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003724 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003725 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3726 // Switch the union field if it differs. This happens if we had
3727 // preceding zero-initialization, and we're now initializing a union
3728 // subobject other than the first.
3729 // FIXME: In this case, the values of the other subobjects are
3730 // specified, since zero-initialization sets all padding bits to zero.
3731 if (Value->isUninit() ||
3732 (Value->isUnion() && Value->getUnionField() != FD)) {
3733 if (CD->isUnion())
3734 *Value = APValue(FD);
3735 else
3736 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003737 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003738 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003739 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003740 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003741 if (CD->isUnion())
3742 Value = &Value->getUnionValue();
3743 else
3744 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003745 }
Richard Smithd62306a2011-11-10 06:34:14 +00003746 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003747 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003748 }
Richard Smith253c2a32012-01-27 01:14:48 +00003749
Richard Smith08d6a2c2013-07-24 07:11:57 +00003750 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003751 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3752 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003753 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003754 // If we're checking for a potential constant expression, evaluate all
3755 // initializers even if some of them fail.
3756 if (!Info.keepEvaluatingAfterFailure())
3757 return false;
3758 Success = false;
3759 }
Richard Smithd62306a2011-11-10 06:34:14 +00003760 }
3761
Richard Smithd9f663b2013-04-22 15:31:51 +00003762 return Success &&
3763 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003764}
3765
Eli Friedman9a156e52008-11-12 09:44:48 +00003766//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003767// Generic Evaluation
3768//===----------------------------------------------------------------------===//
3769namespace {
3770
Aaron Ballman68af21c2014-01-03 19:26:43 +00003771template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003772class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003773 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003774private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003775 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003776 return static_cast<Derived*>(this)->Success(V, E);
3777 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003778 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003779 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003780 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003781
Richard Smith17100ba2012-02-16 02:46:34 +00003782 // Check whether a conditional operator with a non-constant condition is a
3783 // potential constant expression. If neither arm is a potential constant
3784 // expression, then the conditional operator is not either.
3785 template<typename ConditionalOperator>
3786 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003787 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003788
3789 // Speculatively evaluate both arms.
3790 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003791 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003792 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3793
3794 StmtVisitorTy::Visit(E->getFalseExpr());
3795 if (Diag.empty())
3796 return;
3797
3798 Diag.clear();
3799 StmtVisitorTy::Visit(E->getTrueExpr());
3800 if (Diag.empty())
3801 return;
3802 }
3803
3804 Error(E, diag::note_constexpr_conditional_never_const);
3805 }
3806
3807
3808 template<typename ConditionalOperator>
3809 bool HandleConditionalOperator(const ConditionalOperator *E) {
3810 bool BoolResult;
3811 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003812 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003813 CheckPotentialConstantConditional(E);
3814 return false;
3815 }
3816
3817 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3818 return StmtVisitorTy::Visit(EvalExpr);
3819 }
3820
Peter Collingbournee9200682011-05-13 03:29:01 +00003821protected:
3822 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003823 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003824 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3825
Richard Smith92b1ce02011-12-12 09:28:41 +00003826 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003827 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003828 }
3829
Aaron Ballman68af21c2014-01-03 19:26:43 +00003830 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003831
3832public:
3833 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3834
3835 EvalInfo &getEvalInfo() { return Info; }
3836
Richard Smithf57d8cb2011-12-09 22:58:01 +00003837 /// Report an evaluation error. This should only be called when an error is
3838 /// first discovered. When propagating an error, just return false.
3839 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003840 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003841 return false;
3842 }
3843 bool Error(const Expr *E) {
3844 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3845 }
3846
Aaron Ballman68af21c2014-01-03 19:26:43 +00003847 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003848 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003849 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003850 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003851 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003852 }
3853
Aaron Ballman68af21c2014-01-03 19:26:43 +00003854 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003855 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003856 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003857 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003858 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003859 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003860 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003861 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003862 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003863 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003864 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003865 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003866 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003867 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003868 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003869 // The initializer may not have been parsed yet, or might be erroneous.
3870 if (!E->getExpr())
3871 return Error(E);
3872 return StmtVisitorTy::Visit(E->getExpr());
3873 }
Richard Smith5894a912011-12-19 22:12:41 +00003874 // We cannot create any objects for which cleanups are required, so there is
3875 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003876 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003877 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003878
Aaron Ballman68af21c2014-01-03 19:26:43 +00003879 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003880 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3881 return static_cast<Derived*>(this)->VisitCastExpr(E);
3882 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003883 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003884 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3885 return static_cast<Derived*>(this)->VisitCastExpr(E);
3886 }
3887
Aaron Ballman68af21c2014-01-03 19:26:43 +00003888 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003889 switch (E->getOpcode()) {
3890 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003891 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003892
3893 case BO_Comma:
3894 VisitIgnoredValue(E->getLHS());
3895 return StmtVisitorTy::Visit(E->getRHS());
3896
3897 case BO_PtrMemD:
3898 case BO_PtrMemI: {
3899 LValue Obj;
3900 if (!HandleMemberPointerAccess(Info, E, Obj))
3901 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003902 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003903 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003904 return false;
3905 return DerivedSuccess(Result, E);
3906 }
3907 }
3908 }
3909
Aaron Ballman68af21c2014-01-03 19:26:43 +00003910 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003911 // Evaluate and cache the common expression. We treat it as a temporary,
3912 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003913 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003914 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003915 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003916
Richard Smith17100ba2012-02-16 02:46:34 +00003917 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003918 }
3919
Aaron Ballman68af21c2014-01-03 19:26:43 +00003920 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003921 bool IsBcpCall = false;
3922 // If the condition (ignoring parens) is a __builtin_constant_p call,
3923 // the result is a constant expression if it can be folded without
3924 // side-effects. This is an important GNU extension. See GCC PR38377
3925 // for discussion.
3926 if (const CallExpr *CallCE =
3927 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00003928 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003929 IsBcpCall = true;
3930
3931 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3932 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003933 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003934 return false;
3935
Richard Smith6d4c6582013-11-05 22:18:15 +00003936 FoldConstant Fold(Info, IsBcpCall);
3937 if (!HandleConditionalOperator(E)) {
3938 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003939 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003940 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003941
3942 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003943 }
3944
Aaron Ballman68af21c2014-01-03 19:26:43 +00003945 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003946 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3947 return DerivedSuccess(*Value, E);
3948
3949 const Expr *Source = E->getSourceExpr();
3950 if (!Source)
3951 return Error(E);
3952 if (Source == E) { // sanity checking.
3953 assert(0 && "OpaqueValueExpr recursively refers to itself");
3954 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003955 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003956 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003957 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003958
Aaron Ballman68af21c2014-01-03 19:26:43 +00003959 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003960 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003961 QualType CalleeType = Callee->getType();
3962
Craig Topper36250ad2014-05-12 05:36:57 +00003963 const FunctionDecl *FD = nullptr;
3964 LValue *This = nullptr, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003965 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003966 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003967
Richard Smithe97cbd72011-11-11 04:05:33 +00003968 // Extract function decl and 'this' pointer from the callee.
3969 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00003970 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3972 // Explicit bound member calls, such as x.f() or p->g();
3973 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003974 return false;
3975 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003976 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003977 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003978 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3979 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003980 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3981 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003982 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003983 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003984 return Error(Callee);
3985
3986 FD = dyn_cast<FunctionDecl>(Member);
3987 if (!FD)
3988 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003989 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003990 LValue Call;
3991 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003993
Richard Smitha8105bc2012-01-06 16:39:00 +00003994 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003995 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003996 FD = dyn_cast_or_null<FunctionDecl>(
3997 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003998 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003999 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004000
4001 // Overloaded operator calls to member functions are represented as normal
4002 // calls with '*this' as the first argument.
4003 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4004 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004005 // FIXME: When selecting an implicit conversion for an overloaded
4006 // operator delete, we sometimes try to evaluate calls to conversion
4007 // operators without a 'this' parameter!
4008 if (Args.empty())
4009 return Error(E);
4010
Richard Smithe97cbd72011-11-11 04:05:33 +00004011 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4012 return false;
4013 This = &ThisVal;
4014 Args = Args.slice(1);
4015 }
4016
4017 // Don't call function pointers which have been cast to some other type.
4018 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004019 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004020 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004021 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004022
Richard Smith47b34932012-02-01 02:39:43 +00004023 if (This && !This->checkSubobject(Info, E, CSK_This))
4024 return false;
4025
Richard Smith3607ffe2012-02-13 03:54:03 +00004026 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4027 // calls to such functions in constant expressions.
4028 if (This && !HasQualifier &&
4029 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4030 return Error(E, diag::note_constexpr_virtual_call);
4031
Craig Topper36250ad2014-05-12 05:36:57 +00004032 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004033 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004034 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004035
Richard Smith357362d2011-12-13 06:39:58 +00004036 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004037 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4038 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004039 return false;
4040
Richard Smithb228a862012-02-15 02:18:13 +00004041 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004042 }
4043
Aaron Ballman68af21c2014-01-03 19:26:43 +00004044 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004045 return StmtVisitorTy::Visit(E->getInitializer());
4046 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004047 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004048 if (E->getNumInits() == 0)
4049 return DerivedZeroInitialization(E);
4050 if (E->getNumInits() == 1)
4051 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004052 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004053 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004054 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004055 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004056 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004058 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004059 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004060 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004061 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004062 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004063
Richard Smithd62306a2011-11-10 06:34:14 +00004064 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004065 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004066 assert(!E->isArrow() && "missing call to bound member function?");
4067
Richard Smith2e312c82012-03-03 22:46:17 +00004068 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004069 if (!Evaluate(Val, Info, E->getBase()))
4070 return false;
4071
4072 QualType BaseTy = E->getBase()->getType();
4073
4074 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004075 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004076 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004077 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004078 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4079
Richard Smith3229b742013-05-05 21:17:10 +00004080 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004081 SubobjectDesignator Designator(BaseTy);
4082 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004083
Richard Smith3229b742013-05-05 21:17:10 +00004084 APValue Result;
4085 return extractSubobject(Info, E, Obj, Designator, Result) &&
4086 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004087 }
4088
Aaron Ballman68af21c2014-01-03 19:26:43 +00004089 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004090 switch (E->getCastKind()) {
4091 default:
4092 break;
4093
Richard Smitha23ab512013-05-23 00:30:41 +00004094 case CK_AtomicToNonAtomic: {
4095 APValue AtomicVal;
4096 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4097 return false;
4098 return DerivedSuccess(AtomicVal, E);
4099 }
4100
Richard Smith11562c52011-10-28 17:51:58 +00004101 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004102 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004103 return StmtVisitorTy::Visit(E->getSubExpr());
4104
4105 case CK_LValueToRValue: {
4106 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004107 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4108 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004109 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004110 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004111 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004112 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004113 return false;
4114 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004115 }
4116 }
4117
Richard Smithf57d8cb2011-12-09 22:58:01 +00004118 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004119 }
4120
Aaron Ballman68af21c2014-01-03 19:26:43 +00004121 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004122 return VisitUnaryPostIncDec(UO);
4123 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004124 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004125 return VisitUnaryPostIncDec(UO);
4126 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004127 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004128 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4129 return Error(UO);
4130
4131 LValue LVal;
4132 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4133 return false;
4134 APValue RVal;
4135 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4136 UO->isIncrementOp(), &RVal))
4137 return false;
4138 return DerivedSuccess(RVal, UO);
4139 }
4140
Aaron Ballman68af21c2014-01-03 19:26:43 +00004141 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004142 // We will have checked the full-expressions inside the statement expression
4143 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004144 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004145 return Error(E);
4146
Richard Smith08d6a2c2013-07-24 07:11:57 +00004147 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004148 const CompoundStmt *CS = E->getSubStmt();
4149 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4150 BE = CS->body_end();
4151 /**/; ++BI) {
4152 if (BI + 1 == BE) {
4153 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4154 if (!FinalExpr) {
4155 Info.Diag((*BI)->getLocStart(),
4156 diag::note_constexpr_stmt_expr_unsupported);
4157 return false;
4158 }
4159 return this->Visit(FinalExpr);
4160 }
4161
4162 APValue ReturnValue;
4163 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4164 if (ESR != ESR_Succeeded) {
4165 // FIXME: If the statement-expression terminated due to 'return',
4166 // 'break', or 'continue', it would be nice to propagate that to
4167 // the outer statement evaluation rather than bailing out.
4168 if (ESR != ESR_Failed)
4169 Info.Diag((*BI)->getLocStart(),
4170 diag::note_constexpr_stmt_expr_unsupported);
4171 return false;
4172 }
4173 }
4174 }
4175
Richard Smith4a678122011-10-24 18:44:57 +00004176 /// Visit a value which is evaluated, but whose value is ignored.
4177 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004178 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004179 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004180};
4181
4182}
4183
4184//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004185// Common base class for lvalue and temporary evaluation.
4186//===----------------------------------------------------------------------===//
4187namespace {
4188template<class Derived>
4189class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004190 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004191protected:
4192 LValue &Result;
4193 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004194 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004195
4196 bool Success(APValue::LValueBase B) {
4197 Result.set(B);
4198 return true;
4199 }
4200
4201public:
4202 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4203 ExprEvaluatorBaseTy(Info), Result(Result) {}
4204
Richard Smith2e312c82012-03-03 22:46:17 +00004205 bool Success(const APValue &V, const Expr *E) {
4206 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004207 return true;
4208 }
Richard Smith027bf112011-11-17 22:56:20 +00004209
Richard Smith027bf112011-11-17 22:56:20 +00004210 bool VisitMemberExpr(const MemberExpr *E) {
4211 // Handle non-static data members.
4212 QualType BaseTy;
4213 if (E->isArrow()) {
4214 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4215 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004216 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004217 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004218 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004219 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4220 return false;
4221 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004222 } else {
4223 if (!this->Visit(E->getBase()))
4224 return false;
4225 BaseTy = E->getBase()->getType();
4226 }
Richard Smith027bf112011-11-17 22:56:20 +00004227
Richard Smith1b78b3d2012-01-25 22:15:11 +00004228 const ValueDecl *MD = E->getMemberDecl();
4229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4230 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4231 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4232 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004233 if (!HandleLValueMember(this->Info, E, Result, FD))
4234 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004235 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004236 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4237 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004238 } else
4239 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004240
Richard Smith1b78b3d2012-01-25 22:15:11 +00004241 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004242 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004243 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004244 RefValue))
4245 return false;
4246 return Success(RefValue, E);
4247 }
4248 return true;
4249 }
4250
4251 bool VisitBinaryOperator(const BinaryOperator *E) {
4252 switch (E->getOpcode()) {
4253 default:
4254 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4255
4256 case BO_PtrMemD:
4257 case BO_PtrMemI:
4258 return HandleMemberPointerAccess(this->Info, E, Result);
4259 }
4260 }
4261
4262 bool VisitCastExpr(const CastExpr *E) {
4263 switch (E->getCastKind()) {
4264 default:
4265 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4266
4267 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004268 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004269 if (!this->Visit(E->getSubExpr()))
4270 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004271
4272 // Now figure out the necessary offset to add to the base LV to get from
4273 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004274 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4275 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004276 }
4277 }
4278};
4279}
4280
4281//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004282// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004283//
4284// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4285// function designators (in C), decl references to void objects (in C), and
4286// temporaries (if building with -Wno-address-of-temporary).
4287//
4288// LValue evaluation produces values comprising a base expression of one of the
4289// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004290// - Declarations
4291// * VarDecl
4292// * FunctionDecl
4293// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004294// * CompoundLiteralExpr in C
4295// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004296// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004297// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004298// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004299// * ObjCEncodeExpr
4300// * AddrLabelExpr
4301// * BlockExpr
4302// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004303// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004304// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004305// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004306// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4307// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004308// * A MaterializeTemporaryExpr that has static storage duration, with no
4309// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004310// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004311//===----------------------------------------------------------------------===//
4312namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004313class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004314 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004315public:
Richard Smith027bf112011-11-17 22:56:20 +00004316 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4317 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004318
Richard Smith11562c52011-10-28 17:51:58 +00004319 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004320 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004321
Peter Collingbournee9200682011-05-13 03:29:01 +00004322 bool VisitDeclRefExpr(const DeclRefExpr *E);
4323 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004324 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004325 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4326 bool VisitMemberExpr(const MemberExpr *E);
4327 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4328 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004329 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004330 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004331 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4332 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004333 bool VisitUnaryReal(const UnaryOperator *E);
4334 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004335 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4336 return VisitUnaryPreIncDec(UO);
4337 }
4338 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4339 return VisitUnaryPreIncDec(UO);
4340 }
Richard Smith3229b742013-05-05 21:17:10 +00004341 bool VisitBinAssign(const BinaryOperator *BO);
4342 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004343
Peter Collingbournee9200682011-05-13 03:29:01 +00004344 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004345 switch (E->getCastKind()) {
4346 default:
Richard Smith027bf112011-11-17 22:56:20 +00004347 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004348
Eli Friedmance3e02a2011-10-11 00:13:24 +00004349 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004350 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004351 if (!Visit(E->getSubExpr()))
4352 return false;
4353 Result.Designator.setInvalid();
4354 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004355
Richard Smith027bf112011-11-17 22:56:20 +00004356 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004357 if (!Visit(E->getSubExpr()))
4358 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004359 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004360 }
4361 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004362};
4363} // end anonymous namespace
4364
Richard Smith11562c52011-10-28 17:51:58 +00004365/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004366/// expressions which are not glvalues, in two cases:
4367/// * function designators in C, and
4368/// * "extern void" objects
4369static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4370 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4371 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004372 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004373}
4374
Peter Collingbournee9200682011-05-13 03:29:01 +00004375bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer11a54c32014-06-24 06:40:51 +00004376 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
4377 if (FD->hasAttr<DLLImportAttr>())
4378 return ZeroInitialization(E);
Richard Smithce40ad62011-11-12 22:28:03 +00004379 return Success(FD);
David Majnemer11a54c32014-06-24 06:40:51 +00004380 }
Richard Smithce40ad62011-11-12 22:28:03 +00004381 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004382 return VisitVarDecl(E, VD);
4383 return Error(E);
4384}
Richard Smith733237d2011-10-24 23:14:33 +00004385
Richard Smith11562c52011-10-28 17:51:58 +00004386bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004387 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004388 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4389 Frame = Info.CurrentCall;
4390
Richard Smithfec09922011-11-01 16:57:24 +00004391 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004392 if (Frame) {
4393 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004394 return true;
4395 }
David Majnemerc28a9642014-06-24 05:59:13 +00004396 // The address of __declspec(dllimport) variables aren't constant.
4397 if (VD->hasAttr<DLLImportAttr>())
4398 return ZeroInitialization(E);
Richard Smithce40ad62011-11-12 22:28:03 +00004399 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004400 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004401
Richard Smith3229b742013-05-05 21:17:10 +00004402 APValue *V;
4403 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004404 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004405 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004406 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004407 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4408 return false;
4409 }
Richard Smith3229b742013-05-05 21:17:10 +00004410 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004411}
4412
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004413bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4414 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004415 // Walk through the expression to find the materialized temporary itself.
4416 SmallVector<const Expr *, 2> CommaLHSs;
4417 SmallVector<SubobjectAdjustment, 2> Adjustments;
4418 const Expr *Inner = E->GetTemporaryExpr()->
4419 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004420
Richard Smith84401042013-06-03 05:03:02 +00004421 // If we passed any comma operators, evaluate their LHSs.
4422 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4423 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4424 return false;
4425
Richard Smithe6c01442013-06-05 00:46:14 +00004426 // A materialized temporary with static storage duration can appear within the
4427 // result of a constant expression evaluation, so we need to preserve its
4428 // value for use outside this evaluation.
4429 APValue *Value;
4430 if (E->getStorageDuration() == SD_Static) {
4431 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004432 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004433 Result.set(E);
4434 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004435 Value = &Info.CurrentCall->
4436 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004437 Result.set(E, Info.CurrentCall->Index);
4438 }
4439
Richard Smithea4ad5d2013-06-06 08:19:16 +00004440 QualType Type = Inner->getType();
4441
Richard Smith84401042013-06-03 05:03:02 +00004442 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004443 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4444 (E->getStorageDuration() == SD_Static &&
4445 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4446 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004447 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004448 }
Richard Smith84401042013-06-03 05:03:02 +00004449
4450 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004451 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4452 --I;
4453 switch (Adjustments[I].Kind) {
4454 case SubobjectAdjustment::DerivedToBaseAdjustment:
4455 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4456 Type, Result))
4457 return false;
4458 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4459 break;
4460
4461 case SubobjectAdjustment::FieldAdjustment:
4462 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4463 return false;
4464 Type = Adjustments[I].Field->getType();
4465 break;
4466
4467 case SubobjectAdjustment::MemberPointerAdjustment:
4468 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4469 Adjustments[I].Ptr.RHS))
4470 return false;
4471 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4472 break;
4473 }
4474 }
4475
4476 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004477}
4478
Peter Collingbournee9200682011-05-13 03:29:01 +00004479bool
4480LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004481 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4482 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4483 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004484 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004485}
4486
Richard Smith6e525142011-12-27 12:18:28 +00004487bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004488 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004489 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004490
4491 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4492 << E->getExprOperand()->getType()
4493 << E->getExprOperand()->getSourceRange();
4494 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004495}
4496
Francois Pichet0066db92012-04-16 04:08:35 +00004497bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4498 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004499}
Francois Pichet0066db92012-04-16 04:08:35 +00004500
Peter Collingbournee9200682011-05-13 03:29:01 +00004501bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004502 // Handle static data members.
4503 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4504 VisitIgnoredValue(E->getBase());
4505 return VisitVarDecl(E, VD);
4506 }
4507
Richard Smith254a73d2011-10-28 22:34:42 +00004508 // Handle static member functions.
4509 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4510 if (MD->isStatic()) {
4511 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004512 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004513 }
4514 }
4515
Richard Smithd62306a2011-11-10 06:34:14 +00004516 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004517 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004518}
4519
Peter Collingbournee9200682011-05-13 03:29:01 +00004520bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004521 // FIXME: Deal with vectors as array subscript bases.
4522 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004523 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004524
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004525 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004526 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004527
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004528 APSInt Index;
4529 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004530 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004531
Richard Smith861b5b52013-05-07 23:34:45 +00004532 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4533 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004534}
Eli Friedman9a156e52008-11-12 09:44:48 +00004535
Peter Collingbournee9200682011-05-13 03:29:01 +00004536bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004537 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004538}
4539
Richard Smith66c96992012-02-18 22:04:06 +00004540bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4541 if (!Visit(E->getSubExpr()))
4542 return false;
4543 // __real is a no-op on scalar lvalues.
4544 if (E->getSubExpr()->getType()->isAnyComplexType())
4545 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4546 return true;
4547}
4548
4549bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4550 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4551 "lvalue __imag__ on scalar?");
4552 if (!Visit(E->getSubExpr()))
4553 return false;
4554 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4555 return true;
4556}
4557
Richard Smith243ef902013-05-05 23:31:59 +00004558bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4559 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004560 return Error(UO);
4561
4562 if (!this->Visit(UO->getSubExpr()))
4563 return false;
4564
Richard Smith243ef902013-05-05 23:31:59 +00004565 return handleIncDec(
4566 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004567 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004568}
4569
4570bool LValueExprEvaluator::VisitCompoundAssignOperator(
4571 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004572 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004573 return Error(CAO);
4574
Richard Smith3229b742013-05-05 21:17:10 +00004575 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004576
4577 // The overall lvalue result is the result of evaluating the LHS.
4578 if (!this->Visit(CAO->getLHS())) {
4579 if (Info.keepEvaluatingAfterFailure())
4580 Evaluate(RHS, this->Info, CAO->getRHS());
4581 return false;
4582 }
4583
Richard Smith3229b742013-05-05 21:17:10 +00004584 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4585 return false;
4586
Richard Smith43e77732013-05-07 04:50:00 +00004587 return handleCompoundAssignment(
4588 this->Info, CAO,
4589 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4590 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004591}
4592
4593bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004594 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4595 return Error(E);
4596
Richard Smith3229b742013-05-05 21:17:10 +00004597 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004598
4599 if (!this->Visit(E->getLHS())) {
4600 if (Info.keepEvaluatingAfterFailure())
4601 Evaluate(NewVal, this->Info, E->getRHS());
4602 return false;
4603 }
4604
Richard Smith3229b742013-05-05 21:17:10 +00004605 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4606 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004607
4608 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004609 NewVal);
4610}
4611
Eli Friedman9a156e52008-11-12 09:44:48 +00004612//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004613// Pointer Evaluation
4614//===----------------------------------------------------------------------===//
4615
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004616namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004617class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004618 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004619 LValue &Result;
4620
Peter Collingbournee9200682011-05-13 03:29:01 +00004621 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004622 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004623 return true;
4624 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004625public:
Mike Stump11289f42009-09-09 15:08:12 +00004626
John McCall45d55e42010-05-07 21:00:08 +00004627 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004628 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004629
Richard Smith2e312c82012-03-03 22:46:17 +00004630 bool Success(const APValue &V, const Expr *E) {
4631 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004632 return true;
4633 }
Richard Smithfddd3842011-12-30 21:15:51 +00004634 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004635 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004636 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004637
John McCall45d55e42010-05-07 21:00:08 +00004638 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004639 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004640 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004641 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004642 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004643 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004644 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004645 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004646 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004647 bool VisitCallExpr(const CallExpr *E);
4648 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004649 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004650 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004651 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004652 }
Richard Smithd62306a2011-11-10 06:34:14 +00004653 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004654 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004655 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004656 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004657 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004658 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004659 Result = *Info.CurrentCall->This;
4660 return true;
4661 }
John McCallc07a0c72011-02-17 10:25:35 +00004662
Eli Friedman449fe542009-03-23 04:56:01 +00004663 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004664};
Chris Lattner05706e882008-07-11 18:11:29 +00004665} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004666
John McCall45d55e42010-05-07 21:00:08 +00004667static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004668 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004669 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004670}
4671
John McCall45d55e42010-05-07 21:00:08 +00004672bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004673 if (E->getOpcode() != BO_Add &&
4674 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004675 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004676
Chris Lattner05706e882008-07-11 18:11:29 +00004677 const Expr *PExp = E->getLHS();
4678 const Expr *IExp = E->getRHS();
4679 if (IExp->getType()->isPointerType())
4680 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004681
Richard Smith253c2a32012-01-27 01:14:48 +00004682 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4683 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004684 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004685
John McCall45d55e42010-05-07 21:00:08 +00004686 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004687 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004688 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004689
4690 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004691 if (E->getOpcode() == BO_Sub)
4692 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004693
Ted Kremenek28831752012-08-23 20:46:57 +00004694 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004695 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4696 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004697}
Eli Friedman9a156e52008-11-12 09:44:48 +00004698
John McCall45d55e42010-05-07 21:00:08 +00004699bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4700 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004701}
Mike Stump11289f42009-09-09 15:08:12 +00004702
Peter Collingbournee9200682011-05-13 03:29:01 +00004703bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4704 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004705
Eli Friedman847a2bc2009-12-27 05:43:15 +00004706 switch (E->getCastKind()) {
4707 default:
4708 break;
4709
John McCalle3027922010-08-25 11:45:40 +00004710 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004711 case CK_CPointerToObjCPointerCast:
4712 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004713 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004714 if (!Visit(SubExpr))
4715 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004716 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4717 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4718 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004719 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004720 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004721 if (SubExpr->getType()->isVoidPointerType())
4722 CCEDiag(E, diag::note_constexpr_invalid_cast)
4723 << 3 << SubExpr->getType();
4724 else
4725 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4726 }
Richard Smith96e0c102011-11-04 02:25:55 +00004727 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004728
Anders Carlsson18275092010-10-31 20:41:46 +00004729 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004730 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004731 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004732 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004733 if (!Result.Base && Result.Offset.isZero())
4734 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004735
Richard Smithd62306a2011-11-10 06:34:14 +00004736 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004737 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004738 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4739 castAs<PointerType>()->getPointeeType(),
4740 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004741
Richard Smith027bf112011-11-17 22:56:20 +00004742 case CK_BaseToDerived:
4743 if (!Visit(E->getSubExpr()))
4744 return false;
4745 if (!Result.Base && Result.Offset.isZero())
4746 return true;
4747 return HandleBaseToDerivedCast(Info, E, Result);
4748
Richard Smith0b0a0b62011-10-29 20:57:55 +00004749 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004750 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004751 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004752
John McCalle3027922010-08-25 11:45:40 +00004753 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004754 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4755
Richard Smith2e312c82012-03-03 22:46:17 +00004756 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004757 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004758 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004759
John McCall45d55e42010-05-07 21:00:08 +00004760 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004761 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4762 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004763 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004764 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004765 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004766 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004767 return true;
4768 } else {
4769 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004770 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004771 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004772 }
4773 }
John McCalle3027922010-08-25 11:45:40 +00004774 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004775 if (SubExpr->isGLValue()) {
4776 if (!EvaluateLValue(SubExpr, Result, Info))
4777 return false;
4778 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004779 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004780 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004781 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004782 return false;
4783 }
Richard Smith96e0c102011-11-04 02:25:55 +00004784 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004785 if (const ConstantArrayType *CAT
4786 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4787 Result.addArray(Info, E, CAT);
4788 else
4789 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004790 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004791
John McCalle3027922010-08-25 11:45:40 +00004792 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004793 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004794 }
4795
Richard Smith11562c52011-10-28 17:51:58 +00004796 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004797}
Chris Lattner05706e882008-07-11 18:11:29 +00004798
Peter Collingbournee9200682011-05-13 03:29:01 +00004799bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004800 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004801 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004802
Alp Tokera724cff2013-12-28 21:59:02 +00004803 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004804 case Builtin::BI__builtin_addressof:
4805 return EvaluateLValue(E->getArg(0), Result, Info);
4806
4807 default:
4808 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4809 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004810}
Chris Lattner05706e882008-07-11 18:11:29 +00004811
4812//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004813// Member Pointer Evaluation
4814//===----------------------------------------------------------------------===//
4815
4816namespace {
4817class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004819 MemberPtr &Result;
4820
4821 bool Success(const ValueDecl *D) {
4822 Result = MemberPtr(D);
4823 return true;
4824 }
4825public:
4826
4827 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4828 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4829
Richard Smith2e312c82012-03-03 22:46:17 +00004830 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004831 Result.setFrom(V);
4832 return true;
4833 }
Richard Smithfddd3842011-12-30 21:15:51 +00004834 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004835 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00004836 }
4837
4838 bool VisitCastExpr(const CastExpr *E);
4839 bool VisitUnaryAddrOf(const UnaryOperator *E);
4840};
4841} // end anonymous namespace
4842
4843static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4844 EvalInfo &Info) {
4845 assert(E->isRValue() && E->getType()->isMemberPointerType());
4846 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4847}
4848
4849bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4850 switch (E->getCastKind()) {
4851 default:
4852 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4853
4854 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004855 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004856 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004857
4858 case CK_BaseToDerivedMemberPointer: {
4859 if (!Visit(E->getSubExpr()))
4860 return false;
4861 if (E->path_empty())
4862 return true;
4863 // Base-to-derived member pointer casts store the path in derived-to-base
4864 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4865 // the wrong end of the derived->base arc, so stagger the path by one class.
4866 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4867 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4868 PathI != PathE; ++PathI) {
4869 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4870 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4871 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004872 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004873 }
4874 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4875 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004876 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004877 return true;
4878 }
4879
4880 case CK_DerivedToBaseMemberPointer:
4881 if (!Visit(E->getSubExpr()))
4882 return false;
4883 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4884 PathE = E->path_end(); PathI != PathE; ++PathI) {
4885 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4886 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4887 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004888 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004889 }
4890 return true;
4891 }
4892}
4893
4894bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4895 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4896 // member can be formed.
4897 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4898}
4899
4900//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004901// Record Evaluation
4902//===----------------------------------------------------------------------===//
4903
4904namespace {
4905 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004906 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004907 const LValue &This;
4908 APValue &Result;
4909 public:
4910
4911 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4912 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4913
Richard Smith2e312c82012-03-03 22:46:17 +00004914 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004915 Result = V;
4916 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004917 }
Richard Smithfddd3842011-12-30 21:15:51 +00004918 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004919
Richard Smithe97cbd72011-11-11 04:05:33 +00004920 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004921 bool VisitInitListExpr(const InitListExpr *E);
4922 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004923 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004924 };
4925}
4926
Richard Smithfddd3842011-12-30 21:15:51 +00004927/// Perform zero-initialization on an object of non-union class type.
4928/// C++11 [dcl.init]p5:
4929/// To zero-initialize an object or reference of type T means:
4930/// [...]
4931/// -- if T is a (possibly cv-qualified) non-union class type,
4932/// each non-static data member and each base-class subobject is
4933/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004934static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4935 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004936 const LValue &This, APValue &Result) {
4937 assert(!RD->isUnion() && "Expected non-union class type");
4938 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4939 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00004940 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00004941
John McCalld7bca762012-05-01 00:38:49 +00004942 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004943 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4944
4945 if (CD) {
4946 unsigned Index = 0;
4947 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004948 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004949 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4950 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004951 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4952 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004953 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004954 Result.getStructBase(Index)))
4955 return false;
4956 }
4957 }
4958
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004959 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00004960 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004961 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004962 continue;
4963
4964 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004965 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004966 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004967
David Blaikie2d7c57e2012-04-30 02:36:29 +00004968 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004969 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004970 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004971 return false;
4972 }
4973
4974 return true;
4975}
4976
4977bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4978 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004979 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004980 if (RD->isUnion()) {
4981 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4982 // object's first non-static named data member is zero-initialized
4983 RecordDecl::field_iterator I = RD->field_begin();
4984 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00004985 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00004986 return true;
4987 }
4988
4989 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004990 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004991 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004992 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004993 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004994 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004995 }
4996
Richard Smith5d108602012-02-17 00:44:16 +00004997 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004998 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004999 return false;
5000 }
5001
Richard Smitha8105bc2012-01-06 16:39:00 +00005002 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005003}
5004
Richard Smithe97cbd72011-11-11 04:05:33 +00005005bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5006 switch (E->getCastKind()) {
5007 default:
5008 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5009
5010 case CK_ConstructorConversion:
5011 return Visit(E->getSubExpr());
5012
5013 case CK_DerivedToBase:
5014 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005015 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005016 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005018 if (!DerivedObject.isStruct())
5019 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005020
5021 // Derived-to-base rvalue conversion: just slice off the derived part.
5022 APValue *Value = &DerivedObject;
5023 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5024 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5025 PathE = E->path_end(); PathI != PathE; ++PathI) {
5026 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5027 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5028 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5029 RD = Base;
5030 }
5031 Result = *Value;
5032 return true;
5033 }
5034 }
5035}
5036
Richard Smithd62306a2011-11-10 06:34:14 +00005037bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5038 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005039 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005040 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5041
5042 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005043 const FieldDecl *Field = E->getInitializedFieldInUnion();
5044 Result = APValue(Field);
5045 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005046 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005047
5048 // If the initializer list for a union does not contain any elements, the
5049 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005050 // FIXME: The element should be initialized from an initializer list.
5051 // Is this difference ever observable for initializer lists which
5052 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005053 ImplicitValueInitExpr VIE(Field->getType());
5054 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5055
Richard Smithd62306a2011-11-10 06:34:14 +00005056 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005057 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5058 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005059
5060 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5061 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5062 isa<CXXDefaultInitExpr>(InitExpr));
5063
Richard Smithb228a862012-02-15 02:18:13 +00005064 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005065 }
5066
5067 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5068 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005069 Result = APValue(APValue::UninitStruct(), 0,
5070 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005071 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005072 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005073 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005074 // Anonymous bit-fields are not considered members of the class for
5075 // purposes of aggregate initialization.
5076 if (Field->isUnnamedBitfield())
5077 continue;
5078
5079 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005080
Richard Smith253c2a32012-01-27 01:14:48 +00005081 bool HaveInit = ElementNo < E->getNumInits();
5082
5083 // FIXME: Diagnostics here should point to the end of the initializer
5084 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005085 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005086 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005087 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005088
5089 // Perform an implicit value-initialization for members beyond the end of
5090 // the initializer list.
5091 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005092 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005093
Richard Smith852c9db2013-04-20 22:23:05 +00005094 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5095 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5096 isa<CXXDefaultInitExpr>(Init));
5097
Richard Smith49ca8aa2013-08-06 07:09:20 +00005098 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5099 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5100 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005101 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005102 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005103 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005104 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005105 }
5106 }
5107
Richard Smith253c2a32012-01-27 01:14:48 +00005108 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005109}
5110
5111bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5112 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005113 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5114
Richard Smithfddd3842011-12-30 21:15:51 +00005115 bool ZeroInit = E->requiresZeroInitialization();
5116 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005117 // If we've already performed zero-initialization, we're already done.
5118 if (!Result.isUninit())
5119 return true;
5120
Richard Smithda3f4fd2014-03-05 23:32:50 +00005121 // We can get here in two different ways:
5122 // 1) We're performing value-initialization, and should zero-initialize
5123 // the object, or
5124 // 2) We're performing default-initialization of an object with a trivial
5125 // constexpr default constructor, in which case we should start the
5126 // lifetimes of all the base subobjects (there can be no data member
5127 // subobjects in this case) per [basic.life]p1.
5128 // Either way, ZeroInitialization is appropriate.
5129 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005130 }
5131
Craig Topper36250ad2014-05-12 05:36:57 +00005132 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005133 FD->getBody(Definition);
5134
Richard Smith357362d2011-12-13 06:39:58 +00005135 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5136 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005137
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005138 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005139 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005140 if (const MaterializeTemporaryExpr *ME
5141 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5142 return Visit(ME->GetTemporaryExpr());
5143
Richard Smithfddd3842011-12-30 21:15:51 +00005144 if (ZeroInit && !ZeroInitialization(E))
5145 return false;
5146
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005147 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005148 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005149 cast<CXXConstructorDecl>(Definition), Info,
5150 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005151}
5152
Richard Smithcc1b96d2013-06-12 22:31:48 +00005153bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5154 const CXXStdInitializerListExpr *E) {
5155 const ConstantArrayType *ArrayType =
5156 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5157
5158 LValue Array;
5159 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5160 return false;
5161
5162 // Get a pointer to the first element of the array.
5163 Array.addArray(Info, E, ArrayType);
5164
5165 // FIXME: Perform the checks on the field types in SemaInit.
5166 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5167 RecordDecl::field_iterator Field = Record->field_begin();
5168 if (Field == Record->field_end())
5169 return Error(E);
5170
5171 // Start pointer.
5172 if (!Field->getType()->isPointerType() ||
5173 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5174 ArrayType->getElementType()))
5175 return Error(E);
5176
5177 // FIXME: What if the initializer_list type has base classes, etc?
5178 Result = APValue(APValue::UninitStruct(), 0, 2);
5179 Array.moveInto(Result.getStructField(0));
5180
5181 if (++Field == Record->field_end())
5182 return Error(E);
5183
5184 if (Field->getType()->isPointerType() &&
5185 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5186 ArrayType->getElementType())) {
5187 // End pointer.
5188 if (!HandleLValueArrayAdjustment(Info, E, Array,
5189 ArrayType->getElementType(),
5190 ArrayType->getSize().getZExtValue()))
5191 return false;
5192 Array.moveInto(Result.getStructField(1));
5193 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5194 // Length.
5195 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5196 else
5197 return Error(E);
5198
5199 if (++Field != Record->field_end())
5200 return Error(E);
5201
5202 return true;
5203}
5204
Richard Smithd62306a2011-11-10 06:34:14 +00005205static bool EvaluateRecord(const Expr *E, const LValue &This,
5206 APValue &Result, EvalInfo &Info) {
5207 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005208 "can't evaluate expression as a record rvalue");
5209 return RecordExprEvaluator(Info, This, Result).Visit(E);
5210}
5211
5212//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005213// Temporary Evaluation
5214//
5215// Temporaries are represented in the AST as rvalues, but generally behave like
5216// lvalues. The full-object of which the temporary is a subobject is implicitly
5217// materialized so that a reference can bind to it.
5218//===----------------------------------------------------------------------===//
5219namespace {
5220class TemporaryExprEvaluator
5221 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5222public:
5223 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5224 LValueExprEvaluatorBaseTy(Info, Result) {}
5225
5226 /// Visit an expression which constructs the value of this temporary.
5227 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005228 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005229 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5230 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005231 }
5232
5233 bool VisitCastExpr(const CastExpr *E) {
5234 switch (E->getCastKind()) {
5235 default:
5236 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5237
5238 case CK_ConstructorConversion:
5239 return VisitConstructExpr(E->getSubExpr());
5240 }
5241 }
5242 bool VisitInitListExpr(const InitListExpr *E) {
5243 return VisitConstructExpr(E);
5244 }
5245 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5246 return VisitConstructExpr(E);
5247 }
5248 bool VisitCallExpr(const CallExpr *E) {
5249 return VisitConstructExpr(E);
5250 }
5251};
5252} // end anonymous namespace
5253
5254/// Evaluate an expression of record type as a temporary.
5255static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005256 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005257 return TemporaryExprEvaluator(Info, Result).Visit(E);
5258}
5259
5260//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005261// Vector Evaluation
5262//===----------------------------------------------------------------------===//
5263
5264namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005265 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005266 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005267 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005268 public:
Mike Stump11289f42009-09-09 15:08:12 +00005269
Richard Smith2d406342011-10-22 21:10:00 +00005270 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5271 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005272
Richard Smith2d406342011-10-22 21:10:00 +00005273 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5274 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5275 // FIXME: remove this APValue copy.
5276 Result = APValue(V.data(), V.size());
5277 return true;
5278 }
Richard Smith2e312c82012-03-03 22:46:17 +00005279 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005280 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005281 Result = V;
5282 return true;
5283 }
Richard Smithfddd3842011-12-30 21:15:51 +00005284 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005285
Richard Smith2d406342011-10-22 21:10:00 +00005286 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005287 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005288 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005289 bool VisitInitListExpr(const InitListExpr *E);
5290 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005291 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005292 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005293 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005294 };
5295} // end anonymous namespace
5296
5297static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005298 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005299 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005300}
5301
Richard Smith2d406342011-10-22 21:10:00 +00005302bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5303 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005304 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005305
Richard Smith161f09a2011-12-06 22:44:34 +00005306 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005307 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005308
Eli Friedmanc757de22011-03-25 00:43:55 +00005309 switch (E->getCastKind()) {
5310 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005311 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005312 if (SETy->isIntegerType()) {
5313 APSInt IntResult;
5314 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005315 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005316 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005317 } else if (SETy->isRealFloatingType()) {
5318 APFloat F(0.0);
5319 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005320 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005321 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005322 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005323 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005324 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005325
5326 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005327 SmallVector<APValue, 4> Elts(NElts, Val);
5328 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005329 }
Eli Friedman803acb32011-12-22 03:51:45 +00005330 case CK_BitCast: {
5331 // Evaluate the operand into an APInt we can extract from.
5332 llvm::APInt SValInt;
5333 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5334 return false;
5335 // Extract the elements
5336 QualType EltTy = VTy->getElementType();
5337 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5338 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5339 SmallVector<APValue, 4> Elts;
5340 if (EltTy->isRealFloatingType()) {
5341 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005342 unsigned FloatEltSize = EltSize;
5343 if (&Sem == &APFloat::x87DoubleExtended)
5344 FloatEltSize = 80;
5345 for (unsigned i = 0; i < NElts; i++) {
5346 llvm::APInt Elt;
5347 if (BigEndian)
5348 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5349 else
5350 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005351 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005352 }
5353 } else if (EltTy->isIntegerType()) {
5354 for (unsigned i = 0; i < NElts; i++) {
5355 llvm::APInt Elt;
5356 if (BigEndian)
5357 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5358 else
5359 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5360 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5361 }
5362 } else {
5363 return Error(E);
5364 }
5365 return Success(Elts, E);
5366 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005367 default:
Richard Smith11562c52011-10-28 17:51:58 +00005368 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005369 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005370}
5371
Richard Smith2d406342011-10-22 21:10:00 +00005372bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005373VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005374 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005375 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005376 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005377
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005378 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005379 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005380
Eli Friedmanb9c71292012-01-03 23:24:20 +00005381 // The number of initializers can be less than the number of
5382 // vector elements. For OpenCL, this can be due to nested vector
5383 // initialization. For GCC compatibility, missing trailing elements
5384 // should be initialized with zeroes.
5385 unsigned CountInits = 0, CountElts = 0;
5386 while (CountElts < NumElements) {
5387 // Handle nested vector initialization.
5388 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005389 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005390 APValue v;
5391 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5392 return Error(E);
5393 unsigned vlen = v.getVectorLength();
5394 for (unsigned j = 0; j < vlen; j++)
5395 Elements.push_back(v.getVectorElt(j));
5396 CountElts += vlen;
5397 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005398 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005399 if (CountInits < NumInits) {
5400 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005401 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005402 } else // trailing integer zero.
5403 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5404 Elements.push_back(APValue(sInt));
5405 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005406 } else {
5407 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005408 if (CountInits < NumInits) {
5409 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005410 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005411 } else // trailing float zero.
5412 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5413 Elements.push_back(APValue(f));
5414 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005415 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005416 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005417 }
Richard Smith2d406342011-10-22 21:10:00 +00005418 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005419}
5420
Richard Smith2d406342011-10-22 21:10:00 +00005421bool
Richard Smithfddd3842011-12-30 21:15:51 +00005422VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005423 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005424 QualType EltTy = VT->getElementType();
5425 APValue ZeroElement;
5426 if (EltTy->isIntegerType())
5427 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5428 else
5429 ZeroElement =
5430 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5431
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005432 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005433 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005434}
5435
Richard Smith2d406342011-10-22 21:10:00 +00005436bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005437 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005438 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005439}
5440
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005441//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005442// Array Evaluation
5443//===----------------------------------------------------------------------===//
5444
5445namespace {
5446 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005447 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005448 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005449 APValue &Result;
5450 public:
5451
Richard Smithd62306a2011-11-10 06:34:14 +00005452 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5453 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005454
5455 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005456 assert((V.isArray() || V.isLValue()) &&
5457 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005458 Result = V;
5459 return true;
5460 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005461
Richard Smithfddd3842011-12-30 21:15:51 +00005462 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005463 const ConstantArrayType *CAT =
5464 Info.Ctx.getAsConstantArrayType(E->getType());
5465 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005466 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005467
5468 Result = APValue(APValue::UninitArray(), 0,
5469 CAT->getSize().getZExtValue());
5470 if (!Result.hasArrayFiller()) return true;
5471
Richard Smithfddd3842011-12-30 21:15:51 +00005472 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005473 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005474 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005475 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005476 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005477 }
5478
Richard Smithf3e9e432011-11-07 09:22:26 +00005479 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005480 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005481 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5482 const LValue &Subobject,
5483 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005484 };
5485} // end anonymous namespace
5486
Richard Smithd62306a2011-11-10 06:34:14 +00005487static bool EvaluateArray(const Expr *E, const LValue &This,
5488 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005489 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005490 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005491}
5492
5493bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5494 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5495 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005496 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005497
Richard Smithca2cfbf2011-12-22 01:07:19 +00005498 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5499 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005500 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005501 LValue LV;
5502 if (!EvaluateLValue(E->getInit(0), LV, Info))
5503 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005504 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005505 LV.moveInto(Val);
5506 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005507 }
5508
Richard Smith253c2a32012-01-27 01:14:48 +00005509 bool Success = true;
5510
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005511 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5512 "zero-initialized array shouldn't have any initialized elts");
5513 APValue Filler;
5514 if (Result.isArray() && Result.hasArrayFiller())
5515 Filler = Result.getArrayFiller();
5516
Richard Smith9543c5e2013-04-22 14:44:29 +00005517 unsigned NumEltsToInit = E->getNumInits();
5518 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005519 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005520
5521 // If the initializer might depend on the array index, run it for each
5522 // array element. For now, just whitelist non-class value-initialization.
5523 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5524 NumEltsToInit = NumElts;
5525
5526 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005527
5528 // If the array was previously zero-initialized, preserve the
5529 // zero-initialized values.
5530 if (!Filler.isUninit()) {
5531 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5532 Result.getArrayInitializedElt(I) = Filler;
5533 if (Result.hasArrayFiller())
5534 Result.getArrayFiller() = Filler;
5535 }
5536
Richard Smithd62306a2011-11-10 06:34:14 +00005537 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005538 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005539 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5540 const Expr *Init =
5541 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005542 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005543 Info, Subobject, Init) ||
5544 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005545 CAT->getElementType(), 1)) {
5546 if (!Info.keepEvaluatingAfterFailure())
5547 return false;
5548 Success = false;
5549 }
Richard Smithd62306a2011-11-10 06:34:14 +00005550 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005551
Richard Smith9543c5e2013-04-22 14:44:29 +00005552 if (!Result.hasArrayFiller())
5553 return Success;
5554
5555 // If we get here, we have a trivial filler, which we can just evaluate
5556 // once and splat over the rest of the array elements.
5557 assert(FillerExpr && "no array filler for incomplete init list");
5558 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5559 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005560}
5561
Richard Smith027bf112011-11-17 22:56:20 +00005562bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005563 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5564}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005565
Richard Smith9543c5e2013-04-22 14:44:29 +00005566bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5567 const LValue &Subobject,
5568 APValue *Value,
5569 QualType Type) {
5570 bool HadZeroInit = !Value->isUninit();
5571
5572 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5573 unsigned N = CAT->getSize().getZExtValue();
5574
5575 // Preserve the array filler if we had prior zero-initialization.
5576 APValue Filler =
5577 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5578 : APValue();
5579
5580 *Value = APValue(APValue::UninitArray(), N, N);
5581
5582 if (HadZeroInit)
5583 for (unsigned I = 0; I != N; ++I)
5584 Value->getArrayInitializedElt(I) = Filler;
5585
5586 // Initialize the elements.
5587 LValue ArrayElt = Subobject;
5588 ArrayElt.addArray(Info, E, CAT);
5589 for (unsigned I = 0; I != N; ++I)
5590 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5591 CAT->getElementType()) ||
5592 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5593 CAT->getElementType(), 1))
5594 return false;
5595
5596 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005597 }
Richard Smith027bf112011-11-17 22:56:20 +00005598
Richard Smith9543c5e2013-04-22 14:44:29 +00005599 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005600 return Error(E);
5601
Richard Smith027bf112011-11-17 22:56:20 +00005602 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005603
Richard Smithfddd3842011-12-30 21:15:51 +00005604 bool ZeroInit = E->requiresZeroInitialization();
5605 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005606 if (HadZeroInit)
5607 return true;
5608
Richard Smithda3f4fd2014-03-05 23:32:50 +00005609 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5610 ImplicitValueInitExpr VIE(Type);
5611 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005612 }
5613
Craig Topper36250ad2014-05-12 05:36:57 +00005614 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005615 FD->getBody(Definition);
5616
Richard Smith357362d2011-12-13 06:39:58 +00005617 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5618 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005619
Richard Smith9eae7232012-01-12 18:54:33 +00005620 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005621 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005622 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005623 return false;
5624 }
5625
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005626 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005627 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005628 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005629 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005630}
5631
Richard Smithf3e9e432011-11-07 09:22:26 +00005632//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005633// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005634//
5635// As a GNU extension, we support casting pointers to sufficiently-wide integer
5636// types and back in constant folding. Integer values are thus represented
5637// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005638//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005639
5640namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005641class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005642 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005643 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005644public:
Richard Smith2e312c82012-03-03 22:46:17 +00005645 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005646 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005647
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005648 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005649 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005650 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005651 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005652 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005653 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005654 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005655 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005656 return true;
5657 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005658 bool Success(const llvm::APSInt &SI, const Expr *E) {
5659 return Success(SI, E, Result);
5660 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005661
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005662 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005663 assert(E->getType()->isIntegralOrEnumerationType() &&
5664 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005665 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005666 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005667 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005668 Result.getInt().setIsUnsigned(
5669 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005670 return true;
5671 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005672 bool Success(const llvm::APInt &I, const Expr *E) {
5673 return Success(I, E, Result);
5674 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005675
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005676 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005677 assert(E->getType()->isIntegralOrEnumerationType() &&
5678 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005679 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005680 return true;
5681 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005682 bool Success(uint64_t Value, const Expr *E) {
5683 return Success(Value, E, Result);
5684 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005685
Ken Dyckdbc01912011-03-11 02:13:43 +00005686 bool Success(CharUnits Size, const Expr *E) {
5687 return Success(Size.getQuantity(), E);
5688 }
5689
Richard Smith2e312c82012-03-03 22:46:17 +00005690 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005691 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005692 Result = V;
5693 return true;
5694 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005695 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005696 }
Mike Stump11289f42009-09-09 15:08:12 +00005697
Richard Smithfddd3842011-12-30 21:15:51 +00005698 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005699
Peter Collingbournee9200682011-05-13 03:29:01 +00005700 //===--------------------------------------------------------------------===//
5701 // Visitor Methods
5702 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005703
Chris Lattner7174bf32008-07-12 00:38:25 +00005704 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005705 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005706 }
5707 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005708 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005709 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005710
5711 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5712 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005713 if (CheckReferencedDecl(E, E->getDecl()))
5714 return true;
5715
5716 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005717 }
5718 bool VisitMemberExpr(const MemberExpr *E) {
5719 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005720 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005721 return true;
5722 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005723
5724 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005725 }
5726
Peter Collingbournee9200682011-05-13 03:29:01 +00005727 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005728 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005729 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005730 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005731
Peter Collingbournee9200682011-05-13 03:29:01 +00005732 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005733 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005734
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005735 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005736 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005737 }
Mike Stump11289f42009-09-09 15:08:12 +00005738
Ted Kremeneke65b0862012-03-06 20:05:56 +00005739 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5740 return Success(E->getValue(), E);
5741 }
5742
Richard Smith4ce706a2011-10-11 21:43:33 +00005743 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005744 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005745 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005746 }
5747
Douglas Gregor29c42f22012-02-24 07:38:34 +00005748 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5749 return Success(E->getValue(), E);
5750 }
5751
John Wiegley6242b6a2011-04-28 00:16:57 +00005752 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5753 return Success(E->getValue(), E);
5754 }
5755
John Wiegleyf9f65842011-04-25 06:54:41 +00005756 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5757 return Success(E->getValue(), E);
5758 }
5759
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005760 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005761 bool VisitUnaryImag(const UnaryOperator *E);
5762
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005763 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005764 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005765
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005766private:
Ken Dyck160146e2010-01-27 17:10:57 +00005767 CharUnits GetAlignOfExpr(const Expr *E);
5768 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005769 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005770 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005771 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005772};
Chris Lattner05706e882008-07-11 18:11:29 +00005773} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005774
Richard Smith11562c52011-10-28 17:51:58 +00005775/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5776/// produce either the integer value or a pointer.
5777///
5778/// GCC has a heinous extension which folds casts between pointer types and
5779/// pointer-sized integral types. We support this by allowing the evaluation of
5780/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5781/// Some simple arithmetic on such values is supported (they are treated much
5782/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005783static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005784 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005785 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005786 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005787}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005788
Richard Smithf57d8cb2011-12-09 22:58:01 +00005789static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005790 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005791 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005792 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005793 if (!Val.isInt()) {
5794 // FIXME: It would be better to produce the diagnostic for casting
5795 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005796 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005797 return false;
5798 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005799 Result = Val.getInt();
5800 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005801}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005802
Richard Smithf57d8cb2011-12-09 22:58:01 +00005803/// Check whether the given declaration can be directly converted to an integral
5804/// rvalue. If not, no diagnostic is produced; there are other things we can
5805/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005806bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005807 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005808 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005809 // Check for signedness/width mismatches between E type and ECD value.
5810 bool SameSign = (ECD->getInitVal().isSigned()
5811 == E->getType()->isSignedIntegerOrEnumerationType());
5812 bool SameWidth = (ECD->getInitVal().getBitWidth()
5813 == Info.Ctx.getIntWidth(E->getType()));
5814 if (SameSign && SameWidth)
5815 return Success(ECD->getInitVal(), E);
5816 else {
5817 // Get rid of mismatch (otherwise Success assertions will fail)
5818 // by computing a new value matching the type of E.
5819 llvm::APSInt Val = ECD->getInitVal();
5820 if (!SameSign)
5821 Val.setIsSigned(!ECD->getInitVal().isSigned());
5822 if (!SameWidth)
5823 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5824 return Success(Val, E);
5825 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005826 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005827 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005828}
5829
Chris Lattner86ee2862008-10-06 06:40:35 +00005830/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5831/// as GCC.
5832static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5833 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005834 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005835 enum gcc_type_class {
5836 no_type_class = -1,
5837 void_type_class, integer_type_class, char_type_class,
5838 enumeral_type_class, boolean_type_class,
5839 pointer_type_class, reference_type_class, offset_type_class,
5840 real_type_class, complex_type_class,
5841 function_type_class, method_type_class,
5842 record_type_class, union_type_class,
5843 array_type_class, string_type_class,
5844 lang_type_class
5845 };
Mike Stump11289f42009-09-09 15:08:12 +00005846
5847 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005848 // ideal, however it is what gcc does.
5849 if (E->getNumArgs() == 0)
5850 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005851
Chris Lattner86ee2862008-10-06 06:40:35 +00005852 QualType ArgTy = E->getArg(0)->getType();
5853 if (ArgTy->isVoidType())
5854 return void_type_class;
5855 else if (ArgTy->isEnumeralType())
5856 return enumeral_type_class;
5857 else if (ArgTy->isBooleanType())
5858 return boolean_type_class;
5859 else if (ArgTy->isCharType())
5860 return string_type_class; // gcc doesn't appear to use char_type_class
5861 else if (ArgTy->isIntegerType())
5862 return integer_type_class;
5863 else if (ArgTy->isPointerType())
5864 return pointer_type_class;
5865 else if (ArgTy->isReferenceType())
5866 return reference_type_class;
5867 else if (ArgTy->isRealType())
5868 return real_type_class;
5869 else if (ArgTy->isComplexType())
5870 return complex_type_class;
5871 else if (ArgTy->isFunctionType())
5872 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005873 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005874 return record_type_class;
5875 else if (ArgTy->isUnionType())
5876 return union_type_class;
5877 else if (ArgTy->isArrayType())
5878 return array_type_class;
5879 else if (ArgTy->isUnionType())
5880 return union_type_class;
5881 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005882 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005883}
5884
Richard Smith5fab0c92011-12-28 19:48:30 +00005885/// EvaluateBuiltinConstantPForLValue - Determine the result of
5886/// __builtin_constant_p when applied to the given lvalue.
5887///
5888/// An lvalue is only "constant" if it is a pointer or reference to the first
5889/// character of a string literal.
5890template<typename LValue>
5891static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005892 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005893 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5894}
5895
5896/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5897/// GCC as we can manage.
5898static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5899 QualType ArgType = Arg->getType();
5900
5901 // __builtin_constant_p always has one operand. The rules which gcc follows
5902 // are not precisely documented, but are as follows:
5903 //
5904 // - If the operand is of integral, floating, complex or enumeration type,
5905 // and can be folded to a known value of that type, it returns 1.
5906 // - If the operand and can be folded to a pointer to the first character
5907 // of a string literal (or such a pointer cast to an integral type), it
5908 // returns 1.
5909 //
5910 // Otherwise, it returns 0.
5911 //
5912 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5913 // its support for this does not currently work.
5914 if (ArgType->isIntegralOrEnumerationType()) {
5915 Expr::EvalResult Result;
5916 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5917 return false;
5918
5919 APValue &V = Result.Val;
5920 if (V.getKind() == APValue::Int)
5921 return true;
5922
5923 return EvaluateBuiltinConstantPForLValue(V);
5924 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5925 return Arg->isEvaluatable(Ctx);
5926 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5927 LValue LV;
5928 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005929 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005930 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5931 : EvaluatePointer(Arg, LV, Info)) &&
5932 !Status.HasSideEffects)
5933 return EvaluateBuiltinConstantPForLValue(LV);
5934 }
5935
5936 // Anything else isn't considered to be sufficiently constant.
5937 return false;
5938}
5939
John McCall95007602010-05-10 23:27:23 +00005940/// Retrieves the "underlying object type" of the given expression,
5941/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005942QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5944 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005945 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005946 } else if (const Expr *E = B.get<const Expr*>()) {
5947 if (isa<CompoundLiteralExpr>(E))
5948 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005949 }
5950
5951 return QualType();
5952}
5953
Peter Collingbournee9200682011-05-13 03:29:01 +00005954bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005955 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005956
5957 {
5958 // The operand of __builtin_object_size is never evaluated for side-effects.
5959 // If there are any, but we can determine the pointed-to object anyway, then
5960 // ignore the side-effects.
5961 SpeculativeEvaluationRAII SpeculativeEval(Info);
5962 if (!EvaluatePointer(E->getArg(0), Base, Info))
5963 return false;
5964 }
John McCall95007602010-05-10 23:27:23 +00005965
5966 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005967 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005968
Richard Smithce40ad62011-11-12 22:28:03 +00005969 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005970 if (T.isNull() ||
5971 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005972 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005973 T->isVariablyModifiedType() ||
5974 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005975 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005976
5977 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5978 CharUnits Offset = Base.getLValueOffset();
5979
5980 if (!Offset.isNegative() && Offset <= Size)
5981 Size -= Offset;
5982 else
5983 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005984 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005985}
5986
Peter Collingbournee9200682011-05-13 03:29:01 +00005987bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00005988 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005989 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005990 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005991
5992 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005993 if (TryEvaluateBuiltinObjectSize(E))
5994 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005995
Richard Smith0421ce72012-08-07 04:16:51 +00005996 // If evaluating the argument has side-effects, we can't determine the size
5997 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5998 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005999 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006000 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006001 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006002 return Success(0, E);
6003 }
Mike Stump876387b2009-10-27 22:09:17 +00006004
Richard Smith01ade172012-05-23 04:13:20 +00006005 // Expression had no side effects, but we couldn't statically determine the
6006 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006007 switch (Info.EvalMode) {
6008 case EvalInfo::EM_ConstantExpression:
6009 case EvalInfo::EM_PotentialConstantExpression:
6010 case EvalInfo::EM_ConstantFold:
6011 case EvalInfo::EM_EvaluateForOverflow:
6012 case EvalInfo::EM_IgnoreSideEffects:
6013 return Error(E);
6014 case EvalInfo::EM_ConstantExpressionUnevaluated:
6015 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6016 return Success(-1ULL, E);
6017 }
Mike Stump722cedf2009-10-26 18:35:08 +00006018 }
6019
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006020 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006021 case Builtin::BI__builtin_bswap32:
6022 case Builtin::BI__builtin_bswap64: {
6023 APSInt Val;
6024 if (!EvaluateInteger(E->getArg(0), Val, Info))
6025 return false;
6026
6027 return Success(Val.byteSwap(), E);
6028 }
6029
Richard Smith8889a3d2013-06-13 06:26:32 +00006030 case Builtin::BI__builtin_classify_type:
6031 return Success(EvaluateBuiltinClassifyType(E), E);
6032
6033 // FIXME: BI__builtin_clrsb
6034 // FIXME: BI__builtin_clrsbl
6035 // FIXME: BI__builtin_clrsbll
6036
Richard Smith80b3c8e2013-06-13 05:04:16 +00006037 case Builtin::BI__builtin_clz:
6038 case Builtin::BI__builtin_clzl:
6039 case Builtin::BI__builtin_clzll: {
6040 APSInt Val;
6041 if (!EvaluateInteger(E->getArg(0), Val, Info))
6042 return false;
6043 if (!Val)
6044 return Error(E);
6045
6046 return Success(Val.countLeadingZeros(), E);
6047 }
6048
Richard Smith8889a3d2013-06-13 06:26:32 +00006049 case Builtin::BI__builtin_constant_p:
6050 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6051
Richard Smith80b3c8e2013-06-13 05:04:16 +00006052 case Builtin::BI__builtin_ctz:
6053 case Builtin::BI__builtin_ctzl:
6054 case Builtin::BI__builtin_ctzll: {
6055 APSInt Val;
6056 if (!EvaluateInteger(E->getArg(0), Val, Info))
6057 return false;
6058 if (!Val)
6059 return Error(E);
6060
6061 return Success(Val.countTrailingZeros(), E);
6062 }
6063
Richard Smith8889a3d2013-06-13 06:26:32 +00006064 case Builtin::BI__builtin_eh_return_data_regno: {
6065 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6066 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6067 return Success(Operand, E);
6068 }
6069
6070 case Builtin::BI__builtin_expect:
6071 return Visit(E->getArg(0));
6072
6073 case Builtin::BI__builtin_ffs:
6074 case Builtin::BI__builtin_ffsl:
6075 case Builtin::BI__builtin_ffsll: {
6076 APSInt Val;
6077 if (!EvaluateInteger(E->getArg(0), Val, Info))
6078 return false;
6079
6080 unsigned N = Val.countTrailingZeros();
6081 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6082 }
6083
6084 case Builtin::BI__builtin_fpclassify: {
6085 APFloat Val(0.0);
6086 if (!EvaluateFloat(E->getArg(5), Val, Info))
6087 return false;
6088 unsigned Arg;
6089 switch (Val.getCategory()) {
6090 case APFloat::fcNaN: Arg = 0; break;
6091 case APFloat::fcInfinity: Arg = 1; break;
6092 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6093 case APFloat::fcZero: Arg = 4; break;
6094 }
6095 return Visit(E->getArg(Arg));
6096 }
6097
6098 case Builtin::BI__builtin_isinf_sign: {
6099 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006100 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006101 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6102 }
6103
Richard Smithea3019d2013-10-15 19:07:14 +00006104 case Builtin::BI__builtin_isinf: {
6105 APFloat Val(0.0);
6106 return EvaluateFloat(E->getArg(0), Val, Info) &&
6107 Success(Val.isInfinity() ? 1 : 0, E);
6108 }
6109
6110 case Builtin::BI__builtin_isfinite: {
6111 APFloat Val(0.0);
6112 return EvaluateFloat(E->getArg(0), Val, Info) &&
6113 Success(Val.isFinite() ? 1 : 0, E);
6114 }
6115
6116 case Builtin::BI__builtin_isnan: {
6117 APFloat Val(0.0);
6118 return EvaluateFloat(E->getArg(0), Val, Info) &&
6119 Success(Val.isNaN() ? 1 : 0, E);
6120 }
6121
6122 case Builtin::BI__builtin_isnormal: {
6123 APFloat Val(0.0);
6124 return EvaluateFloat(E->getArg(0), Val, Info) &&
6125 Success(Val.isNormal() ? 1 : 0, E);
6126 }
6127
Richard Smith8889a3d2013-06-13 06:26:32 +00006128 case Builtin::BI__builtin_parity:
6129 case Builtin::BI__builtin_parityl:
6130 case Builtin::BI__builtin_parityll: {
6131 APSInt Val;
6132 if (!EvaluateInteger(E->getArg(0), Val, Info))
6133 return false;
6134
6135 return Success(Val.countPopulation() % 2, E);
6136 }
6137
Richard Smith80b3c8e2013-06-13 05:04:16 +00006138 case Builtin::BI__builtin_popcount:
6139 case Builtin::BI__builtin_popcountl:
6140 case Builtin::BI__builtin_popcountll: {
6141 APSInt Val;
6142 if (!EvaluateInteger(E->getArg(0), Val, Info))
6143 return false;
6144
6145 return Success(Val.countPopulation(), E);
6146 }
6147
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006148 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006149 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006150 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006151 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006152 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6153 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006154 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006155 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006156 case Builtin::BI__builtin_strlen: {
6157 // As an extension, we support __builtin_strlen() as a constant expression,
6158 // and support folding strlen() to a constant.
6159 LValue String;
6160 if (!EvaluatePointer(E->getArg(0), String, Info))
6161 return false;
6162
6163 // Fast path: if it's a string literal, search the string value.
6164 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6165 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006166 // The string literal may have embedded null characters. Find the first
6167 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006168 StringRef Str = S->getBytes();
6169 int64_t Off = String.Offset.getQuantity();
6170 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6171 S->getCharByteWidth() == 1) {
6172 Str = Str.substr(Off);
6173
6174 StringRef::size_type Pos = Str.find(0);
6175 if (Pos != StringRef::npos)
6176 Str = Str.substr(0, Pos);
6177
6178 return Success(Str.size(), E);
6179 }
6180
6181 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006182 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006183
6184 // Slow path: scan the bytes of the string looking for the terminating 0.
6185 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6186 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6187 APValue Char;
6188 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6189 !Char.isInt())
6190 return false;
6191 if (!Char.getInt())
6192 return Success(Strlen, E);
6193 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6194 return false;
6195 }
6196 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006197
Richard Smith01ba47d2012-04-13 00:45:38 +00006198 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006199 case Builtin::BI__atomic_is_lock_free:
6200 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006201 APSInt SizeVal;
6202 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6203 return false;
6204
6205 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6206 // of two less than the maximum inline atomic width, we know it is
6207 // lock-free. If the size isn't a power of two, or greater than the
6208 // maximum alignment where we promote atomics, we know it is not lock-free
6209 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6210 // the answer can only be determined at runtime; for example, 16-byte
6211 // atomics have lock-free implementations on some, but not all,
6212 // x86-64 processors.
6213
6214 // Check power-of-two.
6215 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006216 if (Size.isPowerOfTwo()) {
6217 // Check against inlining width.
6218 unsigned InlineWidthBits =
6219 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6220 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6221 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6222 Size == CharUnits::One() ||
6223 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6224 Expr::NPC_NeverValueDependent))
6225 // OK, we will inline appropriately-aligned operations of this size,
6226 // and _Atomic(T) is appropriately-aligned.
6227 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006228
Richard Smith01ba47d2012-04-13 00:45:38 +00006229 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6230 castAs<PointerType>()->getPointeeType();
6231 if (!PointeeType->isIncompleteType() &&
6232 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6233 // OK, we will inline operations on this object.
6234 return Success(1, E);
6235 }
6236 }
6237 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006238
Richard Smith01ba47d2012-04-13 00:45:38 +00006239 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6240 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006241 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006242 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006243}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006244
Richard Smith8b3497e2011-10-31 01:37:14 +00006245static bool HasSameBase(const LValue &A, const LValue &B) {
6246 if (!A.getLValueBase())
6247 return !B.getLValueBase();
6248 if (!B.getLValueBase())
6249 return false;
6250
Richard Smithce40ad62011-11-12 22:28:03 +00006251 if (A.getLValueBase().getOpaqueValue() !=
6252 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006253 const Decl *ADecl = GetLValueBaseDecl(A);
6254 if (!ADecl)
6255 return false;
6256 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006257 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006258 return false;
6259 }
6260
6261 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006262 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006263}
6264
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006265namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006266
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006267/// \brief Data recursive integer evaluator of certain binary operators.
6268///
6269/// We use a data recursive algorithm for binary operators so that we are able
6270/// to handle extreme cases of chained binary operators without causing stack
6271/// overflow.
6272class DataRecursiveIntBinOpEvaluator {
6273 struct EvalResult {
6274 APValue Val;
6275 bool Failed;
6276
6277 EvalResult() : Failed(false) { }
6278
6279 void swap(EvalResult &RHS) {
6280 Val.swap(RHS.Val);
6281 Failed = RHS.Failed;
6282 RHS.Failed = false;
6283 }
6284 };
6285
6286 struct Job {
6287 const Expr *E;
6288 EvalResult LHSResult; // meaningful only for binary operator expression.
6289 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006290
6291 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006292 void startSpeculativeEval(EvalInfo &Info) {
6293 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006294 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006295 StoredInfo = &Info;
6296 }
6297 ~Job() {
6298 if (StoredInfo) {
6299 StoredInfo->EvalStatus = OldEvalStatus;
6300 }
6301 }
6302 private:
6303 EvalInfo *StoredInfo; // non-null if status changed.
6304 Expr::EvalStatus OldEvalStatus;
6305 };
6306
6307 SmallVector<Job, 16> Queue;
6308
6309 IntExprEvaluator &IntEval;
6310 EvalInfo &Info;
6311 APValue &FinalResult;
6312
6313public:
6314 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6315 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6316
6317 /// \brief True if \param E is a binary operator that we are going to handle
6318 /// data recursively.
6319 /// We handle binary operators that are comma, logical, or that have operands
6320 /// with integral or enumeration type.
6321 static bool shouldEnqueue(const BinaryOperator *E) {
6322 return E->getOpcode() == BO_Comma ||
6323 E->isLogicalOp() ||
6324 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6325 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006326 }
6327
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006328 bool Traverse(const BinaryOperator *E) {
6329 enqueue(E);
6330 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006331 while (!Queue.empty())
6332 process(PrevResult);
6333
6334 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006335
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006336 FinalResult.swap(PrevResult.Val);
6337 return true;
6338 }
6339
6340private:
6341 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6342 return IntEval.Success(Value, E, Result);
6343 }
6344 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6345 return IntEval.Success(Value, E, Result);
6346 }
6347 bool Error(const Expr *E) {
6348 return IntEval.Error(E);
6349 }
6350 bool Error(const Expr *E, diag::kind D) {
6351 return IntEval.Error(E, D);
6352 }
6353
6354 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6355 return Info.CCEDiag(E, D);
6356 }
6357
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006358 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6359 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006360 bool &SuppressRHSDiags);
6361
6362 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6363 const BinaryOperator *E, APValue &Result);
6364
6365 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6366 Result.Failed = !Evaluate(Result.Val, Info, E);
6367 if (Result.Failed)
6368 Result.Val = APValue();
6369 }
6370
Richard Trieuba4d0872012-03-21 23:30:30 +00006371 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006372
6373 void enqueue(const Expr *E) {
6374 E = E->IgnoreParens();
6375 Queue.resize(Queue.size()+1);
6376 Queue.back().E = E;
6377 Queue.back().Kind = Job::AnyExprKind;
6378 }
6379};
6380
6381}
6382
6383bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006384 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006385 bool &SuppressRHSDiags) {
6386 if (E->getOpcode() == BO_Comma) {
6387 // Ignore LHS but note if we could not evaluate it.
6388 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006389 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006390 return true;
6391 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006393 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006394 bool LHSAsBool;
6395 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006396 // We were able to evaluate the LHS, see if we can get away with not
6397 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006398 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6399 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006400 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006401 }
6402 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006403 LHSResult.Failed = true;
6404
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006405 // Since we weren't able to evaluate the left hand side, it
6406 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006407 if (!Info.noteSideEffect())
6408 return false;
6409
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410 // We can't evaluate the LHS; however, sometimes the result
6411 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6412 // Don't ignore RHS and suppress diagnostics from this arm.
6413 SuppressRHSDiags = true;
6414 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006415
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006416 return true;
6417 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006418
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006419 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6420 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006421
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006422 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006423 return false; // Ignore RHS;
6424
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006425 return true;
6426}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006427
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006428bool DataRecursiveIntBinOpEvaluator::
6429 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6430 const BinaryOperator *E, APValue &Result) {
6431 if (E->getOpcode() == BO_Comma) {
6432 if (RHSResult.Failed)
6433 return false;
6434 Result = RHSResult.Val;
6435 return true;
6436 }
6437
6438 if (E->isLogicalOp()) {
6439 bool lhsResult, rhsResult;
6440 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6441 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6442
6443 if (LHSIsOK) {
6444 if (RHSIsOK) {
6445 if (E->getOpcode() == BO_LOr)
6446 return Success(lhsResult || rhsResult, E, Result);
6447 else
6448 return Success(lhsResult && rhsResult, E, Result);
6449 }
6450 } else {
6451 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006452 // We can't evaluate the LHS; however, sometimes the result
6453 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6454 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006455 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006456 }
6457 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006458
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006459 return false;
6460 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006461
6462 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6463 E->getRHS()->getType()->isIntegralOrEnumerationType());
6464
6465 if (LHSResult.Failed || RHSResult.Failed)
6466 return false;
6467
6468 const APValue &LHSVal = LHSResult.Val;
6469 const APValue &RHSVal = RHSResult.Val;
6470
6471 // Handle cases like (unsigned long)&a + 4.
6472 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6473 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006474 CharUnits AdditionalOffset =
6475 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006476 if (E->getOpcode() == BO_Add)
6477 Result.getLValueOffset() += AdditionalOffset;
6478 else
6479 Result.getLValueOffset() -= AdditionalOffset;
6480 return true;
6481 }
6482
6483 // Handle cases like 4 + (unsigned long)&a
6484 if (E->getOpcode() == BO_Add &&
6485 RHSVal.isLValue() && LHSVal.isInt()) {
6486 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006487 Result.getLValueOffset() +=
6488 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006489 return true;
6490 }
6491
6492 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6493 // Handle (intptr_t)&&A - (intptr_t)&&B.
6494 if (!LHSVal.getLValueOffset().isZero() ||
6495 !RHSVal.getLValueOffset().isZero())
6496 return false;
6497 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6498 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6499 if (!LHSExpr || !RHSExpr)
6500 return false;
6501 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6502 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6503 if (!LHSAddrExpr || !RHSAddrExpr)
6504 return false;
6505 // Make sure both labels come from the same function.
6506 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6507 RHSAddrExpr->getLabel()->getDeclContext())
6508 return false;
6509 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6510 return true;
6511 }
Richard Smith43e77732013-05-07 04:50:00 +00006512
6513 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006514 if (!LHSVal.isInt() || !RHSVal.isInt())
6515 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006516
6517 // Set up the width and signedness manually, in case it can't be deduced
6518 // from the operation we're performing.
6519 // FIXME: Don't do this in the cases where we can deduce it.
6520 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6521 E->getType()->isUnsignedIntegerOrEnumerationType());
6522 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6523 RHSVal.getInt(), Value))
6524 return false;
6525 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006526}
6527
Richard Trieuba4d0872012-03-21 23:30:30 +00006528void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006529 Job &job = Queue.back();
6530
6531 switch (job.Kind) {
6532 case Job::AnyExprKind: {
6533 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6534 if (shouldEnqueue(Bop)) {
6535 job.Kind = Job::BinOpKind;
6536 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006537 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006538 }
6539 }
6540
6541 EvaluateExpr(job.E, Result);
6542 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006543 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006544 }
6545
6546 case Job::BinOpKind: {
6547 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006548 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006549 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006550 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006551 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006552 }
6553 if (SuppressRHSDiags)
6554 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006555 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006556 job.Kind = Job::BinOpVisitedLHSKind;
6557 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006558 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006559 }
6560
6561 case Job::BinOpVisitedLHSKind: {
6562 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6563 EvalResult RHS;
6564 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006565 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006566 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006567 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006568 }
6569 }
6570
6571 llvm_unreachable("Invalid Job::Kind!");
6572}
6573
6574bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6575 if (E->isAssignmentOp())
6576 return Error(E);
6577
6578 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6579 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006580
Anders Carlssonacc79812008-11-16 07:17:21 +00006581 QualType LHSTy = E->getLHS()->getType();
6582 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006583
6584 if (LHSTy->isAnyComplexType()) {
6585 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006586 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006587
Richard Smith253c2a32012-01-27 01:14:48 +00006588 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6589 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006590 return false;
6591
Richard Smith253c2a32012-01-27 01:14:48 +00006592 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006593 return false;
6594
6595 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006596 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006597 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006598 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006599 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6600
John McCalle3027922010-08-25 11:45:40 +00006601 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006602 return Success((CR_r == APFloat::cmpEqual &&
6603 CR_i == APFloat::cmpEqual), E);
6604 else {
John McCalle3027922010-08-25 11:45:40 +00006605 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006606 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006607 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006608 CR_r == APFloat::cmpLessThan ||
6609 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006610 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006611 CR_i == APFloat::cmpLessThan ||
6612 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006613 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006614 } else {
John McCalle3027922010-08-25 11:45:40 +00006615 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006616 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6617 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6618 else {
John McCalle3027922010-08-25 11:45:40 +00006619 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006620 "Invalid compex comparison.");
6621 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6622 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6623 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006624 }
6625 }
Mike Stump11289f42009-09-09 15:08:12 +00006626
Anders Carlssonacc79812008-11-16 07:17:21 +00006627 if (LHSTy->isRealFloatingType() &&
6628 RHSTy->isRealFloatingType()) {
6629 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006630
Richard Smith253c2a32012-01-27 01:14:48 +00006631 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6632 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006633 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006634
Richard Smith253c2a32012-01-27 01:14:48 +00006635 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006636 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006637
Anders Carlssonacc79812008-11-16 07:17:21 +00006638 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006639
Anders Carlssonacc79812008-11-16 07:17:21 +00006640 switch (E->getOpcode()) {
6641 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006642 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006643 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006644 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006645 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006646 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006647 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006648 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006649 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006650 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006651 E);
John McCalle3027922010-08-25 11:45:40 +00006652 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006653 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006654 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006655 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006656 || CR == APFloat::cmpLessThan
6657 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006658 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006659 }
Mike Stump11289f42009-09-09 15:08:12 +00006660
Eli Friedmana38da572009-04-28 19:17:36 +00006661 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006662 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006663 LValue LHSValue, RHSValue;
6664
6665 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6666 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006667 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006668
Richard Smith253c2a32012-01-27 01:14:48 +00006669 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006670 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006671
Richard Smith8b3497e2011-10-31 01:37:14 +00006672 // Reject differing bases from the normal codepath; we special-case
6673 // comparisons to null.
6674 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006675 if (E->getOpcode() == BO_Sub) {
6676 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006677 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6678 return false;
6679 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006680 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006681 if (!LHSExpr || !RHSExpr)
6682 return false;
6683 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6684 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6685 if (!LHSAddrExpr || !RHSAddrExpr)
6686 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006687 // Make sure both labels come from the same function.
6688 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6689 RHSAddrExpr->getLabel()->getDeclContext())
6690 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006691 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006692 return true;
6693 }
Richard Smith83c68212011-10-31 05:11:32 +00006694 // Inequalities and subtractions between unrelated pointers have
6695 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006696 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006697 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006698 // A constant address may compare equal to the address of a symbol.
6699 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006700 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006701 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6702 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006703 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006704 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006705 // distinct addresses. In clang, the result of such a comparison is
6706 // unspecified, so it is not a constant expression. However, we do know
6707 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006708 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6709 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006710 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006711 // We can't tell whether weak symbols will end up pointing to the same
6712 // object.
6713 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006714 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006715 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006716 // (Note that clang defaults to -fmerge-all-constants, which can
6717 // lead to inconsistent results for comparisons involving the address
6718 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006719 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006720 }
Eli Friedman64004332009-03-23 04:38:34 +00006721
Richard Smith1b470412012-02-01 08:10:20 +00006722 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6723 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6724
Richard Smith84f6dcf2012-02-02 01:16:57 +00006725 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6726 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6727
John McCalle3027922010-08-25 11:45:40 +00006728 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006729 // C++11 [expr.add]p6:
6730 // Unless both pointers point to elements of the same array object, or
6731 // one past the last element of the array object, the behavior is
6732 // undefined.
6733 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6734 !AreElementsOfSameArray(getType(LHSValue.Base),
6735 LHSDesignator, RHSDesignator))
6736 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6737
Chris Lattner882bdf22010-04-20 17:13:14 +00006738 QualType Type = E->getLHS()->getType();
6739 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006740
Richard Smithd62306a2011-11-10 06:34:14 +00006741 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006742 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006743 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006744
Richard Smith84c6b3d2013-09-10 21:34:14 +00006745 // As an extension, a type may have zero size (empty struct or union in
6746 // C, array of zero length). Pointer subtraction in such cases has
6747 // undefined behavior, so is not constant.
6748 if (ElementSize.isZero()) {
6749 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6750 << ElementType;
6751 return false;
6752 }
6753
Richard Smith1b470412012-02-01 08:10:20 +00006754 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6755 // and produce incorrect results when it overflows. Such behavior
6756 // appears to be non-conforming, but is common, so perhaps we should
6757 // assume the standard intended for such cases to be undefined behavior
6758 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006759
Richard Smith1b470412012-02-01 08:10:20 +00006760 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6761 // overflow in the final conversion to ptrdiff_t.
6762 APSInt LHS(
6763 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6764 APSInt RHS(
6765 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6766 APSInt ElemSize(
6767 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6768 APSInt TrueResult = (LHS - RHS) / ElemSize;
6769 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6770
6771 if (Result.extend(65) != TrueResult)
6772 HandleOverflow(Info, E, TrueResult, E->getType());
6773 return Success(Result, E);
6774 }
Richard Smithde21b242012-01-31 06:41:30 +00006775
6776 // C++11 [expr.rel]p3:
6777 // Pointers to void (after pointer conversions) can be compared, with a
6778 // result defined as follows: If both pointers represent the same
6779 // address or are both the null pointer value, the result is true if the
6780 // operator is <= or >= and false otherwise; otherwise the result is
6781 // unspecified.
6782 // We interpret this as applying to pointers to *cv* void.
6783 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006784 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006785 CCEDiag(E, diag::note_constexpr_void_comparison);
6786
Richard Smith84f6dcf2012-02-02 01:16:57 +00006787 // C++11 [expr.rel]p2:
6788 // - If two pointers point to non-static data members of the same object,
6789 // or to subobjects or array elements fo such members, recursively, the
6790 // pointer to the later declared member compares greater provided the
6791 // two members have the same access control and provided their class is
6792 // not a union.
6793 // [...]
6794 // - Otherwise pointer comparisons are unspecified.
6795 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6796 E->isRelationalOp()) {
6797 bool WasArrayIndex;
6798 unsigned Mismatch =
6799 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6800 RHSDesignator, WasArrayIndex);
6801 // At the point where the designators diverge, the comparison has a
6802 // specified value if:
6803 // - we are comparing array indices
6804 // - we are comparing fields of a union, or fields with the same access
6805 // Otherwise, the result is unspecified and thus the comparison is not a
6806 // constant expression.
6807 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6808 Mismatch < RHSDesignator.Entries.size()) {
6809 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6810 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6811 if (!LF && !RF)
6812 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6813 else if (!LF)
6814 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6815 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6816 << RF->getParent() << RF;
6817 else if (!RF)
6818 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6819 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6820 << LF->getParent() << LF;
6821 else if (!LF->getParent()->isUnion() &&
6822 LF->getAccess() != RF->getAccess())
6823 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6824 << LF << LF->getAccess() << RF << RF->getAccess()
6825 << LF->getParent();
6826 }
6827 }
6828
Eli Friedman6c31cb42012-04-16 04:30:08 +00006829 // The comparison here must be unsigned, and performed with the same
6830 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006831 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6832 uint64_t CompareLHS = LHSOffset.getQuantity();
6833 uint64_t CompareRHS = RHSOffset.getQuantity();
6834 assert(PtrSize <= 64 && "Unexpected pointer width");
6835 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6836 CompareLHS &= Mask;
6837 CompareRHS &= Mask;
6838
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006839 // If there is a base and this is a relational operator, we can only
6840 // compare pointers within the object in question; otherwise, the result
6841 // depends on where the object is located in memory.
6842 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6843 QualType BaseTy = getType(LHSValue.Base);
6844 if (BaseTy->isIncompleteType())
6845 return Error(E);
6846 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6847 uint64_t OffsetLimit = Size.getQuantity();
6848 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6849 return Error(E);
6850 }
6851
Richard Smith8b3497e2011-10-31 01:37:14 +00006852 switch (E->getOpcode()) {
6853 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006854 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6855 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6856 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6857 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6858 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6859 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006860 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006861 }
6862 }
Richard Smith7bb00672012-02-01 01:42:44 +00006863
6864 if (LHSTy->isMemberPointerType()) {
6865 assert(E->isEqualityOp() && "unexpected member pointer operation");
6866 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6867
6868 MemberPtr LHSValue, RHSValue;
6869
6870 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6871 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6872 return false;
6873
6874 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6875 return false;
6876
6877 // C++11 [expr.eq]p2:
6878 // If both operands are null, they compare equal. Otherwise if only one is
6879 // null, they compare unequal.
6880 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6881 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6882 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6883 }
6884
6885 // Otherwise if either is a pointer to a virtual member function, the
6886 // result is unspecified.
6887 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6888 if (MD->isVirtual())
6889 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6890 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6891 if (MD->isVirtual())
6892 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6893
6894 // Otherwise they compare equal if and only if they would refer to the
6895 // same member of the same most derived object or the same subobject if
6896 // they were dereferenced with a hypothetical object of the associated
6897 // class type.
6898 bool Equal = LHSValue == RHSValue;
6899 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6900 }
6901
Richard Smithab44d9b2012-02-14 22:35:28 +00006902 if (LHSTy->isNullPtrType()) {
6903 assert(E->isComparisonOp() && "unexpected nullptr operation");
6904 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6905 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6906 // are compared, the result is true of the operator is <=, >= or ==, and
6907 // false otherwise.
6908 BinaryOperator::Opcode Opcode = E->getOpcode();
6909 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6910 }
6911
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006912 assert((!LHSTy->isIntegralOrEnumerationType() ||
6913 !RHSTy->isIntegralOrEnumerationType()) &&
6914 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6915 // We can't continue from here for non-integral types.
6916 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006917}
6918
Ken Dyck160146e2010-01-27 17:10:57 +00006919CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Richard Smithf6d70302014-06-10 23:34:28 +00006920 // C++ [expr.alignof]p3:
6921 // When alignof is applied to a reference type, the result is the
6922 // alignment of the referenced type.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006923 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6924 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006925
6926 // __alignof is defined to return the preferred alignment.
6927 return Info.Ctx.toCharUnitsFromBits(
6928 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006929}
6930
Ken Dyck160146e2010-01-27 17:10:57 +00006931CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006932 E = E->IgnoreParens();
6933
John McCall768439e2013-05-06 07:40:34 +00006934 // The kinds of expressions that we have special-case logic here for
6935 // should be kept up to date with the special checks for those
6936 // expressions in Sema.
6937
Chris Lattner68061312009-01-24 21:53:27 +00006938 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006939 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006940 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithf6d70302014-06-10 23:34:28 +00006941 return Info.Ctx.getDeclAlign(DRE->getDecl(),
Ken Dyck160146e2010-01-27 17:10:57 +00006942 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006943
Chris Lattner68061312009-01-24 21:53:27 +00006944 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006945 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6946 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006947
Chris Lattner24aeeab2009-01-24 21:09:06 +00006948 return GetAlignOfType(E->getType());
6949}
6950
6951
Peter Collingbournee190dee2011-03-11 19:24:49 +00006952/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6953/// a result as the expression's type.
6954bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6955 const UnaryExprOrTypeTraitExpr *E) {
6956 switch(E->getKind()) {
6957 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006958 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006959 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006960 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006961 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006962 }
Eli Friedman64004332009-03-23 04:38:34 +00006963
Peter Collingbournee190dee2011-03-11 19:24:49 +00006964 case UETT_VecStep: {
6965 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006966
Peter Collingbournee190dee2011-03-11 19:24:49 +00006967 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006968 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006969
Peter Collingbournee190dee2011-03-11 19:24:49 +00006970 // The vec_step built-in functions that take a 3-component
6971 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6972 if (n == 3)
6973 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006974
Peter Collingbournee190dee2011-03-11 19:24:49 +00006975 return Success(n, E);
6976 } else
6977 return Success(1, E);
6978 }
6979
6980 case UETT_SizeOf: {
6981 QualType SrcTy = E->getTypeOfArgument();
6982 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6983 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006984 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6985 SrcTy = Ref->getPointeeType();
6986
Richard Smithd62306a2011-11-10 06:34:14 +00006987 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006988 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006989 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006990 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006991 }
6992 }
6993
6994 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006995}
6996
Peter Collingbournee9200682011-05-13 03:29:01 +00006997bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006998 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006999 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007000 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007001 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007002 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007003 for (unsigned i = 0; i != n; ++i) {
7004 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7005 switch (ON.getKind()) {
7006 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007007 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007008 APSInt IdxResult;
7009 if (!EvaluateInteger(Idx, IdxResult, Info))
7010 return false;
7011 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7012 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007013 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007014 CurrentType = AT->getElementType();
7015 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7016 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007017 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007018 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007019
Douglas Gregor882211c2010-04-28 22:16:22 +00007020 case OffsetOfExpr::OffsetOfNode::Field: {
7021 FieldDecl *MemberDecl = ON.getField();
7022 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007023 if (!RT)
7024 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007025 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007026 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007027 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007028 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007029 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007030 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007031 CurrentType = MemberDecl->getType().getNonReferenceType();
7032 break;
7033 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007034
Douglas Gregor882211c2010-04-28 22:16:22 +00007035 case OffsetOfExpr::OffsetOfNode::Identifier:
7036 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007037
Douglas Gregord1702062010-04-29 00:18:15 +00007038 case OffsetOfExpr::OffsetOfNode::Base: {
7039 CXXBaseSpecifier *BaseSpec = ON.getBase();
7040 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007041 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007042
7043 // Find the layout of the class whose base we are looking into.
7044 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007045 if (!RT)
7046 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007047 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007048 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007049 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7050
7051 // Find the base class itself.
7052 CurrentType = BaseSpec->getType();
7053 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7054 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007055 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007056
7057 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007058 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007059 break;
7060 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007061 }
7062 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007063 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007064}
7065
Chris Lattnere13042c2008-07-11 19:10:17 +00007066bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007067 switch (E->getOpcode()) {
7068 default:
7069 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7070 // See C99 6.6p3.
7071 return Error(E);
7072 case UO_Extension:
7073 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7074 // If so, we could clear the diagnostic ID.
7075 return Visit(E->getSubExpr());
7076 case UO_Plus:
7077 // The result is just the value.
7078 return Visit(E->getSubExpr());
7079 case UO_Minus: {
7080 if (!Visit(E->getSubExpr()))
7081 return false;
7082 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007083 const APSInt &Value = Result.getInt();
7084 if (Value.isSigned() && Value.isMinSignedValue())
7085 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7086 E->getType());
7087 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007088 }
7089 case UO_Not: {
7090 if (!Visit(E->getSubExpr()))
7091 return false;
7092 if (!Result.isInt()) return Error(E);
7093 return Success(~Result.getInt(), E);
7094 }
7095 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007096 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007097 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007098 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007099 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007100 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007101 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007102}
Mike Stump11289f42009-09-09 15:08:12 +00007103
Chris Lattner477c4be2008-07-12 01:15:53 +00007104/// HandleCast - This is used to evaluate implicit or explicit casts where the
7105/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007106bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7107 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007108 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007109 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007110
Eli Friedmanc757de22011-03-25 00:43:55 +00007111 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007112 case CK_BaseToDerived:
7113 case CK_DerivedToBase:
7114 case CK_UncheckedDerivedToBase:
7115 case CK_Dynamic:
7116 case CK_ToUnion:
7117 case CK_ArrayToPointerDecay:
7118 case CK_FunctionToPointerDecay:
7119 case CK_NullToPointer:
7120 case CK_NullToMemberPointer:
7121 case CK_BaseToDerivedMemberPointer:
7122 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007123 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007124 case CK_ConstructorConversion:
7125 case CK_IntegralToPointer:
7126 case CK_ToVoid:
7127 case CK_VectorSplat:
7128 case CK_IntegralToFloating:
7129 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007130 case CK_CPointerToObjCPointerCast:
7131 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007132 case CK_AnyPointerToBlockPointerCast:
7133 case CK_ObjCObjectLValueCast:
7134 case CK_FloatingRealToComplex:
7135 case CK_FloatingComplexToReal:
7136 case CK_FloatingComplexCast:
7137 case CK_FloatingComplexToIntegralComplex:
7138 case CK_IntegralRealToComplex:
7139 case CK_IntegralComplexCast:
7140 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007141 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007142 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007143 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007144 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007145 llvm_unreachable("invalid cast kind for integral value");
7146
Eli Friedman9faf2f92011-03-25 19:07:11 +00007147 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007148 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007149 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007150 case CK_ARCProduceObject:
7151 case CK_ARCConsumeObject:
7152 case CK_ARCReclaimReturnedObject:
7153 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007154 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007155 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007156
Richard Smith4ef685b2012-01-17 21:17:26 +00007157 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007158 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007159 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007160 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007161 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007162
7163 case CK_MemberPointerToBoolean:
7164 case CK_PointerToBoolean:
7165 case CK_IntegralToBoolean:
7166 case CK_FloatingToBoolean:
7167 case CK_FloatingComplexToBoolean:
7168 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007169 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007170 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007171 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007172 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007173 }
7174
Eli Friedmanc757de22011-03-25 00:43:55 +00007175 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007176 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007177 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007178
Eli Friedman742421e2009-02-20 01:15:07 +00007179 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007180 // Allow casts of address-of-label differences if they are no-ops
7181 // or narrowing. (The narrowing case isn't actually guaranteed to
7182 // be constant-evaluatable except in some narrow cases which are hard
7183 // to detect here. We let it through on the assumption the user knows
7184 // what they are doing.)
7185 if (Result.isAddrLabelDiff())
7186 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007187 // Only allow casts of lvalues if they are lossless.
7188 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7189 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007190
Richard Smith911e1422012-01-30 22:27:01 +00007191 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7192 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007193 }
Mike Stump11289f42009-09-09 15:08:12 +00007194
Eli Friedmanc757de22011-03-25 00:43:55 +00007195 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007196 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7197
John McCall45d55e42010-05-07 21:00:08 +00007198 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007199 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007200 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007201
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007202 if (LV.getLValueBase()) {
7203 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007204 // FIXME: Allow a larger integer size than the pointer size, and allow
7205 // narrowing back down to pointer width in subsequent integral casts.
7206 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007207 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007208 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007209
Richard Smithcf74da72011-11-16 07:18:12 +00007210 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007211 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007212 return true;
7213 }
7214
Ken Dyck02990832010-01-15 12:37:54 +00007215 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7216 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007217 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007218 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007219
Eli Friedmanc757de22011-03-25 00:43:55 +00007220 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007221 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007222 if (!EvaluateComplex(SubExpr, C, Info))
7223 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007224 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007225 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007226
Eli Friedmanc757de22011-03-25 00:43:55 +00007227 case CK_FloatingToIntegral: {
7228 APFloat F(0.0);
7229 if (!EvaluateFloat(SubExpr, F, Info))
7230 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007231
Richard Smith357362d2011-12-13 06:39:58 +00007232 APSInt Value;
7233 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7234 return false;
7235 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007236 }
7237 }
Mike Stump11289f42009-09-09 15:08:12 +00007238
Eli Friedmanc757de22011-03-25 00:43:55 +00007239 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007240}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007241
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007242bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7243 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007244 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007245 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7246 return false;
7247 if (!LV.isComplexInt())
7248 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007249 return Success(LV.getComplexIntReal(), E);
7250 }
7251
7252 return Visit(E->getSubExpr());
7253}
7254
Eli Friedman4e7a2412009-02-27 04:45:43 +00007255bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007256 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007257 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007258 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7259 return false;
7260 if (!LV.isComplexInt())
7261 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007262 return Success(LV.getComplexIntImag(), E);
7263 }
7264
Richard Smith4a678122011-10-24 18:44:57 +00007265 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007266 return Success(0, E);
7267}
7268
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007269bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7270 return Success(E->getPackLength(), E);
7271}
7272
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007273bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7274 return Success(E->getValue(), E);
7275}
7276
Chris Lattner05706e882008-07-11 18:11:29 +00007277//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007278// Float Evaluation
7279//===----------------------------------------------------------------------===//
7280
7281namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007282class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007283 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007284 APFloat &Result;
7285public:
7286 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007287 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007288
Richard Smith2e312c82012-03-03 22:46:17 +00007289 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007290 Result = V.getFloat();
7291 return true;
7292 }
Eli Friedman24c01542008-08-22 00:06:13 +00007293
Richard Smithfddd3842011-12-30 21:15:51 +00007294 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007295 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7296 return true;
7297 }
7298
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007299 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007300
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007301 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007302 bool VisitBinaryOperator(const BinaryOperator *E);
7303 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007304 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007305
John McCallb1fb0d32010-05-07 22:08:54 +00007306 bool VisitUnaryReal(const UnaryOperator *E);
7307 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007308
Richard Smithfddd3842011-12-30 21:15:51 +00007309 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007310};
7311} // end anonymous namespace
7312
7313static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007314 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007315 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007316}
7317
Jay Foad39c79802011-01-12 09:06:06 +00007318static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007319 QualType ResultTy,
7320 const Expr *Arg,
7321 bool SNaN,
7322 llvm::APFloat &Result) {
7323 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7324 if (!S) return false;
7325
7326 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7327
7328 llvm::APInt fill;
7329
7330 // Treat empty strings as if they were zero.
7331 if (S->getString().empty())
7332 fill = llvm::APInt(32, 0);
7333 else if (S->getString().getAsInteger(0, fill))
7334 return false;
7335
7336 if (SNaN)
7337 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7338 else
7339 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7340 return true;
7341}
7342
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007343bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007344 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007345 default:
7346 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7347
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007348 case Builtin::BI__builtin_huge_val:
7349 case Builtin::BI__builtin_huge_valf:
7350 case Builtin::BI__builtin_huge_vall:
7351 case Builtin::BI__builtin_inf:
7352 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007353 case Builtin::BI__builtin_infl: {
7354 const llvm::fltSemantics &Sem =
7355 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007356 Result = llvm::APFloat::getInf(Sem);
7357 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007358 }
Mike Stump11289f42009-09-09 15:08:12 +00007359
John McCall16291492010-02-28 13:00:19 +00007360 case Builtin::BI__builtin_nans:
7361 case Builtin::BI__builtin_nansf:
7362 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007363 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7364 true, Result))
7365 return Error(E);
7366 return true;
John McCall16291492010-02-28 13:00:19 +00007367
Chris Lattner0b7282e2008-10-06 06:31:58 +00007368 case Builtin::BI__builtin_nan:
7369 case Builtin::BI__builtin_nanf:
7370 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007371 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007372 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007373 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7374 false, Result))
7375 return Error(E);
7376 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007377
7378 case Builtin::BI__builtin_fabs:
7379 case Builtin::BI__builtin_fabsf:
7380 case Builtin::BI__builtin_fabsl:
7381 if (!EvaluateFloat(E->getArg(0), Result, Info))
7382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007383
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007384 if (Result.isNegative())
7385 Result.changeSign();
7386 return true;
7387
Richard Smith8889a3d2013-06-13 06:26:32 +00007388 // FIXME: Builtin::BI__builtin_powi
7389 // FIXME: Builtin::BI__builtin_powif
7390 // FIXME: Builtin::BI__builtin_powil
7391
Mike Stump11289f42009-09-09 15:08:12 +00007392 case Builtin::BI__builtin_copysign:
7393 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007394 case Builtin::BI__builtin_copysignl: {
7395 APFloat RHS(0.);
7396 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7397 !EvaluateFloat(E->getArg(1), RHS, Info))
7398 return false;
7399 Result.copySign(RHS);
7400 return true;
7401 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007402 }
7403}
7404
John McCallb1fb0d32010-05-07 22:08:54 +00007405bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007406 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7407 ComplexValue CV;
7408 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7409 return false;
7410 Result = CV.FloatReal;
7411 return true;
7412 }
7413
7414 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007415}
7416
7417bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007418 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7419 ComplexValue CV;
7420 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7421 return false;
7422 Result = CV.FloatImag;
7423 return true;
7424 }
7425
Richard Smith4a678122011-10-24 18:44:57 +00007426 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007427 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7428 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007429 return true;
7430}
7431
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007432bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007433 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007434 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007435 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007436 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007437 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007438 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7439 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007440 Result.changeSign();
7441 return true;
7442 }
7443}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007444
Eli Friedman24c01542008-08-22 00:06:13 +00007445bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007446 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7447 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007448
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007449 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007450 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7451 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007452 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007453 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7454 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007455}
7456
7457bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7458 Result = E->getValue();
7459 return true;
7460}
7461
Peter Collingbournee9200682011-05-13 03:29:01 +00007462bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7463 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007464
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007465 switch (E->getCastKind()) {
7466 default:
Richard Smith11562c52011-10-28 17:51:58 +00007467 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007468
7469 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007470 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007471 return EvaluateInteger(SubExpr, IntResult, Info) &&
7472 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7473 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007474 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007475
7476 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007477 if (!Visit(SubExpr))
7478 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007479 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7480 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007481 }
John McCalld7646252010-11-14 08:17:51 +00007482
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007483 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007484 ComplexValue V;
7485 if (!EvaluateComplex(SubExpr, V, Info))
7486 return false;
7487 Result = V.getComplexFloatReal();
7488 return true;
7489 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007490 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007491}
7492
Eli Friedman24c01542008-08-22 00:06:13 +00007493//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007494// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007495//===----------------------------------------------------------------------===//
7496
7497namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007498class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007499 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007500 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007501
Anders Carlsson537969c2008-11-16 20:27:53 +00007502public:
John McCall93d91dc2010-05-07 17:22:02 +00007503 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007504 : ExprEvaluatorBaseTy(info), Result(Result) {}
7505
Richard Smith2e312c82012-03-03 22:46:17 +00007506 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007507 Result.setFrom(V);
7508 return true;
7509 }
Mike Stump11289f42009-09-09 15:08:12 +00007510
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007511 bool ZeroInitialization(const Expr *E);
7512
Anders Carlsson537969c2008-11-16 20:27:53 +00007513 //===--------------------------------------------------------------------===//
7514 // Visitor Methods
7515 //===--------------------------------------------------------------------===//
7516
Peter Collingbournee9200682011-05-13 03:29:01 +00007517 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007518 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007519 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007520 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007521 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007522};
7523} // end anonymous namespace
7524
John McCall93d91dc2010-05-07 17:22:02 +00007525static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7526 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007527 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007528 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007529}
7530
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007531bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007532 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007533 if (ElemTy->isRealFloatingType()) {
7534 Result.makeComplexFloat();
7535 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7536 Result.FloatReal = Zero;
7537 Result.FloatImag = Zero;
7538 } else {
7539 Result.makeComplexInt();
7540 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7541 Result.IntReal = Zero;
7542 Result.IntImag = Zero;
7543 }
7544 return true;
7545}
7546
Peter Collingbournee9200682011-05-13 03:29:01 +00007547bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7548 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007549
7550 if (SubExpr->getType()->isRealFloatingType()) {
7551 Result.makeComplexFloat();
7552 APFloat &Imag = Result.FloatImag;
7553 if (!EvaluateFloat(SubExpr, Imag, Info))
7554 return false;
7555
7556 Result.FloatReal = APFloat(Imag.getSemantics());
7557 return true;
7558 } else {
7559 assert(SubExpr->getType()->isIntegerType() &&
7560 "Unexpected imaginary literal.");
7561
7562 Result.makeComplexInt();
7563 APSInt &Imag = Result.IntImag;
7564 if (!EvaluateInteger(SubExpr, Imag, Info))
7565 return false;
7566
7567 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7568 return true;
7569 }
7570}
7571
Peter Collingbournee9200682011-05-13 03:29:01 +00007572bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007573
John McCallfcef3cf2010-12-14 17:51:41 +00007574 switch (E->getCastKind()) {
7575 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007576 case CK_BaseToDerived:
7577 case CK_DerivedToBase:
7578 case CK_UncheckedDerivedToBase:
7579 case CK_Dynamic:
7580 case CK_ToUnion:
7581 case CK_ArrayToPointerDecay:
7582 case CK_FunctionToPointerDecay:
7583 case CK_NullToPointer:
7584 case CK_NullToMemberPointer:
7585 case CK_BaseToDerivedMemberPointer:
7586 case CK_DerivedToBaseMemberPointer:
7587 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007588 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007589 case CK_ConstructorConversion:
7590 case CK_IntegralToPointer:
7591 case CK_PointerToIntegral:
7592 case CK_PointerToBoolean:
7593 case CK_ToVoid:
7594 case CK_VectorSplat:
7595 case CK_IntegralCast:
7596 case CK_IntegralToBoolean:
7597 case CK_IntegralToFloating:
7598 case CK_FloatingToIntegral:
7599 case CK_FloatingToBoolean:
7600 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007601 case CK_CPointerToObjCPointerCast:
7602 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007603 case CK_AnyPointerToBlockPointerCast:
7604 case CK_ObjCObjectLValueCast:
7605 case CK_FloatingComplexToReal:
7606 case CK_FloatingComplexToBoolean:
7607 case CK_IntegralComplexToReal:
7608 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007609 case CK_ARCProduceObject:
7610 case CK_ARCConsumeObject:
7611 case CK_ARCReclaimReturnedObject:
7612 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007613 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007614 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007615 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007616 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007617 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007618 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007619
John McCallfcef3cf2010-12-14 17:51:41 +00007620 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007621 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007622 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007623 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007624
7625 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007626 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007627 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007628 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007629
7630 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007631 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007632 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007633 return false;
7634
John McCallfcef3cf2010-12-14 17:51:41 +00007635 Result.makeComplexFloat();
7636 Result.FloatImag = APFloat(Real.getSemantics());
7637 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007638 }
7639
John McCallfcef3cf2010-12-14 17:51:41 +00007640 case CK_FloatingComplexCast: {
7641 if (!Visit(E->getSubExpr()))
7642 return false;
7643
7644 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7645 QualType From
7646 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7647
Richard Smith357362d2011-12-13 06:39:58 +00007648 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7649 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007650 }
7651
7652 case CK_FloatingComplexToIntegralComplex: {
7653 if (!Visit(E->getSubExpr()))
7654 return false;
7655
7656 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7657 QualType From
7658 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7659 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007660 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7661 To, Result.IntReal) &&
7662 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7663 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007664 }
7665
7666 case CK_IntegralRealToComplex: {
7667 APSInt &Real = Result.IntReal;
7668 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7669 return false;
7670
7671 Result.makeComplexInt();
7672 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7673 return true;
7674 }
7675
7676 case CK_IntegralComplexCast: {
7677 if (!Visit(E->getSubExpr()))
7678 return false;
7679
7680 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7681 QualType From
7682 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7683
Richard Smith911e1422012-01-30 22:27:01 +00007684 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7685 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007686 return true;
7687 }
7688
7689 case CK_IntegralComplexToFloatingComplex: {
7690 if (!Visit(E->getSubExpr()))
7691 return false;
7692
Ted Kremenek28831752012-08-23 20:46:57 +00007693 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007694 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007695 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007696 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007697 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7698 To, Result.FloatReal) &&
7699 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7700 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007701 }
7702 }
7703
7704 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007705}
7706
John McCall93d91dc2010-05-07 17:22:02 +00007707bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007708 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007709 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7710
Richard Smith253c2a32012-01-27 01:14:48 +00007711 bool LHSOK = Visit(E->getLHS());
7712 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007713 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007714
John McCall93d91dc2010-05-07 17:22:02 +00007715 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007716 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007717 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007718
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007719 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7720 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007721 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007722 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007723 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007724 if (Result.isComplexFloat()) {
7725 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7726 APFloat::rmNearestTiesToEven);
7727 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7728 APFloat::rmNearestTiesToEven);
7729 } else {
7730 Result.getComplexIntReal() += RHS.getComplexIntReal();
7731 Result.getComplexIntImag() += RHS.getComplexIntImag();
7732 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007733 break;
John McCalle3027922010-08-25 11:45:40 +00007734 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007735 if (Result.isComplexFloat()) {
7736 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7737 APFloat::rmNearestTiesToEven);
7738 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7739 APFloat::rmNearestTiesToEven);
7740 } else {
7741 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7742 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7743 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007744 break;
John McCalle3027922010-08-25 11:45:40 +00007745 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007746 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007747 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007748 APFloat &LHS_r = LHS.getComplexFloatReal();
7749 APFloat &LHS_i = LHS.getComplexFloatImag();
7750 APFloat &RHS_r = RHS.getComplexFloatReal();
7751 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007752
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007753 APFloat Tmp = LHS_r;
7754 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7755 Result.getComplexFloatReal() = Tmp;
7756 Tmp = LHS_i;
7757 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7758 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7759
7760 Tmp = LHS_r;
7761 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7762 Result.getComplexFloatImag() = Tmp;
7763 Tmp = LHS_i;
7764 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7765 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7766 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007767 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007768 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007769 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7770 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007771 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007772 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7773 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7774 }
7775 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007776 case BO_Div:
7777 if (Result.isComplexFloat()) {
7778 ComplexValue LHS = Result;
7779 APFloat &LHS_r = LHS.getComplexFloatReal();
7780 APFloat &LHS_i = LHS.getComplexFloatImag();
7781 APFloat &RHS_r = RHS.getComplexFloatReal();
7782 APFloat &RHS_i = RHS.getComplexFloatImag();
7783 APFloat &Res_r = Result.getComplexFloatReal();
7784 APFloat &Res_i = Result.getComplexFloatImag();
7785
7786 APFloat Den = RHS_r;
7787 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7788 APFloat Tmp = RHS_i;
7789 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7790 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7791
7792 Res_r = LHS_r;
7793 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7794 Tmp = LHS_i;
7795 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7796 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7797 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7798
7799 Res_i = LHS_i;
7800 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7801 Tmp = LHS_r;
7802 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7803 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7804 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7805 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007806 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7807 return Error(E, diag::note_expr_divide_by_zero);
7808
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007809 ComplexValue LHS = Result;
7810 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7811 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7812 Result.getComplexIntReal() =
7813 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7814 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7815 Result.getComplexIntImag() =
7816 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7817 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7818 }
7819 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007820 }
7821
John McCall93d91dc2010-05-07 17:22:02 +00007822 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007823}
7824
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007825bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7826 // Get the operand value into 'Result'.
7827 if (!Visit(E->getSubExpr()))
7828 return false;
7829
7830 switch (E->getOpcode()) {
7831 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007832 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007833 case UO_Extension:
7834 return true;
7835 case UO_Plus:
7836 // The result is always just the subexpr.
7837 return true;
7838 case UO_Minus:
7839 if (Result.isComplexFloat()) {
7840 Result.getComplexFloatReal().changeSign();
7841 Result.getComplexFloatImag().changeSign();
7842 }
7843 else {
7844 Result.getComplexIntReal() = -Result.getComplexIntReal();
7845 Result.getComplexIntImag() = -Result.getComplexIntImag();
7846 }
7847 return true;
7848 case UO_Not:
7849 if (Result.isComplexFloat())
7850 Result.getComplexFloatImag().changeSign();
7851 else
7852 Result.getComplexIntImag() = -Result.getComplexIntImag();
7853 return true;
7854 }
7855}
7856
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007857bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7858 if (E->getNumInits() == 2) {
7859 if (E->getType()->isComplexType()) {
7860 Result.makeComplexFloat();
7861 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7862 return false;
7863 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7864 return false;
7865 } else {
7866 Result.makeComplexInt();
7867 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7868 return false;
7869 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7870 return false;
7871 }
7872 return true;
7873 }
7874 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7875}
7876
Anders Carlsson537969c2008-11-16 20:27:53 +00007877//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007878// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7879// implicit conversion.
7880//===----------------------------------------------------------------------===//
7881
7882namespace {
7883class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007884 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007885 APValue &Result;
7886public:
7887 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7888 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7889
7890 bool Success(const APValue &V, const Expr *E) {
7891 Result = V;
7892 return true;
7893 }
7894
7895 bool ZeroInitialization(const Expr *E) {
7896 ImplicitValueInitExpr VIE(
7897 E->getType()->castAs<AtomicType>()->getValueType());
7898 return Evaluate(Result, Info, &VIE);
7899 }
7900
7901 bool VisitCastExpr(const CastExpr *E) {
7902 switch (E->getCastKind()) {
7903 default:
7904 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7905 case CK_NonAtomicToAtomic:
7906 return Evaluate(Result, Info, E->getSubExpr());
7907 }
7908 }
7909};
7910} // end anonymous namespace
7911
7912static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7913 assert(E->isRValue() && E->getType()->isAtomicType());
7914 return AtomicExprEvaluator(Info, Result).Visit(E);
7915}
7916
7917//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007918// Void expression evaluation, primarily for a cast to void on the LHS of a
7919// comma operator
7920//===----------------------------------------------------------------------===//
7921
7922namespace {
7923class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007924 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007925public:
7926 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7927
Richard Smith2e312c82012-03-03 22:46:17 +00007928 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007929
7930 bool VisitCastExpr(const CastExpr *E) {
7931 switch (E->getCastKind()) {
7932 default:
7933 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7934 case CK_ToVoid:
7935 VisitIgnoredValue(E->getSubExpr());
7936 return true;
7937 }
7938 }
7939};
7940} // end anonymous namespace
7941
7942static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7943 assert(E->isRValue() && E->getType()->isVoidType());
7944 return VoidExprEvaluator(Info).Visit(E);
7945}
7946
7947//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007948// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007949//===----------------------------------------------------------------------===//
7950
Richard Smith2e312c82012-03-03 22:46:17 +00007951static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007952 // In C, function designators are not lvalues, but we evaluate them as if they
7953 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007954 QualType T = E->getType();
7955 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007956 LValue LV;
7957 if (!EvaluateLValue(E, LV, Info))
7958 return false;
7959 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007960 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007961 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007962 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007963 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007964 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007965 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007966 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007967 LValue LV;
7968 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007969 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007970 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007971 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007972 llvm::APFloat F(0.0);
7973 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007974 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007975 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007976 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007977 ComplexValue C;
7978 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007979 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007980 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007981 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007982 MemberPtr P;
7983 if (!EvaluateMemberPointer(E, P, Info))
7984 return false;
7985 P.moveInto(Result);
7986 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007987 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007988 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007989 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007990 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7991 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007992 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007993 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007994 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007995 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007996 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007997 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7998 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007999 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008000 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008001 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008002 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008003 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008004 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008005 if (!EvaluateVoid(E, Info))
8006 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008007 } else if (T->isAtomicType()) {
8008 if (!EvaluateAtomic(E, Result, Info))
8009 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008010 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008011 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008012 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008013 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008014 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008015 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008016 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008017
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008018 return true;
8019}
8020
Richard Smithb228a862012-02-15 02:18:13 +00008021/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8022/// cases, the in-place evaluation is essential, since later initializers for
8023/// an object can indirectly refer to subobjects which were initialized earlier.
8024static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008025 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008026 assert(!E->isValueDependent());
8027
Richard Smith7525ff62013-05-09 07:14:00 +00008028 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008029 return false;
8030
8031 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008032 // Evaluate arrays and record types in-place, so that later initializers can
8033 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008034 if (E->getType()->isArrayType())
8035 return EvaluateArray(E, This, Result, Info);
8036 else if (E->getType()->isRecordType())
8037 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008038 }
8039
8040 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008041 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008042}
8043
Richard Smithf57d8cb2011-12-09 22:58:01 +00008044/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8045/// lvalue-to-rvalue cast if it is an lvalue.
8046static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008047 if (E->getType().isNull())
8048 return false;
8049
Richard Smithfddd3842011-12-30 21:15:51 +00008050 if (!CheckLiteralType(Info, E))
8051 return false;
8052
Richard Smith2e312c82012-03-03 22:46:17 +00008053 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008054 return false;
8055
8056 if (E->isGLValue()) {
8057 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008058 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008059 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008060 return false;
8061 }
8062
Richard Smith2e312c82012-03-03 22:46:17 +00008063 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008064 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008065}
Richard Smith11562c52011-10-28 17:51:58 +00008066
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008067static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8068 const ASTContext &Ctx, bool &IsConst) {
8069 // Fast-path evaluations of integer literals, since we sometimes see files
8070 // containing vast quantities of these.
8071 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8072 Result.Val = APValue(APSInt(L->getValue(),
8073 L->getType()->isUnsignedIntegerType()));
8074 IsConst = true;
8075 return true;
8076 }
James Dennett0492ef02014-03-14 17:44:10 +00008077
8078 // This case should be rare, but we need to check it before we check on
8079 // the type below.
8080 if (Exp->getType().isNull()) {
8081 IsConst = false;
8082 return true;
8083 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008084
8085 // FIXME: Evaluating values of large array and record types can cause
8086 // performance problems. Only do so in C++11 for now.
8087 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8088 Exp->getType()->isRecordType()) &&
8089 !Ctx.getLangOpts().CPlusPlus11) {
8090 IsConst = false;
8091 return true;
8092 }
8093 return false;
8094}
8095
8096
Richard Smith7b553f12011-10-29 00:50:52 +00008097/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008098/// any crazy technique (that has nothing to do with language standards) that
8099/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008100/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8101/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008102bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008103 bool IsConst;
8104 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8105 return IsConst;
8106
Richard Smith6d4c6582013-11-05 22:18:15 +00008107 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008108 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008109}
8110
Jay Foad39c79802011-01-12 09:06:06 +00008111bool Expr::EvaluateAsBooleanCondition(bool &Result,
8112 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008113 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008114 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008115 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008116}
8117
Richard Smith5fab0c92011-12-28 19:48:30 +00008118bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8119 SideEffectsKind AllowSideEffects) const {
8120 if (!getType()->isIntegralOrEnumerationType())
8121 return false;
8122
Richard Smith11562c52011-10-28 17:51:58 +00008123 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008124 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8125 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008126 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008127
Richard Smith11562c52011-10-28 17:51:58 +00008128 Result = ExprResult.Val.getInt();
8129 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008130}
8131
Jay Foad39c79802011-01-12 09:06:06 +00008132bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008133 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008134
John McCall45d55e42010-05-07 21:00:08 +00008135 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008136 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8137 !CheckLValueConstantExpression(Info, getExprLoc(),
8138 Ctx.getLValueReferenceType(getType()), LV))
8139 return false;
8140
Richard Smith2e312c82012-03-03 22:46:17 +00008141 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008142 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008143}
8144
Richard Smithd0b4dd62011-12-19 06:19:21 +00008145bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8146 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008147 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008148 // FIXME: Evaluating initializers for large array and record types can cause
8149 // performance problems. Only do so in C++11 for now.
8150 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008151 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008152 return false;
8153
Richard Smithd0b4dd62011-12-19 06:19:21 +00008154 Expr::EvalStatus EStatus;
8155 EStatus.Diag = &Notes;
8156
Richard Smith6d4c6582013-11-05 22:18:15 +00008157 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008158 InitInfo.setEvaluatingDecl(VD, Value);
8159
8160 LValue LVal;
8161 LVal.set(VD);
8162
Richard Smithfddd3842011-12-30 21:15:51 +00008163 // C++11 [basic.start.init]p2:
8164 // Variables with static storage duration or thread storage duration shall be
8165 // zero-initialized before any other initialization takes place.
8166 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008167 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008168 !VD->getType()->isReferenceType()) {
8169 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008170 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008171 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008172 return false;
8173 }
8174
Richard Smith7525ff62013-05-09 07:14:00 +00008175 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8176 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008177 EStatus.HasSideEffects)
8178 return false;
8179
8180 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8181 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008182}
8183
Richard Smith7b553f12011-10-29 00:50:52 +00008184/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8185/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008186bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008187 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008188 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008189}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008190
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008191APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008192 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008193 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008194 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008195 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008196 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008197 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008198 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008199
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008200 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008201}
John McCall864e3962010-05-07 05:32:02 +00008202
Richard Smithe9ff7702013-11-05 22:23:30 +00008203void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008204 bool IsConst;
8205 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008206 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008207 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008208 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8209 }
8210}
8211
Richard Smithe6c01442013-06-05 00:46:14 +00008212bool Expr::EvalResult::isGlobalLValue() const {
8213 assert(Val.isLValue());
8214 return IsGlobalLValue(Val.getLValueBase());
8215}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008216
8217
John McCall864e3962010-05-07 05:32:02 +00008218/// isIntegerConstantExpr - this recursive routine will test if an expression is
8219/// an integer constant expression.
8220
8221/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8222/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008223
8224// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008225// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8226// and a (possibly null) SourceLocation indicating the location of the problem.
8227//
John McCall864e3962010-05-07 05:32:02 +00008228// Note that to reduce code duplication, this helper does no evaluation
8229// itself; the caller checks whether the expression is evaluatable, and
8230// in the rare cases where CheckICE actually cares about the evaluated
8231// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008232
Dan Gohman28ade552010-07-26 21:25:24 +00008233namespace {
8234
Richard Smith9e575da2012-12-28 13:25:52 +00008235enum ICEKind {
8236 /// This expression is an ICE.
8237 IK_ICE,
8238 /// This expression is not an ICE, but if it isn't evaluated, it's
8239 /// a legal subexpression for an ICE. This return value is used to handle
8240 /// the comma operator in C99 mode, and non-constant subexpressions.
8241 IK_ICEIfUnevaluated,
8242 /// This expression is not an ICE, and is not a legal subexpression for one.
8243 IK_NotICE
8244};
8245
John McCall864e3962010-05-07 05:32:02 +00008246struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008247 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008248 SourceLocation Loc;
8249
Richard Smith9e575da2012-12-28 13:25:52 +00008250 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008251};
8252
Dan Gohman28ade552010-07-26 21:25:24 +00008253}
8254
Richard Smith9e575da2012-12-28 13:25:52 +00008255static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8256
8257static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008258
Craig Toppera31a8822013-08-22 07:09:37 +00008259static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008260 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008261 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008262 !EVResult.Val.isInt())
8263 return ICEDiag(IK_NotICE, E->getLocStart());
8264
John McCall864e3962010-05-07 05:32:02 +00008265 return NoDiag();
8266}
8267
Craig Toppera31a8822013-08-22 07:09:37 +00008268static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008269 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008270 if (!E->getType()->isIntegralOrEnumerationType())
8271 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008272
8273 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008274#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008275#define STMT(Node, Base) case Expr::Node##Class:
8276#define EXPR(Node, Base)
8277#include "clang/AST/StmtNodes.inc"
8278 case Expr::PredefinedExprClass:
8279 case Expr::FloatingLiteralClass:
8280 case Expr::ImaginaryLiteralClass:
8281 case Expr::StringLiteralClass:
8282 case Expr::ArraySubscriptExprClass:
8283 case Expr::MemberExprClass:
8284 case Expr::CompoundAssignOperatorClass:
8285 case Expr::CompoundLiteralExprClass:
8286 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008287 case Expr::DesignatedInitExprClass:
8288 case Expr::ImplicitValueInitExprClass:
8289 case Expr::ParenListExprClass:
8290 case Expr::VAArgExprClass:
8291 case Expr::AddrLabelExprClass:
8292 case Expr::StmtExprClass:
8293 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008294 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008295 case Expr::CXXDynamicCastExprClass:
8296 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008297 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008298 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008299 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008300 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008301 case Expr::CXXThisExprClass:
8302 case Expr::CXXThrowExprClass:
8303 case Expr::CXXNewExprClass:
8304 case Expr::CXXDeleteExprClass:
8305 case Expr::CXXPseudoDestructorExprClass:
8306 case Expr::UnresolvedLookupExprClass:
8307 case Expr::DependentScopeDeclRefExprClass:
8308 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008309 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008310 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008311 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008312 case Expr::CXXTemporaryObjectExprClass:
8313 case Expr::CXXUnresolvedConstructExprClass:
8314 case Expr::CXXDependentScopeMemberExprClass:
8315 case Expr::UnresolvedMemberExprClass:
8316 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008317 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008318 case Expr::ObjCArrayLiteralClass:
8319 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008320 case Expr::ObjCEncodeExprClass:
8321 case Expr::ObjCMessageExprClass:
8322 case Expr::ObjCSelectorExprClass:
8323 case Expr::ObjCProtocolExprClass:
8324 case Expr::ObjCIvarRefExprClass:
8325 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008326 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008327 case Expr::ObjCIsaExprClass:
8328 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008329 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008330 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008331 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008332 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008333 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008334 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008335 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008336 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008337 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008338 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008339 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008340 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008341 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008342 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008343
Richard Smithf137f932014-01-25 20:50:08 +00008344 case Expr::InitListExprClass: {
8345 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8346 // form "T x = { a };" is equivalent to "T x = a;".
8347 // Unless we're initializing a reference, T is a scalar as it is known to be
8348 // of integral or enumeration type.
8349 if (E->isRValue())
8350 if (cast<InitListExpr>(E)->getNumInits() == 1)
8351 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8352 return ICEDiag(IK_NotICE, E->getLocStart());
8353 }
8354
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008355 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008356 case Expr::GNUNullExprClass:
8357 // GCC considers the GNU __null value to be an integral constant expression.
8358 return NoDiag();
8359
John McCall7c454bb2011-07-15 05:09:51 +00008360 case Expr::SubstNonTypeTemplateParmExprClass:
8361 return
8362 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8363
John McCall864e3962010-05-07 05:32:02 +00008364 case Expr::ParenExprClass:
8365 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008366 case Expr::GenericSelectionExprClass:
8367 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008368 case Expr::IntegerLiteralClass:
8369 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008370 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008371 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008372 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008373 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008374 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008375 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008376 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008377 return NoDiag();
8378 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008379 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008380 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8381 // constant expressions, but they can never be ICEs because an ICE cannot
8382 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008383 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008384 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008385 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008386 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008387 }
Richard Smith6365c912012-02-24 22:12:32 +00008388 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008389 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8390 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008391 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008392 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008393 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008394 // Parameter variables are never constants. Without this check,
8395 // getAnyInitializer() can find a default argument, which leads
8396 // to chaos.
8397 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008398 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008399
8400 // C++ 7.1.5.1p2
8401 // A variable of non-volatile const-qualified integral or enumeration
8402 // type initialized by an ICE can be used in ICEs.
8403 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008404 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008405 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008406
Richard Smithd0b4dd62011-12-19 06:19:21 +00008407 const VarDecl *VD;
8408 // Look for a declaration of this variable that has an initializer, and
8409 // check whether it is an ICE.
8410 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8411 return NoDiag();
8412 else
Richard Smith9e575da2012-12-28 13:25:52 +00008413 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008414 }
8415 }
Richard Smith9e575da2012-12-28 13:25:52 +00008416 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008417 }
John McCall864e3962010-05-07 05:32:02 +00008418 case Expr::UnaryOperatorClass: {
8419 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8420 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008421 case UO_PostInc:
8422 case UO_PostDec:
8423 case UO_PreInc:
8424 case UO_PreDec:
8425 case UO_AddrOf:
8426 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008427 // C99 6.6/3 allows increment and decrement within unevaluated
8428 // subexpressions of constant expressions, but they can never be ICEs
8429 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008430 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008431 case UO_Extension:
8432 case UO_LNot:
8433 case UO_Plus:
8434 case UO_Minus:
8435 case UO_Not:
8436 case UO_Real:
8437 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008438 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008439 }
Richard Smith9e575da2012-12-28 13:25:52 +00008440
John McCall864e3962010-05-07 05:32:02 +00008441 // OffsetOf falls through here.
8442 }
8443 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008444 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8445 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8446 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8447 // compliance: we should warn earlier for offsetof expressions with
8448 // array subscripts that aren't ICEs, and if the array subscripts
8449 // are ICEs, the value of the offsetof must be an integer constant.
8450 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008451 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008452 case Expr::UnaryExprOrTypeTraitExprClass: {
8453 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8454 if ((Exp->getKind() == UETT_SizeOf) &&
8455 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008456 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008457 return NoDiag();
8458 }
8459 case Expr::BinaryOperatorClass: {
8460 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8461 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008462 case BO_PtrMemD:
8463 case BO_PtrMemI:
8464 case BO_Assign:
8465 case BO_MulAssign:
8466 case BO_DivAssign:
8467 case BO_RemAssign:
8468 case BO_AddAssign:
8469 case BO_SubAssign:
8470 case BO_ShlAssign:
8471 case BO_ShrAssign:
8472 case BO_AndAssign:
8473 case BO_XorAssign:
8474 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008475 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8476 // constant expressions, but they can never be ICEs because an ICE cannot
8477 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008478 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008479
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_Mul:
8481 case BO_Div:
8482 case BO_Rem:
8483 case BO_Add:
8484 case BO_Sub:
8485 case BO_Shl:
8486 case BO_Shr:
8487 case BO_LT:
8488 case BO_GT:
8489 case BO_LE:
8490 case BO_GE:
8491 case BO_EQ:
8492 case BO_NE:
8493 case BO_And:
8494 case BO_Xor:
8495 case BO_Or:
8496 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008497 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8498 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008499 if (Exp->getOpcode() == BO_Div ||
8500 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008501 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008502 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008503 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008504 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008505 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008506 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008507 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008508 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008509 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008510 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008511 }
8512 }
8513 }
John McCalle3027922010-08-25 11:45:40 +00008514 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008515 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008516 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8517 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008518 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8519 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008520 } else {
8521 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008522 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008523 }
8524 }
Richard Smith9e575da2012-12-28 13:25:52 +00008525 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008526 }
John McCalle3027922010-08-25 11:45:40 +00008527 case BO_LAnd:
8528 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008529 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8530 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008531 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008532 // Rare case where the RHS has a comma "side-effect"; we need
8533 // to actually check the condition to see whether the side
8534 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008535 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008536 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008537 return RHSResult;
8538 return NoDiag();
8539 }
8540
Richard Smith9e575da2012-12-28 13:25:52 +00008541 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008542 }
8543 }
8544 }
8545 case Expr::ImplicitCastExprClass:
8546 case Expr::CStyleCastExprClass:
8547 case Expr::CXXFunctionalCastExprClass:
8548 case Expr::CXXStaticCastExprClass:
8549 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008550 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008551 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008552 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008553 if (isa<ExplicitCastExpr>(E)) {
8554 if (const FloatingLiteral *FL
8555 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8556 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8557 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8558 APSInt IgnoredVal(DestWidth, !DestSigned);
8559 bool Ignored;
8560 // If the value does not fit in the destination type, the behavior is
8561 // undefined, so we are not required to treat it as a constant
8562 // expression.
8563 if (FL->getValue().convertToInteger(IgnoredVal,
8564 llvm::APFloat::rmTowardZero,
8565 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008566 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008567 return NoDiag();
8568 }
8569 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008570 switch (cast<CastExpr>(E)->getCastKind()) {
8571 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008572 case CK_AtomicToNonAtomic:
8573 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008574 case CK_NoOp:
8575 case CK_IntegralToBoolean:
8576 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008577 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008578 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008579 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008580 }
John McCall864e3962010-05-07 05:32:02 +00008581 }
John McCallc07a0c72011-02-17 10:25:35 +00008582 case Expr::BinaryConditionalOperatorClass: {
8583 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8584 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008585 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008586 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008587 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8588 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8589 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008590 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008591 return FalseResult;
8592 }
John McCall864e3962010-05-07 05:32:02 +00008593 case Expr::ConditionalOperatorClass: {
8594 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8595 // If the condition (ignoring parens) is a __builtin_constant_p call,
8596 // then only the true side is actually considered in an integer constant
8597 // expression, and it is fully evaluated. This is an important GNU
8598 // extension. See GCC PR38377 for discussion.
8599 if (const CallExpr *CallCE
8600 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008601 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008602 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008603 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008604 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008605 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008606
Richard Smithf57d8cb2011-12-09 22:58:01 +00008607 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8608 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008609
Richard Smith9e575da2012-12-28 13:25:52 +00008610 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008611 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008612 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008613 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008614 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008615 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008616 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008617 return NoDiag();
8618 // Rare case where the diagnostics depend on which side is evaluated
8619 // Note that if we get here, CondResult is 0, and at least one of
8620 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008621 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008622 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008623 return TrueResult;
8624 }
8625 case Expr::CXXDefaultArgExprClass:
8626 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008627 case Expr::CXXDefaultInitExprClass:
8628 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008629 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008630 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008631 }
8632 }
8633
David Blaikiee4d798f2012-01-20 21:50:17 +00008634 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008635}
8636
Richard Smithf57d8cb2011-12-09 22:58:01 +00008637/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008638static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008639 const Expr *E,
8640 llvm::APSInt *Value,
8641 SourceLocation *Loc) {
8642 if (!E->getType()->isIntegralOrEnumerationType()) {
8643 if (Loc) *Loc = E->getExprLoc();
8644 return false;
8645 }
8646
Richard Smith66e05fe2012-01-18 05:21:49 +00008647 APValue Result;
8648 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008649 return false;
8650
Richard Smith66e05fe2012-01-18 05:21:49 +00008651 assert(Result.isInt() && "pointer cast to int is not an ICE");
8652 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008653 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008654}
8655
Craig Toppera31a8822013-08-22 07:09:37 +00008656bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8657 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008658 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008659 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008660
Richard Smith9e575da2012-12-28 13:25:52 +00008661 ICEDiag D = CheckICE(this, Ctx);
8662 if (D.Kind != IK_ICE) {
8663 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008664 return false;
8665 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008666 return true;
8667}
8668
Craig Toppera31a8822013-08-22 07:09:37 +00008669bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008670 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008671 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008672 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8673
8674 if (!isIntegerConstantExpr(Ctx, Loc))
8675 return false;
8676 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008677 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008678 return true;
8679}
Richard Smith66e05fe2012-01-18 05:21:49 +00008680
Craig Toppera31a8822013-08-22 07:09:37 +00008681bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008682 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008683}
8684
Craig Toppera31a8822013-08-22 07:09:37 +00008685bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008686 SourceLocation *Loc) const {
8687 // We support this checking in C++98 mode in order to diagnose compatibility
8688 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008689 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008690
Richard Smith98a0a492012-02-14 21:38:30 +00008691 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008692 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008693 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008694 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008695 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008696
8697 APValue Scratch;
8698 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8699
8700 if (!Diags.empty()) {
8701 IsConstExpr = false;
8702 if (Loc) *Loc = Diags[0].first;
8703 } else if (!IsConstExpr) {
8704 // FIXME: This shouldn't happen.
8705 if (Loc) *Loc = getExprLoc();
8706 }
8707
8708 return IsConstExpr;
8709}
Richard Smith253c2a32012-01-27 01:14:48 +00008710
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008711bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8712 const FunctionDecl *Callee,
8713 llvm::ArrayRef<const Expr*> Args) const {
8714 Expr::EvalStatus Status;
8715 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8716
8717 ArgVector ArgValues(Args.size());
8718 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8719 I != E; ++I) {
8720 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8721 // If evaluation fails, throw away the argument entirely.
8722 ArgValues[I - Args.begin()] = APValue();
8723 if (Info.EvalStatus.HasSideEffects)
8724 return false;
8725 }
8726
8727 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00008728 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008729 ArgValues.data());
8730 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8731}
8732
Richard Smith253c2a32012-01-27 01:14:48 +00008733bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008734 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008735 PartialDiagnosticAt> &Diags) {
8736 // FIXME: It would be useful to check constexpr function templates, but at the
8737 // moment the constant expression evaluator cannot cope with the non-rigorous
8738 // ASTs which we build for dependent expressions.
8739 if (FD->isDependentContext())
8740 return true;
8741
8742 Expr::EvalStatus Status;
8743 Status.Diag = &Diags;
8744
Richard Smith6d4c6582013-11-05 22:18:15 +00008745 EvalInfo Info(FD->getASTContext(), Status,
8746 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008747
8748 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00008749 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00008750
Richard Smith7525ff62013-05-09 07:14:00 +00008751 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008752 // is a temporary being used as the 'this' pointer.
8753 LValue This;
8754 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008755 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008756
Richard Smith253c2a32012-01-27 01:14:48 +00008757 ArrayRef<const Expr*> Args;
8758
8759 SourceLocation Loc = FD->getLocation();
8760
Richard Smith2e312c82012-03-03 22:46:17 +00008761 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008762 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8763 // Evaluate the call as a constant initializer, to allow the construction
8764 // of objects of non-literal types.
8765 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008766 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008767 } else
Craig Topper36250ad2014-05-12 05:36:57 +00008768 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00008769 Args, FD->getBody(), Info, Scratch);
8770
8771 return Diags.empty();
8772}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008773
8774bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8775 const FunctionDecl *FD,
8776 SmallVectorImpl<
8777 PartialDiagnosticAt> &Diags) {
8778 Expr::EvalStatus Status;
8779 Status.Diag = &Diags;
8780
8781 EvalInfo Info(FD->getASTContext(), Status,
8782 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8783
8784 // Fabricate a call stack frame to give the arguments a plausible cover story.
8785 ArrayRef<const Expr*> Args;
8786 ArgVector ArgValues(0);
8787 bool Success = EvaluateArgs(Args, ArgValues, Info);
8788 (void)Success;
8789 assert(Success &&
8790 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00008791 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008792
8793 APValue ResultScratch;
8794 Evaluate(ResultScratch, Info, E);
8795 return Diags.empty();
8796}