blob: 98061e6c494ee7240dac55422a8816e921cda48c [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 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1273 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001274 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001275 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001276 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001277
Hans Wennborg82dd8772014-06-25 22:19:48 +00001278 // A dllimport variable never acts like a constant.
1279 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001280 return false;
1281 }
1282 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1283 // __declspec(dllimport) must be handled very carefully:
1284 // We must never initialize an expression with the thunk in C++.
1285 // Doing otherwise would allow the same id-expression to yield
1286 // different addresses for the same function in different translation
1287 // units. However, this means that we must dynamically initialize the
1288 // expression with the contents of the import address table at runtime.
1289 //
1290 // The C language has no notion of ODR; furthermore, it has no notion of
1291 // dynamic initialization. This means that we are permitted to
1292 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001293 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001294 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001295 }
1296 }
1297
Richard Smitha8105bc2012-01-06 16:39:00 +00001298 // Allow address constant expressions to be past-the-end pointers. This is
1299 // an extension: the standard requires them to point to an object.
1300 if (!IsReferenceType)
1301 return true;
1302
1303 // A reference constant expression must refer to an object.
1304 if (!Base) {
1305 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001306 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001307 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001308 }
1309
Richard Smith357362d2011-12-13 06:39:58 +00001310 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001311 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001312 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001313 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001314 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001315 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001316 }
1317
Richard Smith80815602011-11-07 05:07:52 +00001318 return true;
1319}
1320
Richard Smithfddd3842011-12-30 21:15:51 +00001321/// Check that this core constant expression is of literal type, and if not,
1322/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001323static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001324 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001325 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001326 return true;
1327
Richard Smith7525ff62013-05-09 07:14:00 +00001328 // C++1y: A constant initializer for an object o [...] may also invoke
1329 // constexpr constructors for o and its subobjects even if those objects
1330 // are of non-literal class types.
1331 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001332 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001333 return true;
1334
Richard Smithfddd3842011-12-30 21:15:51 +00001335 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001336 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001337 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001338 << E->getType();
1339 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001340 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001341 return false;
1342}
1343
Richard Smith0b0a0b62011-10-29 20:57:55 +00001344/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001345/// constant expression. If not, report an appropriate diagnostic. Does not
1346/// check that the expression is of literal type.
1347static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1348 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001349 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001350 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1351 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001352 return false;
1353 }
1354
Richard Smithb228a862012-02-15 02:18:13 +00001355 // Core issue 1454: For a literal constant expression of array or class type,
1356 // each subobject of its value shall have been initialized by a constant
1357 // expression.
1358 if (Value.isArray()) {
1359 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1360 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1361 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1362 Value.getArrayInitializedElt(I)))
1363 return false;
1364 }
1365 if (!Value.hasArrayFiller())
1366 return true;
1367 return CheckConstantExpression(Info, DiagLoc, EltTy,
1368 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001369 }
Richard Smithb228a862012-02-15 02:18:13 +00001370 if (Value.isUnion() && Value.getUnionField()) {
1371 return CheckConstantExpression(Info, DiagLoc,
1372 Value.getUnionField()->getType(),
1373 Value.getUnionValue());
1374 }
1375 if (Value.isStruct()) {
1376 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1377 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1378 unsigned BaseIndex = 0;
1379 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1380 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1381 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1382 Value.getStructBase(BaseIndex)))
1383 return false;
1384 }
1385 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001386 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001387 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001389 return false;
1390 }
1391 }
1392
1393 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001394 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001395 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001396 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1397 }
1398
1399 // Everything else is fine.
1400 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001401}
1402
Richard Smith83c68212011-10-31 05:11:32 +00001403const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001404 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001405}
1406
1407static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001408 if (Value.CallIndex)
1409 return false;
1410 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1411 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001412}
1413
Richard Smithcecf1842011-11-01 21:06:14 +00001414static bool IsWeakLValue(const LValue &Value) {
1415 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001416 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001417}
1418
Richard Smith2e312c82012-03-03 22:46:17 +00001419static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001420 // A null base expression indicates a null pointer. These are always
1421 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001422 if (!Value.getLValueBase()) {
1423 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001424 return true;
1425 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001426
Richard Smith027bf112011-11-17 22:56:20 +00001427 // We have a non-null base. These are generally known to be true, but if it's
1428 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001429 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001430 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001431 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001432}
1433
Richard Smith2e312c82012-03-03 22:46:17 +00001434static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001435 switch (Val.getKind()) {
1436 case APValue::Uninitialized:
1437 return false;
1438 case APValue::Int:
1439 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001440 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001441 case APValue::Float:
1442 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001443 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001444 case APValue::ComplexInt:
1445 Result = Val.getComplexIntReal().getBoolValue() ||
1446 Val.getComplexIntImag().getBoolValue();
1447 return true;
1448 case APValue::ComplexFloat:
1449 Result = !Val.getComplexFloatReal().isZero() ||
1450 !Val.getComplexFloatImag().isZero();
1451 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001452 case APValue::LValue:
1453 return EvalPointerValueAsBool(Val, Result);
1454 case APValue::MemberPointer:
1455 Result = Val.getMemberPointerDecl();
1456 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001457 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001458 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001459 case APValue::Struct:
1460 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001461 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001462 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001463 }
1464
Richard Smith11562c52011-10-28 17:51:58 +00001465 llvm_unreachable("unknown APValue kind");
1466}
1467
1468static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1469 EvalInfo &Info) {
1470 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001471 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001472 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001473 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001474 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001475}
1476
Richard Smith357362d2011-12-13 06:39:58 +00001477template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001478static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001479 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001480 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001481 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001482}
1483
1484static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1485 QualType SrcType, const APFloat &Value,
1486 QualType DestType, APSInt &Result) {
1487 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001488 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001489 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001490
Richard Smith357362d2011-12-13 06:39:58 +00001491 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001492 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001493 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1494 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001495 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001496 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001497}
1498
Richard Smith357362d2011-12-13 06:39:58 +00001499static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1500 QualType SrcType, QualType DestType,
1501 APFloat &Result) {
1502 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001503 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001504 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1505 APFloat::rmNearestTiesToEven, &ignored)
1506 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001507 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001508 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001509}
1510
Richard Smith911e1422012-01-30 22:27:01 +00001511static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1512 QualType DestType, QualType SrcType,
1513 APSInt &Value) {
1514 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001515 APSInt Result = Value;
1516 // Figure out if this is a truncate, extend or noop cast.
1517 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001518 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001519 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001520 return Result;
1521}
1522
Richard Smith357362d2011-12-13 06:39:58 +00001523static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1524 QualType SrcType, const APSInt &Value,
1525 QualType DestType, APFloat &Result) {
1526 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1527 if (Result.convertFromAPInt(Value, Value.isSigned(),
1528 APFloat::rmNearestTiesToEven)
1529 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001530 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001531 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001532}
1533
Richard Smith49ca8aa2013-08-06 07:09:20 +00001534static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1535 APValue &Value, const FieldDecl *FD) {
1536 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1537
1538 if (!Value.isInt()) {
1539 // Trying to store a pointer-cast-to-integer into a bitfield.
1540 // FIXME: In this case, we should provide the diagnostic for casting
1541 // a pointer to an integer.
1542 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1543 Info.Diag(E);
1544 return false;
1545 }
1546
1547 APSInt &Int = Value.getInt();
1548 unsigned OldBitWidth = Int.getBitWidth();
1549 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1550 if (NewBitWidth < OldBitWidth)
1551 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1552 return true;
1553}
1554
Eli Friedman803acb32011-12-22 03:51:45 +00001555static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1556 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001557 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001558 if (!Evaluate(SVal, Info, E))
1559 return false;
1560 if (SVal.isInt()) {
1561 Res = SVal.getInt();
1562 return true;
1563 }
1564 if (SVal.isFloat()) {
1565 Res = SVal.getFloat().bitcastToAPInt();
1566 return true;
1567 }
1568 if (SVal.isVector()) {
1569 QualType VecTy = E->getType();
1570 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1571 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1572 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1573 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1574 Res = llvm::APInt::getNullValue(VecSize);
1575 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1576 APValue &Elt = SVal.getVectorElt(i);
1577 llvm::APInt EltAsInt;
1578 if (Elt.isInt()) {
1579 EltAsInt = Elt.getInt();
1580 } else if (Elt.isFloat()) {
1581 EltAsInt = Elt.getFloat().bitcastToAPInt();
1582 } else {
1583 // Don't try to handle vectors of anything other than int or float
1584 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001585 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001586 return false;
1587 }
1588 unsigned BaseEltSize = EltAsInt.getBitWidth();
1589 if (BigEndian)
1590 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1591 else
1592 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1593 }
1594 return true;
1595 }
1596 // Give up if the input isn't an int, float, or vector. For example, we
1597 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001598 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001599 return false;
1600}
1601
Richard Smith43e77732013-05-07 04:50:00 +00001602/// Perform the given integer operation, which is known to need at most BitWidth
1603/// bits, and check for overflow in the original type (if that type was not an
1604/// unsigned type).
1605template<typename Operation>
1606static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1607 const APSInt &LHS, const APSInt &RHS,
1608 unsigned BitWidth, Operation Op) {
1609 if (LHS.isUnsigned())
1610 return Op(LHS, RHS);
1611
1612 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1613 APSInt Result = Value.trunc(LHS.getBitWidth());
1614 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001615 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001616 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1617 diag::warn_integer_constant_overflow)
1618 << Result.toString(10) << E->getType();
1619 else
1620 HandleOverflow(Info, E, Value, E->getType());
1621 }
1622 return Result;
1623}
1624
1625/// Perform the given binary integer operation.
1626static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1627 BinaryOperatorKind Opcode, APSInt RHS,
1628 APSInt &Result) {
1629 switch (Opcode) {
1630 default:
1631 Info.Diag(E);
1632 return false;
1633 case BO_Mul:
1634 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1635 std::multiplies<APSInt>());
1636 return true;
1637 case BO_Add:
1638 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1639 std::plus<APSInt>());
1640 return true;
1641 case BO_Sub:
1642 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1643 std::minus<APSInt>());
1644 return true;
1645 case BO_And: Result = LHS & RHS; return true;
1646 case BO_Xor: Result = LHS ^ RHS; return true;
1647 case BO_Or: Result = LHS | RHS; return true;
1648 case BO_Div:
1649 case BO_Rem:
1650 if (RHS == 0) {
1651 Info.Diag(E, diag::note_expr_divide_by_zero);
1652 return false;
1653 }
1654 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1655 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1656 LHS.isSigned() && LHS.isMinSignedValue())
1657 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1658 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1659 return true;
1660 case BO_Shl: {
1661 if (Info.getLangOpts().OpenCL)
1662 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1663 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1664 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1665 RHS.isUnsigned());
1666 else if (RHS.isSigned() && RHS.isNegative()) {
1667 // During constant-folding, a negative shift is an opposite shift. Such
1668 // a shift is not a constant expression.
1669 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1670 RHS = -RHS;
1671 goto shift_right;
1672 }
1673 shift_left:
1674 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1675 // the shifted type.
1676 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1677 if (SA != RHS) {
1678 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1679 << RHS << E->getType() << LHS.getBitWidth();
1680 } else if (LHS.isSigned()) {
1681 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1682 // operand, and must not overflow the corresponding unsigned type.
1683 if (LHS.isNegative())
1684 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1685 else if (LHS.countLeadingZeros() < SA)
1686 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1687 }
1688 Result = LHS << SA;
1689 return true;
1690 }
1691 case BO_Shr: {
1692 if (Info.getLangOpts().OpenCL)
1693 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1694 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1695 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1696 RHS.isUnsigned());
1697 else if (RHS.isSigned() && RHS.isNegative()) {
1698 // During constant-folding, a negative shift is an opposite shift. Such a
1699 // shift is not a constant expression.
1700 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1701 RHS = -RHS;
1702 goto shift_left;
1703 }
1704 shift_right:
1705 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1706 // shifted type.
1707 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1708 if (SA != RHS)
1709 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1710 << RHS << E->getType() << LHS.getBitWidth();
1711 Result = LHS >> SA;
1712 return true;
1713 }
1714
1715 case BO_LT: Result = LHS < RHS; return true;
1716 case BO_GT: Result = LHS > RHS; return true;
1717 case BO_LE: Result = LHS <= RHS; return true;
1718 case BO_GE: Result = LHS >= RHS; return true;
1719 case BO_EQ: Result = LHS == RHS; return true;
1720 case BO_NE: Result = LHS != RHS; return true;
1721 }
1722}
1723
Richard Smith861b5b52013-05-07 23:34:45 +00001724/// Perform the given binary floating-point operation, in-place, on LHS.
1725static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1726 APFloat &LHS, BinaryOperatorKind Opcode,
1727 const APFloat &RHS) {
1728 switch (Opcode) {
1729 default:
1730 Info.Diag(E);
1731 return false;
1732 case BO_Mul:
1733 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1734 break;
1735 case BO_Add:
1736 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1737 break;
1738 case BO_Sub:
1739 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1740 break;
1741 case BO_Div:
1742 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1743 break;
1744 }
1745
1746 if (LHS.isInfinity() || LHS.isNaN())
1747 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1748 return true;
1749}
1750
Richard Smitha8105bc2012-01-06 16:39:00 +00001751/// Cast an lvalue referring to a base subobject to a derived class, by
1752/// truncating the lvalue's path to the given length.
1753static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1754 const RecordDecl *TruncatedType,
1755 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001756 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001757
1758 // Check we actually point to a derived class object.
1759 if (TruncatedElements == D.Entries.size())
1760 return true;
1761 assert(TruncatedElements >= D.MostDerivedPathLength &&
1762 "not casting to a derived class");
1763 if (!Result.checkSubobject(Info, E, CSK_Derived))
1764 return false;
1765
1766 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001767 const RecordDecl *RD = TruncatedType;
1768 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001769 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001770 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1771 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001772 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001773 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001774 else
Richard Smithd62306a2011-11-10 06:34:14 +00001775 Result.Offset -= Layout.getBaseClassOffset(Base);
1776 RD = Base;
1777 }
Richard Smith027bf112011-11-17 22:56:20 +00001778 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001779 return true;
1780}
1781
John McCalld7bca762012-05-01 00:38:49 +00001782static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001783 const CXXRecordDecl *Derived,
1784 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001785 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001786 if (!RL) {
1787 if (Derived->isInvalidDecl()) return false;
1788 RL = &Info.Ctx.getASTRecordLayout(Derived);
1789 }
1790
Richard Smithd62306a2011-11-10 06:34:14 +00001791 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001792 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001793 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001794}
1795
Richard Smitha8105bc2012-01-06 16:39:00 +00001796static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001797 const CXXRecordDecl *DerivedDecl,
1798 const CXXBaseSpecifier *Base) {
1799 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1800
John McCalld7bca762012-05-01 00:38:49 +00001801 if (!Base->isVirtual())
1802 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001803
Richard Smitha8105bc2012-01-06 16:39:00 +00001804 SubobjectDesignator &D = Obj.Designator;
1805 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001806 return false;
1807
Richard Smitha8105bc2012-01-06 16:39:00 +00001808 // Extract most-derived object and corresponding type.
1809 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1810 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1811 return false;
1812
1813 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001814 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001815 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1816 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001817 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001818 return true;
1819}
1820
Richard Smith84401042013-06-03 05:03:02 +00001821static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1822 QualType Type, LValue &Result) {
1823 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1824 PathE = E->path_end();
1825 PathI != PathE; ++PathI) {
1826 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1827 *PathI))
1828 return false;
1829 Type = (*PathI)->getType();
1830 }
1831 return true;
1832}
1833
Richard Smithd62306a2011-11-10 06:34:14 +00001834/// Update LVal to refer to the given field, which must be a member of the type
1835/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001836static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001837 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001838 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001839 if (!RL) {
1840 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001841 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001842 }
Richard Smithd62306a2011-11-10 06:34:14 +00001843
1844 unsigned I = FD->getFieldIndex();
1845 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001846 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001847 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001848}
1849
Richard Smith1b78b3d2012-01-25 22:15:11 +00001850/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001851static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001852 LValue &LVal,
1853 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001854 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001855 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001856 return false;
1857 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001858}
1859
Richard Smithd62306a2011-11-10 06:34:14 +00001860/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001861static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1862 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001863 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1864 // extension.
1865 if (Type->isVoidType() || Type->isFunctionType()) {
1866 Size = CharUnits::One();
1867 return true;
1868 }
1869
1870 if (!Type->isConstantSizeType()) {
1871 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001872 // FIXME: Better diagnostic.
1873 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001874 return false;
1875 }
1876
1877 Size = Info.Ctx.getTypeSizeInChars(Type);
1878 return true;
1879}
1880
1881/// Update a pointer value to model pointer arithmetic.
1882/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001883/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001884/// \param LVal - The pointer value to be updated.
1885/// \param EltTy - The pointee type represented by LVal.
1886/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001887static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1888 LValue &LVal, QualType EltTy,
1889 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001890 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001891 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001892 return false;
1893
1894 // Compute the new offset in the appropriate width.
1895 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001896 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001897 return true;
1898}
1899
Richard Smith66c96992012-02-18 22:04:06 +00001900/// Update an lvalue to refer to a component of a complex number.
1901/// \param Info - Information about the ongoing evaluation.
1902/// \param LVal - The lvalue to be updated.
1903/// \param EltTy - The complex number's component type.
1904/// \param Imag - False for the real component, true for the imaginary.
1905static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1906 LValue &LVal, QualType EltTy,
1907 bool Imag) {
1908 if (Imag) {
1909 CharUnits SizeOfComponent;
1910 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1911 return false;
1912 LVal.Offset += SizeOfComponent;
1913 }
1914 LVal.addComplex(Info, E, EltTy, Imag);
1915 return true;
1916}
1917
Richard Smith27908702011-10-24 17:54:18 +00001918/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001919///
1920/// \param Info Information about the ongoing evaluation.
1921/// \param E An expression to be used when printing diagnostics.
1922/// \param VD The variable whose initializer should be obtained.
1923/// \param Frame The frame in which the variable was created. Must be null
1924/// if this variable is not local to the evaluation.
1925/// \param Result Filled in with a pointer to the value of the variable.
1926static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1927 const VarDecl *VD, CallStackFrame *Frame,
1928 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001929 // If this is a parameter to an active constexpr function call, perform
1930 // argument substitution.
1931 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001932 // Assume arguments of a potential constant expression are unknown
1933 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001934 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001935 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001936 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001937 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001938 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001939 }
Richard Smith3229b742013-05-05 21:17:10 +00001940 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001941 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001942 }
Richard Smith27908702011-10-24 17:54:18 +00001943
Richard Smithd9f663b2013-04-22 15:31:51 +00001944 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001945 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001946 Result = Frame->getTemporary(VD);
1947 assert(Result && "missing value for local variable");
1948 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001949 }
1950
Richard Smithd0b4dd62011-12-19 06:19:21 +00001951 // Dig out the initializer, and use the declaration which it's attached to.
1952 const Expr *Init = VD->getAnyInitializer(VD);
1953 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001954 // If we're checking a potential constant expression, the variable could be
1955 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001956 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001957 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001958 return false;
1959 }
1960
Richard Smithd62306a2011-11-10 06:34:14 +00001961 // If we're currently evaluating the initializer of this declaration, use that
1962 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001963 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001964 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001965 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001966 }
1967
Richard Smithcecf1842011-11-01 21:06:14 +00001968 // Never evaluate the initializer of a weak variable. We can't be sure that
1969 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001970 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001971 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001972 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001973 }
Richard Smithcecf1842011-11-01 21:06:14 +00001974
Richard Smithd0b4dd62011-12-19 06:19:21 +00001975 // Check that we can fold the initializer. In C++, we will have already done
1976 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001977 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001978 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001979 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001980 Notes.size() + 1) << VD;
1981 Info.Note(VD->getLocation(), diag::note_declared_at);
1982 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001983 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001984 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001985 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001986 Notes.size() + 1) << VD;
1987 Info.Note(VD->getLocation(), diag::note_declared_at);
1988 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001989 }
Richard Smith27908702011-10-24 17:54:18 +00001990
Richard Smith3229b742013-05-05 21:17:10 +00001991 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001992 return true;
Richard Smith27908702011-10-24 17:54:18 +00001993}
1994
Richard Smith11562c52011-10-28 17:51:58 +00001995static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001996 Qualifiers Quals = T.getQualifiers();
1997 return Quals.hasConst() && !Quals.hasVolatile();
1998}
1999
Richard Smithe97cbd72011-11-11 04:05:33 +00002000/// Get the base index of the given base class within an APValue representing
2001/// the given derived class.
2002static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2003 const CXXRecordDecl *Base) {
2004 Base = Base->getCanonicalDecl();
2005 unsigned Index = 0;
2006 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2007 E = Derived->bases_end(); I != E; ++I, ++Index) {
2008 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2009 return Index;
2010 }
2011
2012 llvm_unreachable("base class missing from derived class's bases list");
2013}
2014
Richard Smith3da88fa2013-04-26 14:36:30 +00002015/// Extract the value of a character from a string literal.
2016static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2017 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00002018 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00002019 const StringLiteral *S = cast<StringLiteral>(Lit);
2020 const ConstantArrayType *CAT =
2021 Info.Ctx.getAsConstantArrayType(S->getType());
2022 assert(CAT && "string literal isn't an array");
2023 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002024 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002025
2026 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002027 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002028 if (Index < S->getLength())
2029 Value = S->getCodeUnit(Index);
2030 return Value;
2031}
2032
Richard Smith3da88fa2013-04-26 14:36:30 +00002033// Expand a string literal into an array of characters.
2034static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2035 APValue &Result) {
2036 const StringLiteral *S = cast<StringLiteral>(Lit);
2037 const ConstantArrayType *CAT =
2038 Info.Ctx.getAsConstantArrayType(S->getType());
2039 assert(CAT && "string literal isn't an array");
2040 QualType CharType = CAT->getElementType();
2041 assert(CharType->isIntegerType() && "unexpected character type");
2042
2043 unsigned Elts = CAT->getSize().getZExtValue();
2044 Result = APValue(APValue::UninitArray(),
2045 std::min(S->getLength(), Elts), Elts);
2046 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2047 CharType->isUnsignedIntegerType());
2048 if (Result.hasArrayFiller())
2049 Result.getArrayFiller() = APValue(Value);
2050 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2051 Value = S->getCodeUnit(I);
2052 Result.getArrayInitializedElt(I) = APValue(Value);
2053 }
2054}
2055
2056// Expand an array so that it has more than Index filled elements.
2057static void expandArray(APValue &Array, unsigned Index) {
2058 unsigned Size = Array.getArraySize();
2059 assert(Index < Size);
2060
2061 // Always at least double the number of elements for which we store a value.
2062 unsigned OldElts = Array.getArrayInitializedElts();
2063 unsigned NewElts = std::max(Index+1, OldElts * 2);
2064 NewElts = std::min(Size, std::max(NewElts, 8u));
2065
2066 // Copy the data across.
2067 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2068 for (unsigned I = 0; I != OldElts; ++I)
2069 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2070 for (unsigned I = OldElts; I != NewElts; ++I)
2071 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2072 if (NewValue.hasArrayFiller())
2073 NewValue.getArrayFiller() = Array.getArrayFiller();
2074 Array.swap(NewValue);
2075}
2076
Richard Smith861b5b52013-05-07 23:34:45 +00002077/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002078enum AccessKinds {
2079 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002080 AK_Assign,
2081 AK_Increment,
2082 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002083};
2084
Richard Smith3229b742013-05-05 21:17:10 +00002085/// A handle to a complete object (an object that is not a subobject of
2086/// another object).
2087struct CompleteObject {
2088 /// The value of the complete object.
2089 APValue *Value;
2090 /// The type of the complete object.
2091 QualType Type;
2092
Craig Topper36250ad2014-05-12 05:36:57 +00002093 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002094 CompleteObject(APValue *Value, QualType Type)
2095 : Value(Value), Type(Type) {
2096 assert(Value && "missing value for complete object");
2097 }
2098
David Blaikie7d170102013-05-15 07:37:26 +00002099 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002100};
2101
Richard Smith3da88fa2013-04-26 14:36:30 +00002102/// Find the designated sub-object of an rvalue.
2103template<typename SubobjectHandler>
2104typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002105findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002106 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002107 if (Sub.Invalid)
2108 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002109 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002110 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002111 if (Info.getLangOpts().CPlusPlus11)
2112 Info.Diag(E, diag::note_constexpr_access_past_end)
2113 << handler.AccessKind;
2114 else
2115 Info.Diag(E);
2116 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002117 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002118
Richard Smith3229b742013-05-05 21:17:10 +00002119 APValue *O = Obj.Value;
2120 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002121 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002122
Richard Smithd62306a2011-11-10 06:34:14 +00002123 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002124 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2125 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002126 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002127 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2128 return handler.failed();
2129 }
2130
Richard Smith49ca8aa2013-08-06 07:09:20 +00002131 if (I == N) {
2132 if (!handler.found(*O, ObjType))
2133 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002134
Richard Smith49ca8aa2013-08-06 07:09:20 +00002135 // If we modified a bit-field, truncate it to the right width.
2136 if (handler.AccessKind != AK_Read &&
2137 LastField && LastField->isBitField() &&
2138 !truncateBitfieldValue(Info, E, *O, LastField))
2139 return false;
2140
2141 return true;
2142 }
2143
Craig Topper36250ad2014-05-12 05:36:57 +00002144 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002145 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002146 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002147 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002148 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002149 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002150 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002151 // Note, it should not be possible to form a pointer with a valid
2152 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002153 if (Info.getLangOpts().CPlusPlus11)
2154 Info.Diag(E, diag::note_constexpr_access_past_end)
2155 << handler.AccessKind;
2156 else
2157 Info.Diag(E);
2158 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002159 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002160
2161 ObjType = CAT->getElementType();
2162
Richard Smith14a94132012-02-17 03:35:37 +00002163 // An array object is represented as either an Array APValue or as an
2164 // LValue which refers to a string literal.
2165 if (O->isLValue()) {
2166 assert(I == N - 1 && "extracting subobject of character?");
2167 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002168 if (handler.AccessKind != AK_Read)
2169 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2170 *O);
2171 else
2172 return handler.foundString(*O, ObjType, Index);
2173 }
2174
2175 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002176 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002177 else if (handler.AccessKind != AK_Read) {
2178 expandArray(*O, Index);
2179 O = &O->getArrayInitializedElt(Index);
2180 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002181 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002182 } else if (ObjType->isAnyComplexType()) {
2183 // Next subobject is a complex number.
2184 uint64_t Index = Sub.Entries[I].ArrayIndex;
2185 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002186 if (Info.getLangOpts().CPlusPlus11)
2187 Info.Diag(E, diag::note_constexpr_access_past_end)
2188 << handler.AccessKind;
2189 else
2190 Info.Diag(E);
2191 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002192 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002193
2194 bool WasConstQualified = ObjType.isConstQualified();
2195 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2196 if (WasConstQualified)
2197 ObjType.addConst();
2198
Richard Smith66c96992012-02-18 22:04:06 +00002199 assert(I == N - 1 && "extracting subobject of scalar?");
2200 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002201 return handler.found(Index ? O->getComplexIntImag()
2202 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002203 } else {
2204 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002205 return handler.found(Index ? O->getComplexFloatImag()
2206 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002207 }
Richard Smithd62306a2011-11-10 06:34:14 +00002208 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002209 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002210 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002211 << Field;
2212 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002213 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002214 }
2215
Richard Smithd62306a2011-11-10 06:34:14 +00002216 // Next subobject is a class, struct or union field.
2217 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2218 if (RD->isUnion()) {
2219 const FieldDecl *UnionField = O->getUnionField();
2220 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002221 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002222 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2223 << handler.AccessKind << Field << !UnionField << UnionField;
2224 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002225 }
Richard Smithd62306a2011-11-10 06:34:14 +00002226 O = &O->getUnionValue();
2227 } else
2228 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002229
2230 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002231 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002232 if (WasConstQualified && !Field->isMutable())
2233 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002234
2235 if (ObjType.isVolatileQualified()) {
2236 if (Info.getLangOpts().CPlusPlus) {
2237 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002238 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2239 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002240 Info.Note(Field->getLocation(), diag::note_declared_at);
2241 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002242 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002243 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002244 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002245 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002246
2247 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002248 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002249 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002250 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2251 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2252 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002253
2254 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002255 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002256 if (WasConstQualified)
2257 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002258 }
2259 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002260}
2261
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002262namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002263struct ExtractSubobjectHandler {
2264 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002265 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002266
2267 static const AccessKinds AccessKind = AK_Read;
2268
2269 typedef bool result_type;
2270 bool failed() { return false; }
2271 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002272 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002273 return true;
2274 }
2275 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002276 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002277 return true;
2278 }
2279 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002280 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002281 return true;
2282 }
2283 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002284 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002285 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2286 return true;
2287 }
2288};
Richard Smith3229b742013-05-05 21:17:10 +00002289} // end anonymous namespace
2290
Richard Smith3da88fa2013-04-26 14:36:30 +00002291const AccessKinds ExtractSubobjectHandler::AccessKind;
2292
2293/// Extract the designated sub-object of an rvalue.
2294static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002295 const CompleteObject &Obj,
2296 const SubobjectDesignator &Sub,
2297 APValue &Result) {
2298 ExtractSubobjectHandler Handler = { Info, Result };
2299 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002300}
2301
Richard Smith3229b742013-05-05 21:17:10 +00002302namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002303struct ModifySubobjectHandler {
2304 EvalInfo &Info;
2305 APValue &NewVal;
2306 const Expr *E;
2307
2308 typedef bool result_type;
2309 static const AccessKinds AccessKind = AK_Assign;
2310
2311 bool checkConst(QualType QT) {
2312 // Assigning to a const object has undefined behavior.
2313 if (QT.isConstQualified()) {
2314 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2315 return false;
2316 }
2317 return true;
2318 }
2319
2320 bool failed() { return false; }
2321 bool found(APValue &Subobj, QualType SubobjType) {
2322 if (!checkConst(SubobjType))
2323 return false;
2324 // We've been given ownership of NewVal, so just swap it in.
2325 Subobj.swap(NewVal);
2326 return true;
2327 }
2328 bool found(APSInt &Value, QualType SubobjType) {
2329 if (!checkConst(SubobjType))
2330 return false;
2331 if (!NewVal.isInt()) {
2332 // Maybe trying to write a cast pointer value into a complex?
2333 Info.Diag(E);
2334 return false;
2335 }
2336 Value = NewVal.getInt();
2337 return true;
2338 }
2339 bool found(APFloat &Value, QualType SubobjType) {
2340 if (!checkConst(SubobjType))
2341 return false;
2342 Value = NewVal.getFloat();
2343 return true;
2344 }
2345 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2346 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2347 }
2348};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002349} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002350
Richard Smith3229b742013-05-05 21:17:10 +00002351const AccessKinds ModifySubobjectHandler::AccessKind;
2352
Richard Smith3da88fa2013-04-26 14:36:30 +00002353/// Update the designated sub-object of an rvalue to the given value.
2354static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002355 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002356 const SubobjectDesignator &Sub,
2357 APValue &NewVal) {
2358 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002359 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002360}
2361
Richard Smith84f6dcf2012-02-02 01:16:57 +00002362/// Find the position where two subobject designators diverge, or equivalently
2363/// the length of the common initial subsequence.
2364static unsigned FindDesignatorMismatch(QualType ObjType,
2365 const SubobjectDesignator &A,
2366 const SubobjectDesignator &B,
2367 bool &WasArrayIndex) {
2368 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2369 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002370 if (!ObjType.isNull() &&
2371 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002372 // Next subobject is an array element.
2373 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2374 WasArrayIndex = true;
2375 return I;
2376 }
Richard Smith66c96992012-02-18 22:04:06 +00002377 if (ObjType->isAnyComplexType())
2378 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2379 else
2380 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002381 } else {
2382 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2383 WasArrayIndex = false;
2384 return I;
2385 }
2386 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2387 // Next subobject is a field.
2388 ObjType = FD->getType();
2389 else
2390 // Next subobject is a base class.
2391 ObjType = QualType();
2392 }
2393 }
2394 WasArrayIndex = false;
2395 return I;
2396}
2397
2398/// Determine whether the given subobject designators refer to elements of the
2399/// same array object.
2400static bool AreElementsOfSameArray(QualType ObjType,
2401 const SubobjectDesignator &A,
2402 const SubobjectDesignator &B) {
2403 if (A.Entries.size() != B.Entries.size())
2404 return false;
2405
2406 bool IsArray = A.MostDerivedArraySize != 0;
2407 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2408 // A is a subobject of the array element.
2409 return false;
2410
2411 // If A (and B) designates an array element, the last entry will be the array
2412 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2413 // of length 1' case, and the entire path must match.
2414 bool WasArrayIndex;
2415 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2416 return CommonLength >= A.Entries.size() - IsArray;
2417}
2418
Richard Smith3229b742013-05-05 21:17:10 +00002419/// Find the complete object to which an LValue refers.
2420CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2421 const LValue &LVal, QualType LValType) {
2422 if (!LVal.Base) {
2423 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2424 return CompleteObject();
2425 }
2426
Craig Topper36250ad2014-05-12 05:36:57 +00002427 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002428 if (LVal.CallIndex) {
2429 Frame = Info.getCallFrame(LVal.CallIndex);
2430 if (!Frame) {
2431 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2432 << AK << LVal.Base.is<const ValueDecl*>();
2433 NoteLValueLocation(Info, LVal.Base);
2434 return CompleteObject();
2435 }
Richard Smith3229b742013-05-05 21:17:10 +00002436 }
2437
2438 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2439 // is not a constant expression (even if the object is non-volatile). We also
2440 // apply this rule to C++98, in order to conform to the expected 'volatile'
2441 // semantics.
2442 if (LValType.isVolatileQualified()) {
2443 if (Info.getLangOpts().CPlusPlus)
2444 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2445 << AK << LValType;
2446 else
2447 Info.Diag(E);
2448 return CompleteObject();
2449 }
2450
2451 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002452 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002453 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002454
2455 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2456 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2457 // In C++11, constexpr, non-volatile variables initialized with constant
2458 // expressions are constant expressions too. Inside constexpr functions,
2459 // parameters are constant expressions even if they're non-const.
2460 // In C++1y, objects local to a constant expression (those with a Frame) are
2461 // both readable and writable inside constant expressions.
2462 // In C, such things can also be folded, although they are not ICEs.
2463 const VarDecl *VD = dyn_cast<VarDecl>(D);
2464 if (VD) {
2465 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2466 VD = VDef;
2467 }
2468 if (!VD || VD->isInvalidDecl()) {
2469 Info.Diag(E);
2470 return CompleteObject();
2471 }
2472
2473 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002474 if (BaseType.isVolatileQualified()) {
2475 if (Info.getLangOpts().CPlusPlus) {
2476 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2477 << AK << 1 << VD;
2478 Info.Note(VD->getLocation(), diag::note_declared_at);
2479 } else {
2480 Info.Diag(E);
2481 }
2482 return CompleteObject();
2483 }
2484
2485 // Unless we're looking at a local variable or argument in a constexpr call,
2486 // the variable we're reading must be const.
2487 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002488 if (Info.getLangOpts().CPlusPlus1y &&
2489 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2490 // OK, we can read and modify an object if we're in the process of
2491 // evaluating its initializer, because its lifetime began in this
2492 // evaluation.
2493 } else if (AK != AK_Read) {
2494 // All the remaining cases only permit reading.
2495 Info.Diag(E, diag::note_constexpr_modify_global);
2496 return CompleteObject();
2497 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002498 // OK, we can read this variable.
2499 } else if (BaseType->isIntegralOrEnumerationType()) {
2500 if (!BaseType.isConstQualified()) {
2501 if (Info.getLangOpts().CPlusPlus) {
2502 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2503 Info.Note(VD->getLocation(), diag::note_declared_at);
2504 } else {
2505 Info.Diag(E);
2506 }
2507 return CompleteObject();
2508 }
2509 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2510 // We support folding of const floating-point types, in order to make
2511 // static const data members of such types (supported as an extension)
2512 // more useful.
2513 if (Info.getLangOpts().CPlusPlus11) {
2514 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2515 Info.Note(VD->getLocation(), diag::note_declared_at);
2516 } else {
2517 Info.CCEDiag(E);
2518 }
2519 } else {
2520 // FIXME: Allow folding of values of any literal type in all languages.
2521 if (Info.getLangOpts().CPlusPlus11) {
2522 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2523 Info.Note(VD->getLocation(), diag::note_declared_at);
2524 } else {
2525 Info.Diag(E);
2526 }
2527 return CompleteObject();
2528 }
2529 }
2530
2531 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2532 return CompleteObject();
2533 } else {
2534 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2535
2536 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002537 if (const MaterializeTemporaryExpr *MTE =
2538 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2539 assert(MTE->getStorageDuration() == SD_Static &&
2540 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002541
Richard Smithe6c01442013-06-05 00:46:14 +00002542 // Per C++1y [expr.const]p2:
2543 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2544 // - a [...] glvalue of integral or enumeration type that refers to
2545 // a non-volatile const object [...]
2546 // [...]
2547 // - a [...] glvalue of literal type that refers to a non-volatile
2548 // object whose lifetime began within the evaluation of e.
2549 //
2550 // C++11 misses the 'began within the evaluation of e' check and
2551 // instead allows all temporaries, including things like:
2552 // int &&r = 1;
2553 // int x = ++r;
2554 // constexpr int k = r;
2555 // Therefore we use the C++1y rules in C++11 too.
2556 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2557 const ValueDecl *ED = MTE->getExtendingDecl();
2558 if (!(BaseType.isConstQualified() &&
2559 BaseType->isIntegralOrEnumerationType()) &&
2560 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2561 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2562 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2563 return CompleteObject();
2564 }
2565
2566 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2567 assert(BaseVal && "got reference to unevaluated temporary");
2568 } else {
2569 Info.Diag(E);
2570 return CompleteObject();
2571 }
2572 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002573 BaseVal = Frame->getTemporary(Base);
2574 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002575 }
Richard Smith3229b742013-05-05 21:17:10 +00002576
2577 // Volatile temporary objects cannot be accessed in constant expressions.
2578 if (BaseType.isVolatileQualified()) {
2579 if (Info.getLangOpts().CPlusPlus) {
2580 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2581 << AK << 0;
2582 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2583 } else {
2584 Info.Diag(E);
2585 }
2586 return CompleteObject();
2587 }
2588 }
2589
Richard Smith7525ff62013-05-09 07:14:00 +00002590 // During the construction of an object, it is not yet 'const'.
2591 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2592 // and this doesn't do quite the right thing for const subobjects of the
2593 // object under construction.
2594 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2595 BaseType = Info.Ctx.getCanonicalType(BaseType);
2596 BaseType.removeLocalConst();
2597 }
2598
Richard Smith6d4c6582013-11-05 22:18:15 +00002599 // In C++1y, we can't safely access any mutable state when we might be
2600 // evaluating after an unmodeled side effect or an evaluation failure.
2601 //
2602 // FIXME: Not all local state is mutable. Allow local constant subobjects
2603 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002604 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002605 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002606 return CompleteObject();
2607
2608 return CompleteObject(BaseVal, BaseType);
2609}
2610
Richard Smith243ef902013-05-05 23:31:59 +00002611/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2612/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2613/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002614///
2615/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002616/// \param Conv - The expression for which we are performing the conversion.
2617/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002618/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2619/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002620/// \param LVal - The glvalue on which we are attempting to perform this action.
2621/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002622static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002623 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002624 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002625 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002626 return false;
2627
Richard Smith3229b742013-05-05 21:17:10 +00002628 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002629 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002630 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2631 !Type.isVolatileQualified()) {
2632 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2633 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2634 // initializer until now for such expressions. Such an expression can't be
2635 // an ICE in C, so this only matters for fold.
2636 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2637 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002638 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002639 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002640 }
Richard Smith3229b742013-05-05 21:17:10 +00002641 APValue Lit;
2642 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2643 return false;
2644 CompleteObject LitObj(&Lit, Base->getType());
2645 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2646 } else if (isa<StringLiteral>(Base)) {
2647 // We represent a string literal array as an lvalue pointing at the
2648 // corresponding expression, rather than building an array of chars.
2649 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2650 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2651 CompleteObject StrObj(&Str, Base->getType());
2652 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002653 }
Richard Smith11562c52011-10-28 17:51:58 +00002654 }
2655
Richard Smith3229b742013-05-05 21:17:10 +00002656 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2657 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002658}
2659
2660/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002661static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002662 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002663 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 return false;
2665
Richard Smith3229b742013-05-05 21:17:10 +00002666 if (!Info.getLangOpts().CPlusPlus1y) {
2667 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002668 return false;
2669 }
2670
Richard Smith3229b742013-05-05 21:17:10 +00002671 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2672 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002673}
2674
Richard Smith243ef902013-05-05 23:31:59 +00002675static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2676 return T->isSignedIntegerType() &&
2677 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2678}
2679
2680namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002681struct CompoundAssignSubobjectHandler {
2682 EvalInfo &Info;
2683 const Expr *E;
2684 QualType PromotedLHSType;
2685 BinaryOperatorKind Opcode;
2686 const APValue &RHS;
2687
2688 static const AccessKinds AccessKind = AK_Assign;
2689
2690 typedef bool result_type;
2691
2692 bool checkConst(QualType QT) {
2693 // Assigning to a const object has undefined behavior.
2694 if (QT.isConstQualified()) {
2695 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2696 return false;
2697 }
2698 return true;
2699 }
2700
2701 bool failed() { return false; }
2702 bool found(APValue &Subobj, QualType SubobjType) {
2703 switch (Subobj.getKind()) {
2704 case APValue::Int:
2705 return found(Subobj.getInt(), SubobjType);
2706 case APValue::Float:
2707 return found(Subobj.getFloat(), SubobjType);
2708 case APValue::ComplexInt:
2709 case APValue::ComplexFloat:
2710 // FIXME: Implement complex compound assignment.
2711 Info.Diag(E);
2712 return false;
2713 case APValue::LValue:
2714 return foundPointer(Subobj, SubobjType);
2715 default:
2716 // FIXME: can this happen?
2717 Info.Diag(E);
2718 return false;
2719 }
2720 }
2721 bool found(APSInt &Value, QualType SubobjType) {
2722 if (!checkConst(SubobjType))
2723 return false;
2724
2725 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2726 // We don't support compound assignment on integer-cast-to-pointer
2727 // values.
2728 Info.Diag(E);
2729 return false;
2730 }
2731
2732 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2733 SubobjType, Value);
2734 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2735 return false;
2736 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2737 return true;
2738 }
2739 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002740 return checkConst(SubobjType) &&
2741 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2742 Value) &&
2743 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2744 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002745 }
2746 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2747 if (!checkConst(SubobjType))
2748 return false;
2749
2750 QualType PointeeType;
2751 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2752 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002753
2754 if (PointeeType.isNull() || !RHS.isInt() ||
2755 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002756 Info.Diag(E);
2757 return false;
2758 }
2759
Richard Smith861b5b52013-05-07 23:34:45 +00002760 int64_t Offset = getExtValue(RHS.getInt());
2761 if (Opcode == BO_Sub)
2762 Offset = -Offset;
2763
2764 LValue LVal;
2765 LVal.setFrom(Info.Ctx, Subobj);
2766 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2767 return false;
2768 LVal.moveInto(Subobj);
2769 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002770 }
2771 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2772 llvm_unreachable("shouldn't encounter string elements here");
2773 }
2774};
2775} // end anonymous namespace
2776
2777const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2778
2779/// Perform a compound assignment of LVal <op>= RVal.
2780static bool handleCompoundAssignment(
2781 EvalInfo &Info, const Expr *E,
2782 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2783 BinaryOperatorKind Opcode, const APValue &RVal) {
2784 if (LVal.Designator.Invalid)
2785 return false;
2786
2787 if (!Info.getLangOpts().CPlusPlus1y) {
2788 Info.Diag(E);
2789 return false;
2790 }
2791
2792 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2793 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2794 RVal };
2795 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2796}
2797
2798namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002799struct IncDecSubobjectHandler {
2800 EvalInfo &Info;
2801 const Expr *E;
2802 AccessKinds AccessKind;
2803 APValue *Old;
2804
2805 typedef bool result_type;
2806
2807 bool checkConst(QualType QT) {
2808 // Assigning to a const object has undefined behavior.
2809 if (QT.isConstQualified()) {
2810 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2811 return false;
2812 }
2813 return true;
2814 }
2815
2816 bool failed() { return false; }
2817 bool found(APValue &Subobj, QualType SubobjType) {
2818 // Stash the old value. Also clear Old, so we don't clobber it later
2819 // if we're post-incrementing a complex.
2820 if (Old) {
2821 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002822 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002823 }
2824
2825 switch (Subobj.getKind()) {
2826 case APValue::Int:
2827 return found(Subobj.getInt(), SubobjType);
2828 case APValue::Float:
2829 return found(Subobj.getFloat(), SubobjType);
2830 case APValue::ComplexInt:
2831 return found(Subobj.getComplexIntReal(),
2832 SubobjType->castAs<ComplexType>()->getElementType()
2833 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2834 case APValue::ComplexFloat:
2835 return found(Subobj.getComplexFloatReal(),
2836 SubobjType->castAs<ComplexType>()->getElementType()
2837 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2838 case APValue::LValue:
2839 return foundPointer(Subobj, SubobjType);
2840 default:
2841 // FIXME: can this happen?
2842 Info.Diag(E);
2843 return false;
2844 }
2845 }
2846 bool found(APSInt &Value, QualType SubobjType) {
2847 if (!checkConst(SubobjType))
2848 return false;
2849
2850 if (!SubobjType->isIntegerType()) {
2851 // We don't support increment / decrement on integer-cast-to-pointer
2852 // values.
2853 Info.Diag(E);
2854 return false;
2855 }
2856
2857 if (Old) *Old = APValue(Value);
2858
2859 // bool arithmetic promotes to int, and the conversion back to bool
2860 // doesn't reduce mod 2^n, so special-case it.
2861 if (SubobjType->isBooleanType()) {
2862 if (AccessKind == AK_Increment)
2863 Value = 1;
2864 else
2865 Value = !Value;
2866 return true;
2867 }
2868
2869 bool WasNegative = Value.isNegative();
2870 if (AccessKind == AK_Increment) {
2871 ++Value;
2872
2873 if (!WasNegative && Value.isNegative() &&
2874 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2875 APSInt ActualValue(Value, /*IsUnsigned*/true);
2876 HandleOverflow(Info, E, ActualValue, SubobjType);
2877 }
2878 } else {
2879 --Value;
2880
2881 if (WasNegative && !Value.isNegative() &&
2882 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2883 unsigned BitWidth = Value.getBitWidth();
2884 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2885 ActualValue.setBit(BitWidth);
2886 HandleOverflow(Info, E, ActualValue, SubobjType);
2887 }
2888 }
2889 return true;
2890 }
2891 bool found(APFloat &Value, QualType SubobjType) {
2892 if (!checkConst(SubobjType))
2893 return false;
2894
2895 if (Old) *Old = APValue(Value);
2896
2897 APFloat One(Value.getSemantics(), 1);
2898 if (AccessKind == AK_Increment)
2899 Value.add(One, APFloat::rmNearestTiesToEven);
2900 else
2901 Value.subtract(One, APFloat::rmNearestTiesToEven);
2902 return true;
2903 }
2904 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2905 if (!checkConst(SubobjType))
2906 return false;
2907
2908 QualType PointeeType;
2909 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2910 PointeeType = PT->getPointeeType();
2911 else {
2912 Info.Diag(E);
2913 return false;
2914 }
2915
2916 LValue LVal;
2917 LVal.setFrom(Info.Ctx, Subobj);
2918 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2919 AccessKind == AK_Increment ? 1 : -1))
2920 return false;
2921 LVal.moveInto(Subobj);
2922 return true;
2923 }
2924 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2925 llvm_unreachable("shouldn't encounter string elements here");
2926 }
2927};
2928} // end anonymous namespace
2929
2930/// Perform an increment or decrement on LVal.
2931static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2932 QualType LValType, bool IsIncrement, APValue *Old) {
2933 if (LVal.Designator.Invalid)
2934 return false;
2935
2936 if (!Info.getLangOpts().CPlusPlus1y) {
2937 Info.Diag(E);
2938 return false;
2939 }
2940
2941 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2942 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2943 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2944 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2945}
2946
Richard Smithe97cbd72011-11-11 04:05:33 +00002947/// Build an lvalue for the object argument of a member function call.
2948static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2949 LValue &This) {
2950 if (Object->getType()->isPointerType())
2951 return EvaluatePointer(Object, This, Info);
2952
2953 if (Object->isGLValue())
2954 return EvaluateLValue(Object, This, Info);
2955
Richard Smithd9f663b2013-04-22 15:31:51 +00002956 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002957 return EvaluateTemporary(Object, This, Info);
2958
Richard Smith3e79a572014-06-11 19:53:12 +00002959 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002960 return false;
2961}
2962
2963/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2964/// lvalue referring to the result.
2965///
2966/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002967/// \param LV - An lvalue referring to the base of the member pointer.
2968/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002969/// \param IncludeMember - Specifies whether the member itself is included in
2970/// the resulting LValue subobject designator. This is not possible when
2971/// creating a bound member function.
2972/// \return The field or method declaration to which the member pointer refers,
2973/// or 0 if evaluation fails.
2974static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002975 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002976 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002977 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002978 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002979 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002980 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00002981 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00002982
2983 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2984 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002985 if (!MemPtr.getDecl()) {
2986 // FIXME: Specific diagnostic.
2987 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002988 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002989 }
Richard Smith253c2a32012-01-27 01:14:48 +00002990
Richard Smith027bf112011-11-17 22:56:20 +00002991 if (MemPtr.isDerivedMember()) {
2992 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002993 // The end of the derived-to-base path for the base object must match the
2994 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002995 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002996 LV.Designator.Entries.size()) {
2997 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00002998 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002999 }
Richard Smith027bf112011-11-17 22:56:20 +00003000 unsigned PathLengthToMember =
3001 LV.Designator.Entries.size() - MemPtr.Path.size();
3002 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3003 const CXXRecordDecl *LVDecl = getAsBaseClass(
3004 LV.Designator.Entries[PathLengthToMember + I]);
3005 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003006 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3007 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003008 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003009 }
Richard Smith027bf112011-11-17 22:56:20 +00003010 }
3011
3012 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003013 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003014 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003015 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003016 } else if (!MemPtr.Path.empty()) {
3017 // Extend the LValue path with the member pointer's path.
3018 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3019 MemPtr.Path.size() + IncludeMember);
3020
3021 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003022 if (const PointerType *PT = LVType->getAs<PointerType>())
3023 LVType = PT->getPointeeType();
3024 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3025 assert(RD && "member pointer access on non-class-type expression");
3026 // The first class in the path is that of the lvalue.
3027 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3028 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003029 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003030 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003031 RD = Base;
3032 }
3033 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003034 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3035 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003036 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003037 }
3038
3039 // Add the member. Note that we cannot build bound member functions here.
3040 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003041 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003042 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003043 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003044 } else if (const IndirectFieldDecl *IFD =
3045 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003046 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003047 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003048 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003049 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003050 }
Richard Smith027bf112011-11-17 22:56:20 +00003051 }
3052
3053 return MemPtr.getDecl();
3054}
3055
Richard Smith84401042013-06-03 05:03:02 +00003056static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3057 const BinaryOperator *BO,
3058 LValue &LV,
3059 bool IncludeMember = true) {
3060 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3061
3062 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3063 if (Info.keepEvaluatingAfterFailure()) {
3064 MemberPtr MemPtr;
3065 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3066 }
Craig Topper36250ad2014-05-12 05:36:57 +00003067 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003068 }
3069
3070 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3071 BO->getRHS(), IncludeMember);
3072}
3073
Richard Smith027bf112011-11-17 22:56:20 +00003074/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3075/// the provided lvalue, which currently refers to the base object.
3076static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3077 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003078 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003079 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003080 return false;
3081
Richard Smitha8105bc2012-01-06 16:39:00 +00003082 QualType TargetQT = E->getType();
3083 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3084 TargetQT = PT->getPointeeType();
3085
3086 // Check this cast lands within the final derived-to-base subobject path.
3087 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003088 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003089 << D.MostDerivedType << TargetQT;
3090 return false;
3091 }
3092
Richard Smith027bf112011-11-17 22:56:20 +00003093 // Check the type of the final cast. We don't need to check the path,
3094 // since a cast can only be formed if the path is unique.
3095 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003096 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3097 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003098 if (NewEntriesSize == D.MostDerivedPathLength)
3099 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3100 else
Richard Smith027bf112011-11-17 22:56:20 +00003101 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003102 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003103 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003104 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003105 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003106 }
Richard Smith027bf112011-11-17 22:56:20 +00003107
3108 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003109 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003110}
3111
Mike Stump876387b2009-10-27 22:09:17 +00003112namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003113enum EvalStmtResult {
3114 /// Evaluation failed.
3115 ESR_Failed,
3116 /// Hit a 'return' statement.
3117 ESR_Returned,
3118 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003119 ESR_Succeeded,
3120 /// Hit a 'continue' statement.
3121 ESR_Continue,
3122 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003123 ESR_Break,
3124 /// Still scanning for 'case' or 'default' statement.
3125 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003126};
3127}
3128
Richard Smithd9f663b2013-04-22 15:31:51 +00003129static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3130 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3131 // We don't need to evaluate the initializer for a static local.
3132 if (!VD->hasLocalStorage())
3133 return true;
3134
3135 LValue Result;
3136 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003137 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003138
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003139 const Expr *InitE = VD->getInit();
3140 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003141 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3142 << false << VD->getType();
3143 Val = APValue();
3144 return false;
3145 }
3146
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003147 if (InitE->isValueDependent())
3148 return false;
3149
3150 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003151 // Wipe out any partially-computed value, to allow tracking that this
3152 // evaluation failed.
3153 Val = APValue();
3154 return false;
3155 }
3156 }
3157
3158 return true;
3159}
3160
Richard Smith4e18ca52013-05-06 05:56:11 +00003161/// Evaluate a condition (either a variable declaration or an expression).
3162static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3163 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003164 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003165 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3166 return false;
3167 return EvaluateAsBooleanCondition(Cond, Result, Info);
3168}
3169
3170static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003171 const Stmt *S,
3172 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003173
3174/// Evaluate the body of a loop, and translate the result as appropriate.
3175static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003176 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003177 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003178 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003179 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003180 case ESR_Break:
3181 return ESR_Succeeded;
3182 case ESR_Succeeded:
3183 case ESR_Continue:
3184 return ESR_Continue;
3185 case ESR_Failed:
3186 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003187 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003188 return ESR;
3189 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003190 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003191}
3192
Richard Smith496ddcf2013-05-12 17:32:42 +00003193/// Evaluate a switch statement.
3194static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3195 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003196 BlockScopeRAII Scope(Info);
3197
Richard Smith496ddcf2013-05-12 17:32:42 +00003198 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003199 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003200 {
3201 FullExpressionRAII Scope(Info);
3202 if (SS->getConditionVariable() &&
3203 !EvaluateDecl(Info, SS->getConditionVariable()))
3204 return ESR_Failed;
3205 if (!EvaluateInteger(SS->getCond(), Value, Info))
3206 return ESR_Failed;
3207 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003208
3209 // Find the switch case corresponding to the value of the condition.
3210 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003211 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003212 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3213 SC = SC->getNextSwitchCase()) {
3214 if (isa<DefaultStmt>(SC)) {
3215 Found = SC;
3216 continue;
3217 }
3218
3219 const CaseStmt *CS = cast<CaseStmt>(SC);
3220 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3221 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3222 : LHS;
3223 if (LHS <= Value && Value <= RHS) {
3224 Found = SC;
3225 break;
3226 }
3227 }
3228
3229 if (!Found)
3230 return ESR_Succeeded;
3231
3232 // Search the switch body for the switch case and evaluate it from there.
3233 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3234 case ESR_Break:
3235 return ESR_Succeeded;
3236 case ESR_Succeeded:
3237 case ESR_Continue:
3238 case ESR_Failed:
3239 case ESR_Returned:
3240 return ESR;
3241 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003242 // This can only happen if the switch case is nested within a statement
3243 // expression. We have no intention of supporting that.
3244 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3245 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003246 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003247 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003248}
3249
Richard Smith254a73d2011-10-28 22:34:42 +00003250// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003251static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003252 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003253 if (!Info.nextStep(S))
3254 return ESR_Failed;
3255
Richard Smith496ddcf2013-05-12 17:32:42 +00003256 // If we're hunting down a 'case' or 'default' label, recurse through
3257 // substatements until we hit the label.
3258 if (Case) {
3259 // FIXME: We don't start the lifetime of objects whose initialization we
3260 // jump over. However, such objects must be of class type with a trivial
3261 // default constructor that initialize all subobjects, so must be empty,
3262 // so this almost never matters.
3263 switch (S->getStmtClass()) {
3264 case Stmt::CompoundStmtClass:
3265 // FIXME: Precompute which substatement of a compound statement we
3266 // would jump to, and go straight there rather than performing a
3267 // linear scan each time.
3268 case Stmt::LabelStmtClass:
3269 case Stmt::AttributedStmtClass:
3270 case Stmt::DoStmtClass:
3271 break;
3272
3273 case Stmt::CaseStmtClass:
3274 case Stmt::DefaultStmtClass:
3275 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003276 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003277 break;
3278
3279 case Stmt::IfStmtClass: {
3280 // FIXME: Precompute which side of an 'if' we would jump to, and go
3281 // straight there rather than scanning both sides.
3282 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003283
3284 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3285 // preceded by our switch label.
3286 BlockScopeRAII Scope(Info);
3287
Richard Smith496ddcf2013-05-12 17:32:42 +00003288 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3289 if (ESR != ESR_CaseNotFound || !IS->getElse())
3290 return ESR;
3291 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3292 }
3293
3294 case Stmt::WhileStmtClass: {
3295 EvalStmtResult ESR =
3296 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3297 if (ESR != ESR_Continue)
3298 return ESR;
3299 break;
3300 }
3301
3302 case Stmt::ForStmtClass: {
3303 const ForStmt *FS = cast<ForStmt>(S);
3304 EvalStmtResult ESR =
3305 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3306 if (ESR != ESR_Continue)
3307 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 if (FS->getInc()) {
3309 FullExpressionRAII IncScope(Info);
3310 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3311 return ESR_Failed;
3312 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003313 break;
3314 }
3315
3316 case Stmt::DeclStmtClass:
3317 // FIXME: If the variable has initialization that can't be jumped over,
3318 // bail out of any immediately-surrounding compound-statement too.
3319 default:
3320 return ESR_CaseNotFound;
3321 }
3322 }
3323
Richard Smith254a73d2011-10-28 22:34:42 +00003324 switch (S->getStmtClass()) {
3325 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003326 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003327 // Don't bother evaluating beyond an expression-statement which couldn't
3328 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003329 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003330 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003331 return ESR_Failed;
3332 return ESR_Succeeded;
3333 }
3334
3335 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003336 return ESR_Failed;
3337
3338 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003339 return ESR_Succeeded;
3340
Richard Smithd9f663b2013-04-22 15:31:51 +00003341 case Stmt::DeclStmtClass: {
3342 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003343 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003344 // Each declaration initialization is its own full-expression.
3345 // FIXME: This isn't quite right; if we're performing aggregate
3346 // initialization, each braced subexpression is its own full-expression.
3347 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003348 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003349 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003350 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003351 return ESR_Succeeded;
3352 }
3353
Richard Smith357362d2011-12-13 06:39:58 +00003354 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003355 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003356 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003357 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003358 return ESR_Failed;
3359 return ESR_Returned;
3360 }
Richard Smith254a73d2011-10-28 22:34:42 +00003361
3362 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003363 BlockScopeRAII Scope(Info);
3364
Richard Smith254a73d2011-10-28 22:34:42 +00003365 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003366 for (const auto *BI : CS->body()) {
3367 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003368 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003369 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003370 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003371 return ESR;
3372 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003373 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003374 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003375
3376 case Stmt::IfStmtClass: {
3377 const IfStmt *IS = cast<IfStmt>(S);
3378
3379 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003380 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003381 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003382 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003383 return ESR_Failed;
3384
3385 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3386 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3387 if (ESR != ESR_Succeeded)
3388 return ESR;
3389 }
3390 return ESR_Succeeded;
3391 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003392
3393 case Stmt::WhileStmtClass: {
3394 const WhileStmt *WS = cast<WhileStmt>(S);
3395 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003396 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003397 bool Continue;
3398 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3399 Continue))
3400 return ESR_Failed;
3401 if (!Continue)
3402 break;
3403
3404 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3405 if (ESR != ESR_Continue)
3406 return ESR;
3407 }
3408 return ESR_Succeeded;
3409 }
3410
3411 case Stmt::DoStmtClass: {
3412 const DoStmt *DS = cast<DoStmt>(S);
3413 bool Continue;
3414 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003415 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003416 if (ESR != ESR_Continue)
3417 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003418 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003419
Richard Smith08d6a2c2013-07-24 07:11:57 +00003420 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003421 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3422 return ESR_Failed;
3423 } while (Continue);
3424 return ESR_Succeeded;
3425 }
3426
3427 case Stmt::ForStmtClass: {
3428 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003429 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003430 if (FS->getInit()) {
3431 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3432 if (ESR != ESR_Succeeded)
3433 return ESR;
3434 }
3435 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003436 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003437 bool Continue = true;
3438 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3439 FS->getCond(), Continue))
3440 return ESR_Failed;
3441 if (!Continue)
3442 break;
3443
3444 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3445 if (ESR != ESR_Continue)
3446 return ESR;
3447
Richard Smith08d6a2c2013-07-24 07:11:57 +00003448 if (FS->getInc()) {
3449 FullExpressionRAII IncScope(Info);
3450 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3451 return ESR_Failed;
3452 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003453 }
3454 return ESR_Succeeded;
3455 }
3456
Richard Smith896e0d72013-05-06 06:51:17 +00003457 case Stmt::CXXForRangeStmtClass: {
3458 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003459 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003460
3461 // Initialize the __range variable.
3462 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3463 if (ESR != ESR_Succeeded)
3464 return ESR;
3465
3466 // Create the __begin and __end iterators.
3467 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3468 if (ESR != ESR_Succeeded)
3469 return ESR;
3470
3471 while (true) {
3472 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003473 {
3474 bool Continue = true;
3475 FullExpressionRAII CondExpr(Info);
3476 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3477 return ESR_Failed;
3478 if (!Continue)
3479 break;
3480 }
Richard Smith896e0d72013-05-06 06:51:17 +00003481
3482 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003483 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003484 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3485 if (ESR != ESR_Succeeded)
3486 return ESR;
3487
3488 // Loop body.
3489 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3490 if (ESR != ESR_Continue)
3491 return ESR;
3492
3493 // Increment: ++__begin
3494 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3495 return ESR_Failed;
3496 }
3497
3498 return ESR_Succeeded;
3499 }
3500
Richard Smith496ddcf2013-05-12 17:32:42 +00003501 case Stmt::SwitchStmtClass:
3502 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3503
Richard Smith4e18ca52013-05-06 05:56:11 +00003504 case Stmt::ContinueStmtClass:
3505 return ESR_Continue;
3506
3507 case Stmt::BreakStmtClass:
3508 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003509
3510 case Stmt::LabelStmtClass:
3511 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3512
3513 case Stmt::AttributedStmtClass:
3514 // As a general principle, C++11 attributes can be ignored without
3515 // any semantic impact.
3516 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3517 Case);
3518
3519 case Stmt::CaseStmtClass:
3520 case Stmt::DefaultStmtClass:
3521 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003522 }
3523}
3524
Richard Smithcc36f692011-12-22 02:22:31 +00003525/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3526/// default constructor. If so, we'll fold it whether or not it's marked as
3527/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3528/// so we need special handling.
3529static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003530 const CXXConstructorDecl *CD,
3531 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003532 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3533 return false;
3534
Richard Smith66e05fe2012-01-18 05:21:49 +00003535 // Value-initialization does not call a trivial default constructor, so such a
3536 // call is a core constant expression whether or not the constructor is
3537 // constexpr.
3538 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003539 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003540 // FIXME: If DiagDecl is an implicitly-declared special member function,
3541 // we should be much more explicit about why it's not constexpr.
3542 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3543 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3544 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003545 } else {
3546 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3547 }
3548 }
3549 return true;
3550}
3551
Richard Smith357362d2011-12-13 06:39:58 +00003552/// CheckConstexprFunction - Check that a function can be called in a constant
3553/// expression.
3554static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3555 const FunctionDecl *Declaration,
3556 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003557 // Potential constant expressions can contain calls to declared, but not yet
3558 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003559 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003560 Declaration->isConstexpr())
3561 return false;
3562
Richard Smith0838f3a2013-05-14 05:18:44 +00003563 // Bail out with no diagnostic if the function declaration itself is invalid.
3564 // We will have produced a relevant diagnostic while parsing it.
3565 if (Declaration->isInvalidDecl())
3566 return false;
3567
Richard Smith357362d2011-12-13 06:39:58 +00003568 // Can we evaluate this function call?
3569 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3570 return true;
3571
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003572 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003573 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003574 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3575 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003576 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3577 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3578 << DiagDecl;
3579 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3580 } else {
3581 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3582 }
3583 return false;
3584}
3585
Richard Smithd62306a2011-11-10 06:34:14 +00003586namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003587typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003588}
3589
3590/// EvaluateArgs - Evaluate the arguments to a function call.
3591static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3592 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003593 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003594 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003595 I != E; ++I) {
3596 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3597 // If we're checking for a potential constant expression, evaluate all
3598 // initializers even if some of them fail.
3599 if (!Info.keepEvaluatingAfterFailure())
3600 return false;
3601 Success = false;
3602 }
3603 }
3604 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003605}
3606
Richard Smith254a73d2011-10-28 22:34:42 +00003607/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003608static bool HandleFunctionCall(SourceLocation CallLoc,
3609 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003610 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003611 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003612 ArgVector ArgValues(Args.size());
3613 if (!EvaluateArgs(Args, ArgValues, Info))
3614 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003615
Richard Smith253c2a32012-01-27 01:14:48 +00003616 if (!Info.CheckCallLimit(CallLoc))
3617 return false;
3618
3619 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003620
3621 // For a trivial copy or move assignment, perform an APValue copy. This is
3622 // essential for unions, where the operations performed by the assignment
3623 // operator cannot be represented as statements.
3624 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3625 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3626 assert(This &&
3627 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3628 LValue RHS;
3629 RHS.setFrom(Info.Ctx, ArgValues[0]);
3630 APValue RHSValue;
3631 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3632 RHS, RHSValue))
3633 return false;
3634 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3635 RHSValue))
3636 return false;
3637 This->moveInto(Result);
3638 return true;
3639 }
3640
Richard Smithd9f663b2013-04-22 15:31:51 +00003641 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003642 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003643 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003644 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003645 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003646 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003647 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003648}
3649
Richard Smithd62306a2011-11-10 06:34:14 +00003650/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003651static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003652 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003653 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003654 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003655 ArgVector ArgValues(Args.size());
3656 if (!EvaluateArgs(Args, ArgValues, Info))
3657 return false;
3658
Richard Smith253c2a32012-01-27 01:14:48 +00003659 if (!Info.CheckCallLimit(CallLoc))
3660 return false;
3661
Richard Smith3607ffe2012-02-13 03:54:03 +00003662 const CXXRecordDecl *RD = Definition->getParent();
3663 if (RD->getNumVBases()) {
3664 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3665 return false;
3666 }
3667
Richard Smith253c2a32012-01-27 01:14:48 +00003668 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003669
3670 // If it's a delegating constructor, just delegate.
3671 if (Definition->isDelegatingConstructor()) {
3672 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003673 {
3674 FullExpressionRAII InitScope(Info);
3675 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3676 return false;
3677 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003678 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003679 }
3680
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003681 // For a trivial copy or move constructor, perform an APValue copy. This is
3682 // essential for unions, where the operations performed by the constructor
3683 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003684 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003685 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3686 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003687 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003688 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003689 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003690 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003691 }
3692
3693 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003694 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003695 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003696 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003697
John McCalld7bca762012-05-01 00:38:49 +00003698 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003699 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3700
Richard Smith08d6a2c2013-07-24 07:11:57 +00003701 // A scope for temporaries lifetime-extended by reference members.
3702 BlockScopeRAII LifetimeExtendedScope(Info);
3703
Richard Smith253c2a32012-01-27 01:14:48 +00003704 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003705 unsigned BasesSeen = 0;
3706#ifndef NDEBUG
3707 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3708#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003709 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003710 LValue Subobject = This;
3711 APValue *Value = &Result;
3712
3713 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003714 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003715 if (I->isBaseInitializer()) {
3716 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003717#ifndef NDEBUG
3718 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003719 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003720 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3721 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3722 "base class initializers not in expected order");
3723 ++BaseIt;
3724#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003725 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003726 BaseType->getAsCXXRecordDecl(), &Layout))
3727 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003728 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003729 } else if ((FD = I->getMember())) {
3730 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003731 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003732 if (RD->isUnion()) {
3733 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003734 Value = &Result.getUnionValue();
3735 } else {
3736 Value = &Result.getStructField(FD->getFieldIndex());
3737 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003738 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003739 // Walk the indirect field decl's chain to find the object to initialize,
3740 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003741 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003742 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003743 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3744 // Switch the union field if it differs. This happens if we had
3745 // preceding zero-initialization, and we're now initializing a union
3746 // subobject other than the first.
3747 // FIXME: In this case, the values of the other subobjects are
3748 // specified, since zero-initialization sets all padding bits to zero.
3749 if (Value->isUninit() ||
3750 (Value->isUnion() && Value->getUnionField() != FD)) {
3751 if (CD->isUnion())
3752 *Value = APValue(FD);
3753 else
3754 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003755 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003756 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003757 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003758 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003759 if (CD->isUnion())
3760 Value = &Value->getUnionValue();
3761 else
3762 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003763 }
Richard Smithd62306a2011-11-10 06:34:14 +00003764 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003765 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003766 }
Richard Smith253c2a32012-01-27 01:14:48 +00003767
Richard Smith08d6a2c2013-07-24 07:11:57 +00003768 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003769 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3770 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003771 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003772 // If we're checking for a potential constant expression, evaluate all
3773 // initializers even if some of them fail.
3774 if (!Info.keepEvaluatingAfterFailure())
3775 return false;
3776 Success = false;
3777 }
Richard Smithd62306a2011-11-10 06:34:14 +00003778 }
3779
Richard Smithd9f663b2013-04-22 15:31:51 +00003780 return Success &&
3781 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003782}
3783
Eli Friedman9a156e52008-11-12 09:44:48 +00003784//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003785// Generic Evaluation
3786//===----------------------------------------------------------------------===//
3787namespace {
3788
Aaron Ballman68af21c2014-01-03 19:26:43 +00003789template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003790class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003791 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003792private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003793 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003794 return static_cast<Derived*>(this)->Success(V, E);
3795 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003796 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003797 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003798 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003799
Richard Smith17100ba2012-02-16 02:46:34 +00003800 // Check whether a conditional operator with a non-constant condition is a
3801 // potential constant expression. If neither arm is a potential constant
3802 // expression, then the conditional operator is not either.
3803 template<typename ConditionalOperator>
3804 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003805 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003806
3807 // Speculatively evaluate both arms.
3808 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003809 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003810 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3811
3812 StmtVisitorTy::Visit(E->getFalseExpr());
3813 if (Diag.empty())
3814 return;
3815
3816 Diag.clear();
3817 StmtVisitorTy::Visit(E->getTrueExpr());
3818 if (Diag.empty())
3819 return;
3820 }
3821
3822 Error(E, diag::note_constexpr_conditional_never_const);
3823 }
3824
3825
3826 template<typename ConditionalOperator>
3827 bool HandleConditionalOperator(const ConditionalOperator *E) {
3828 bool BoolResult;
3829 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003830 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003831 CheckPotentialConstantConditional(E);
3832 return false;
3833 }
3834
3835 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3836 return StmtVisitorTy::Visit(EvalExpr);
3837 }
3838
Peter Collingbournee9200682011-05-13 03:29:01 +00003839protected:
3840 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003841 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003842 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3843
Richard Smith92b1ce02011-12-12 09:28:41 +00003844 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003845 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003846 }
3847
Aaron Ballman68af21c2014-01-03 19:26:43 +00003848 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003849
3850public:
3851 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3852
3853 EvalInfo &getEvalInfo() { return Info; }
3854
Richard Smithf57d8cb2011-12-09 22:58:01 +00003855 /// Report an evaluation error. This should only be called when an error is
3856 /// first discovered. When propagating an error, just return false.
3857 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003858 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003859 return false;
3860 }
3861 bool Error(const Expr *E) {
3862 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3863 }
3864
Aaron Ballman68af21c2014-01-03 19:26:43 +00003865 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003866 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003867 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003868 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003869 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003870 }
3871
Aaron Ballman68af21c2014-01-03 19:26:43 +00003872 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003873 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003874 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003875 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003876 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003877 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003878 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003879 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003880 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003881 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003882 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003883 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003884 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003885 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003886 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003887 // The initializer may not have been parsed yet, or might be erroneous.
3888 if (!E->getExpr())
3889 return Error(E);
3890 return StmtVisitorTy::Visit(E->getExpr());
3891 }
Richard Smith5894a912011-12-19 22:12:41 +00003892 // We cannot create any objects for which cleanups are required, so there is
3893 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003894 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003895 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003896
Aaron Ballman68af21c2014-01-03 19:26:43 +00003897 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003898 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3899 return static_cast<Derived*>(this)->VisitCastExpr(E);
3900 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003901 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003902 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3903 return static_cast<Derived*>(this)->VisitCastExpr(E);
3904 }
3905
Aaron Ballman68af21c2014-01-03 19:26:43 +00003906 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003907 switch (E->getOpcode()) {
3908 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003909 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003910
3911 case BO_Comma:
3912 VisitIgnoredValue(E->getLHS());
3913 return StmtVisitorTy::Visit(E->getRHS());
3914
3915 case BO_PtrMemD:
3916 case BO_PtrMemI: {
3917 LValue Obj;
3918 if (!HandleMemberPointerAccess(Info, E, Obj))
3919 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003920 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003921 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003922 return false;
3923 return DerivedSuccess(Result, E);
3924 }
3925 }
3926 }
3927
Aaron Ballman68af21c2014-01-03 19:26:43 +00003928 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003929 // Evaluate and cache the common expression. We treat it as a temporary,
3930 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003931 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003932 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003933 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003934
Richard Smith17100ba2012-02-16 02:46:34 +00003935 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003936 }
3937
Aaron Ballman68af21c2014-01-03 19:26:43 +00003938 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003939 bool IsBcpCall = false;
3940 // If the condition (ignoring parens) is a __builtin_constant_p call,
3941 // the result is a constant expression if it can be folded without
3942 // side-effects. This is an important GNU extension. See GCC PR38377
3943 // for discussion.
3944 if (const CallExpr *CallCE =
3945 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00003946 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003947 IsBcpCall = true;
3948
3949 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3950 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003951 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003952 return false;
3953
Richard Smith6d4c6582013-11-05 22:18:15 +00003954 FoldConstant Fold(Info, IsBcpCall);
3955 if (!HandleConditionalOperator(E)) {
3956 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003957 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003958 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003959
3960 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003961 }
3962
Aaron Ballman68af21c2014-01-03 19:26:43 +00003963 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003964 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3965 return DerivedSuccess(*Value, E);
3966
3967 const Expr *Source = E->getSourceExpr();
3968 if (!Source)
3969 return Error(E);
3970 if (Source == E) { // sanity checking.
3971 assert(0 && "OpaqueValueExpr recursively refers to itself");
3972 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003973 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003974 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003975 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003976
Aaron Ballman68af21c2014-01-03 19:26:43 +00003977 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003978 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003979 QualType CalleeType = Callee->getType();
3980
Craig Topper36250ad2014-05-12 05:36:57 +00003981 const FunctionDecl *FD = nullptr;
3982 LValue *This = nullptr, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003983 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003984 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003985
Richard Smithe97cbd72011-11-11 04:05:33 +00003986 // Extract function decl and 'this' pointer from the callee.
3987 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00003988 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003989 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3990 // Explicit bound member calls, such as x.f() or p->g();
3991 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 return false;
3993 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003994 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003995 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003996 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3997 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003998 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3999 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004000 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004001 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004002 return Error(Callee);
4003
4004 FD = dyn_cast<FunctionDecl>(Member);
4005 if (!FD)
4006 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004007 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004008 LValue Call;
4009 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004010 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004011
Richard Smitha8105bc2012-01-06 16:39:00 +00004012 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004013 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004014 FD = dyn_cast_or_null<FunctionDecl>(
4015 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004016 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004017 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004018
4019 // Overloaded operator calls to member functions are represented as normal
4020 // calls with '*this' as the first argument.
4021 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4022 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004023 // FIXME: When selecting an implicit conversion for an overloaded
4024 // operator delete, we sometimes try to evaluate calls to conversion
4025 // operators without a 'this' parameter!
4026 if (Args.empty())
4027 return Error(E);
4028
Richard Smithe97cbd72011-11-11 04:05:33 +00004029 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4030 return false;
4031 This = &ThisVal;
4032 Args = Args.slice(1);
4033 }
4034
4035 // Don't call function pointers which have been cast to some other type.
4036 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004037 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004038 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004039 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004040
Richard Smith47b34932012-02-01 02:39:43 +00004041 if (This && !This->checkSubobject(Info, E, CSK_This))
4042 return false;
4043
Richard Smith3607ffe2012-02-13 03:54:03 +00004044 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4045 // calls to such functions in constant expressions.
4046 if (This && !HasQualifier &&
4047 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4048 return Error(E, diag::note_constexpr_virtual_call);
4049
Craig Topper36250ad2014-05-12 05:36:57 +00004050 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004051 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004052 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004053
Richard Smith357362d2011-12-13 06:39:58 +00004054 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004055 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4056 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004057 return false;
4058
Richard Smithb228a862012-02-15 02:18:13 +00004059 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004060 }
4061
Aaron Ballman68af21c2014-01-03 19:26:43 +00004062 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004063 return StmtVisitorTy::Visit(E->getInitializer());
4064 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004065 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004066 if (E->getNumInits() == 0)
4067 return DerivedZeroInitialization(E);
4068 if (E->getNumInits() == 1)
4069 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004070 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004071 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004072 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004073 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004074 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004075 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004076 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004077 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004078 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004079 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004080 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004081
Richard Smithd62306a2011-11-10 06:34:14 +00004082 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004083 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004084 assert(!E->isArrow() && "missing call to bound member function?");
4085
Richard Smith2e312c82012-03-03 22:46:17 +00004086 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004087 if (!Evaluate(Val, Info, E->getBase()))
4088 return false;
4089
4090 QualType BaseTy = E->getBase()->getType();
4091
4092 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004093 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004094 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004095 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004096 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4097
Richard Smith3229b742013-05-05 21:17:10 +00004098 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004099 SubobjectDesignator Designator(BaseTy);
4100 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004101
Richard Smith3229b742013-05-05 21:17:10 +00004102 APValue Result;
4103 return extractSubobject(Info, E, Obj, Designator, Result) &&
4104 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004105 }
4106
Aaron Ballman68af21c2014-01-03 19:26:43 +00004107 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004108 switch (E->getCastKind()) {
4109 default:
4110 break;
4111
Richard Smitha23ab512013-05-23 00:30:41 +00004112 case CK_AtomicToNonAtomic: {
4113 APValue AtomicVal;
4114 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4115 return false;
4116 return DerivedSuccess(AtomicVal, E);
4117 }
4118
Richard Smith11562c52011-10-28 17:51:58 +00004119 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004120 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004121 return StmtVisitorTy::Visit(E->getSubExpr());
4122
4123 case CK_LValueToRValue: {
4124 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004125 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4126 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004127 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004128 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004129 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004130 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004131 return false;
4132 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004133 }
4134 }
4135
Richard Smithf57d8cb2011-12-09 22:58:01 +00004136 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004137 }
4138
Aaron Ballman68af21c2014-01-03 19:26:43 +00004139 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004140 return VisitUnaryPostIncDec(UO);
4141 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004142 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004143 return VisitUnaryPostIncDec(UO);
4144 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004145 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004146 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4147 return Error(UO);
4148
4149 LValue LVal;
4150 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4151 return false;
4152 APValue RVal;
4153 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4154 UO->isIncrementOp(), &RVal))
4155 return false;
4156 return DerivedSuccess(RVal, UO);
4157 }
4158
Aaron Ballman68af21c2014-01-03 19:26:43 +00004159 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004160 // We will have checked the full-expressions inside the statement expression
4161 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004162 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004163 return Error(E);
4164
Richard Smith08d6a2c2013-07-24 07:11:57 +00004165 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004166 const CompoundStmt *CS = E->getSubStmt();
4167 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4168 BE = CS->body_end();
4169 /**/; ++BI) {
4170 if (BI + 1 == BE) {
4171 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4172 if (!FinalExpr) {
4173 Info.Diag((*BI)->getLocStart(),
4174 diag::note_constexpr_stmt_expr_unsupported);
4175 return false;
4176 }
4177 return this->Visit(FinalExpr);
4178 }
4179
4180 APValue ReturnValue;
4181 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4182 if (ESR != ESR_Succeeded) {
4183 // FIXME: If the statement-expression terminated due to 'return',
4184 // 'break', or 'continue', it would be nice to propagate that to
4185 // the outer statement evaluation rather than bailing out.
4186 if (ESR != ESR_Failed)
4187 Info.Diag((*BI)->getLocStart(),
4188 diag::note_constexpr_stmt_expr_unsupported);
4189 return false;
4190 }
4191 }
4192 }
4193
Richard Smith4a678122011-10-24 18:44:57 +00004194 /// Visit a value which is evaluated, but whose value is ignored.
4195 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004196 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004197 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004198};
4199
4200}
4201
4202//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004203// Common base class for lvalue and temporary evaluation.
4204//===----------------------------------------------------------------------===//
4205namespace {
4206template<class Derived>
4207class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004208 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004209protected:
4210 LValue &Result;
4211 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004212 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004213
4214 bool Success(APValue::LValueBase B) {
4215 Result.set(B);
4216 return true;
4217 }
4218
4219public:
4220 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4221 ExprEvaluatorBaseTy(Info), Result(Result) {}
4222
Richard Smith2e312c82012-03-03 22:46:17 +00004223 bool Success(const APValue &V, const Expr *E) {
4224 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004225 return true;
4226 }
Richard Smith027bf112011-11-17 22:56:20 +00004227
Richard Smith027bf112011-11-17 22:56:20 +00004228 bool VisitMemberExpr(const MemberExpr *E) {
4229 // Handle non-static data members.
4230 QualType BaseTy;
4231 if (E->isArrow()) {
4232 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4233 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004234 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004235 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004236 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004237 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4238 return false;
4239 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004240 } else {
4241 if (!this->Visit(E->getBase()))
4242 return false;
4243 BaseTy = E->getBase()->getType();
4244 }
Richard Smith027bf112011-11-17 22:56:20 +00004245
Richard Smith1b78b3d2012-01-25 22:15:11 +00004246 const ValueDecl *MD = E->getMemberDecl();
4247 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4248 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4249 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4250 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004251 if (!HandleLValueMember(this->Info, E, Result, FD))
4252 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004253 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004254 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4255 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004256 } else
4257 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004258
Richard Smith1b78b3d2012-01-25 22:15:11 +00004259 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004260 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004261 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004262 RefValue))
4263 return false;
4264 return Success(RefValue, E);
4265 }
4266 return true;
4267 }
4268
4269 bool VisitBinaryOperator(const BinaryOperator *E) {
4270 switch (E->getOpcode()) {
4271 default:
4272 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4273
4274 case BO_PtrMemD:
4275 case BO_PtrMemI:
4276 return HandleMemberPointerAccess(this->Info, E, Result);
4277 }
4278 }
4279
4280 bool VisitCastExpr(const CastExpr *E) {
4281 switch (E->getCastKind()) {
4282 default:
4283 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4284
4285 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004286 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004287 if (!this->Visit(E->getSubExpr()))
4288 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004289
4290 // Now figure out the necessary offset to add to the base LV to get from
4291 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004292 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4293 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004294 }
4295 }
4296};
4297}
4298
4299//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004300// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004301//
4302// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4303// function designators (in C), decl references to void objects (in C), and
4304// temporaries (if building with -Wno-address-of-temporary).
4305//
4306// LValue evaluation produces values comprising a base expression of one of the
4307// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004308// - Declarations
4309// * VarDecl
4310// * FunctionDecl
4311// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004312// * CompoundLiteralExpr in C
4313// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004314// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004315// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004316// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004317// * ObjCEncodeExpr
4318// * AddrLabelExpr
4319// * BlockExpr
4320// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004321// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004322// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004323// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004324// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4325// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004326// * A MaterializeTemporaryExpr that has static storage duration, with no
4327// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004328// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004329//===----------------------------------------------------------------------===//
4330namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004331class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004332 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004333public:
Richard Smith027bf112011-11-17 22:56:20 +00004334 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4335 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004336
Richard Smith11562c52011-10-28 17:51:58 +00004337 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004338 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004339
Peter Collingbournee9200682011-05-13 03:29:01 +00004340 bool VisitDeclRefExpr(const DeclRefExpr *E);
4341 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004342 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004343 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4344 bool VisitMemberExpr(const MemberExpr *E);
4345 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4346 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004347 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004348 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004349 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4350 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004351 bool VisitUnaryReal(const UnaryOperator *E);
4352 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004353 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4354 return VisitUnaryPreIncDec(UO);
4355 }
4356 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4357 return VisitUnaryPreIncDec(UO);
4358 }
Richard Smith3229b742013-05-05 21:17:10 +00004359 bool VisitBinAssign(const BinaryOperator *BO);
4360 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004361
Peter Collingbournee9200682011-05-13 03:29:01 +00004362 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004363 switch (E->getCastKind()) {
4364 default:
Richard Smith027bf112011-11-17 22:56:20 +00004365 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004366
Eli Friedmance3e02a2011-10-11 00:13:24 +00004367 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004368 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004369 if (!Visit(E->getSubExpr()))
4370 return false;
4371 Result.Designator.setInvalid();
4372 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004373
Richard Smith027bf112011-11-17 22:56:20 +00004374 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004375 if (!Visit(E->getSubExpr()))
4376 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004377 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004378 }
4379 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004380};
4381} // end anonymous namespace
4382
Richard Smith11562c52011-10-28 17:51:58 +00004383/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004384/// expressions which are not glvalues, in two cases:
4385/// * function designators in C, and
4386/// * "extern void" objects
4387static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4388 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4389 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004390 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004391}
4392
Peter Collingbournee9200682011-05-13 03:29:01 +00004393bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004394 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004395 return Success(FD);
4396 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004397 return VisitVarDecl(E, VD);
4398 return Error(E);
4399}
Richard Smith733237d2011-10-24 23:14:33 +00004400
Richard Smith11562c52011-10-28 17:51:58 +00004401bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004402 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004403 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4404 Frame = Info.CurrentCall;
4405
Richard Smithfec09922011-11-01 16:57:24 +00004406 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004407 if (Frame) {
4408 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004409 return true;
4410 }
Richard Smithce40ad62011-11-12 22:28:03 +00004411 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004412 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004413
Richard Smith3229b742013-05-05 21:17:10 +00004414 APValue *V;
4415 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004417 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004418 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004419 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4420 return false;
4421 }
Richard Smith3229b742013-05-05 21:17:10 +00004422 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004423}
4424
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004425bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4426 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004427 // Walk through the expression to find the materialized temporary itself.
4428 SmallVector<const Expr *, 2> CommaLHSs;
4429 SmallVector<SubobjectAdjustment, 2> Adjustments;
4430 const Expr *Inner = E->GetTemporaryExpr()->
4431 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004432
Richard Smith84401042013-06-03 05:03:02 +00004433 // If we passed any comma operators, evaluate their LHSs.
4434 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4435 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4436 return false;
4437
Richard Smithe6c01442013-06-05 00:46:14 +00004438 // A materialized temporary with static storage duration can appear within the
4439 // result of a constant expression evaluation, so we need to preserve its
4440 // value for use outside this evaluation.
4441 APValue *Value;
4442 if (E->getStorageDuration() == SD_Static) {
4443 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004444 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004445 Result.set(E);
4446 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004447 Value = &Info.CurrentCall->
4448 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004449 Result.set(E, Info.CurrentCall->Index);
4450 }
4451
Richard Smithea4ad5d2013-06-06 08:19:16 +00004452 QualType Type = Inner->getType();
4453
Richard Smith84401042013-06-03 05:03:02 +00004454 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004455 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4456 (E->getStorageDuration() == SD_Static &&
4457 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4458 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004459 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004460 }
Richard Smith84401042013-06-03 05:03:02 +00004461
4462 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004463 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4464 --I;
4465 switch (Adjustments[I].Kind) {
4466 case SubobjectAdjustment::DerivedToBaseAdjustment:
4467 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4468 Type, Result))
4469 return false;
4470 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4471 break;
4472
4473 case SubobjectAdjustment::FieldAdjustment:
4474 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4475 return false;
4476 Type = Adjustments[I].Field->getType();
4477 break;
4478
4479 case SubobjectAdjustment::MemberPointerAdjustment:
4480 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4481 Adjustments[I].Ptr.RHS))
4482 return false;
4483 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4484 break;
4485 }
4486 }
4487
4488 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004489}
4490
Peter Collingbournee9200682011-05-13 03:29:01 +00004491bool
4492LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004493 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4494 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4495 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004496 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004497}
4498
Richard Smith6e525142011-12-27 12:18:28 +00004499bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004500 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004501 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004502
4503 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4504 << E->getExprOperand()->getType()
4505 << E->getExprOperand()->getSourceRange();
4506 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004507}
4508
Francois Pichet0066db92012-04-16 04:08:35 +00004509bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4510 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004511}
Francois Pichet0066db92012-04-16 04:08:35 +00004512
Peter Collingbournee9200682011-05-13 03:29:01 +00004513bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004514 // Handle static data members.
4515 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4516 VisitIgnoredValue(E->getBase());
4517 return VisitVarDecl(E, VD);
4518 }
4519
Richard Smith254a73d2011-10-28 22:34:42 +00004520 // Handle static member functions.
4521 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4522 if (MD->isStatic()) {
4523 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004524 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004525 }
4526 }
4527
Richard Smithd62306a2011-11-10 06:34:14 +00004528 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004529 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004530}
4531
Peter Collingbournee9200682011-05-13 03:29:01 +00004532bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004533 // FIXME: Deal with vectors as array subscript bases.
4534 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004535 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004536
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004537 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004538 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004540 APSInt Index;
4541 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004542 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004543
Richard Smith861b5b52013-05-07 23:34:45 +00004544 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4545 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004546}
Eli Friedman9a156e52008-11-12 09:44:48 +00004547
Peter Collingbournee9200682011-05-13 03:29:01 +00004548bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004549 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004550}
4551
Richard Smith66c96992012-02-18 22:04:06 +00004552bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4553 if (!Visit(E->getSubExpr()))
4554 return false;
4555 // __real is a no-op on scalar lvalues.
4556 if (E->getSubExpr()->getType()->isAnyComplexType())
4557 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4558 return true;
4559}
4560
4561bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4562 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4563 "lvalue __imag__ on scalar?");
4564 if (!Visit(E->getSubExpr()))
4565 return false;
4566 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4567 return true;
4568}
4569
Richard Smith243ef902013-05-05 23:31:59 +00004570bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4571 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004572 return Error(UO);
4573
4574 if (!this->Visit(UO->getSubExpr()))
4575 return false;
4576
Richard Smith243ef902013-05-05 23:31:59 +00004577 return handleIncDec(
4578 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004579 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004580}
4581
4582bool LValueExprEvaluator::VisitCompoundAssignOperator(
4583 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004584 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004585 return Error(CAO);
4586
Richard Smith3229b742013-05-05 21:17:10 +00004587 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004588
4589 // The overall lvalue result is the result of evaluating the LHS.
4590 if (!this->Visit(CAO->getLHS())) {
4591 if (Info.keepEvaluatingAfterFailure())
4592 Evaluate(RHS, this->Info, CAO->getRHS());
4593 return false;
4594 }
4595
Richard Smith3229b742013-05-05 21:17:10 +00004596 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4597 return false;
4598
Richard Smith43e77732013-05-07 04:50:00 +00004599 return handleCompoundAssignment(
4600 this->Info, CAO,
4601 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4602 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004603}
4604
4605bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004606 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4607 return Error(E);
4608
Richard Smith3229b742013-05-05 21:17:10 +00004609 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004610
4611 if (!this->Visit(E->getLHS())) {
4612 if (Info.keepEvaluatingAfterFailure())
4613 Evaluate(NewVal, this->Info, E->getRHS());
4614 return false;
4615 }
4616
Richard Smith3229b742013-05-05 21:17:10 +00004617 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4618 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004619
4620 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004621 NewVal);
4622}
4623
Eli Friedman9a156e52008-11-12 09:44:48 +00004624//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004625// Pointer Evaluation
4626//===----------------------------------------------------------------------===//
4627
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004628namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004629class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004630 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004631 LValue &Result;
4632
Peter Collingbournee9200682011-05-13 03:29:01 +00004633 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004634 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004635 return true;
4636 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004637public:
Mike Stump11289f42009-09-09 15:08:12 +00004638
John McCall45d55e42010-05-07 21:00:08 +00004639 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004640 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004641
Richard Smith2e312c82012-03-03 22:46:17 +00004642 bool Success(const APValue &V, const Expr *E) {
4643 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004644 return true;
4645 }
Richard Smithfddd3842011-12-30 21:15:51 +00004646 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004647 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004648 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004649
John McCall45d55e42010-05-07 21:00:08 +00004650 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004651 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004652 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004653 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004654 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004655 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004656 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004657 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004658 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004659 bool VisitCallExpr(const CallExpr *E);
4660 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004661 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004662 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004663 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004664 }
Richard Smithd62306a2011-11-10 06:34:14 +00004665 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004666 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004667 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004668 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004669 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004670 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004671 Result = *Info.CurrentCall->This;
4672 return true;
4673 }
John McCallc07a0c72011-02-17 10:25:35 +00004674
Eli Friedman449fe542009-03-23 04:56:01 +00004675 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004676};
Chris Lattner05706e882008-07-11 18:11:29 +00004677} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004678
John McCall45d55e42010-05-07 21:00:08 +00004679static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004680 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004681 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004682}
4683
John McCall45d55e42010-05-07 21:00:08 +00004684bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004685 if (E->getOpcode() != BO_Add &&
4686 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004687 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004688
Chris Lattner05706e882008-07-11 18:11:29 +00004689 const Expr *PExp = E->getLHS();
4690 const Expr *IExp = E->getRHS();
4691 if (IExp->getType()->isPointerType())
4692 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004693
Richard Smith253c2a32012-01-27 01:14:48 +00004694 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4695 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004696 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004697
John McCall45d55e42010-05-07 21:00:08 +00004698 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004699 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004700 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004701
4702 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004703 if (E->getOpcode() == BO_Sub)
4704 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004705
Ted Kremenek28831752012-08-23 20:46:57 +00004706 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004707 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4708 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004709}
Eli Friedman9a156e52008-11-12 09:44:48 +00004710
John McCall45d55e42010-05-07 21:00:08 +00004711bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4712 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004713}
Mike Stump11289f42009-09-09 15:08:12 +00004714
Peter Collingbournee9200682011-05-13 03:29:01 +00004715bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4716 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004717
Eli Friedman847a2bc2009-12-27 05:43:15 +00004718 switch (E->getCastKind()) {
4719 default:
4720 break;
4721
John McCalle3027922010-08-25 11:45:40 +00004722 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004723 case CK_CPointerToObjCPointerCast:
4724 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004725 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004726 if (!Visit(SubExpr))
4727 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004728 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4729 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4730 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004731 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004732 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004733 if (SubExpr->getType()->isVoidPointerType())
4734 CCEDiag(E, diag::note_constexpr_invalid_cast)
4735 << 3 << SubExpr->getType();
4736 else
4737 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4738 }
Richard Smith96e0c102011-11-04 02:25:55 +00004739 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004740
Anders Carlsson18275092010-10-31 20:41:46 +00004741 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004742 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004743 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004744 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004745 if (!Result.Base && Result.Offset.isZero())
4746 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004747
Richard Smithd62306a2011-11-10 06:34:14 +00004748 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004749 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004750 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4751 castAs<PointerType>()->getPointeeType(),
4752 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004753
Richard Smith027bf112011-11-17 22:56:20 +00004754 case CK_BaseToDerived:
4755 if (!Visit(E->getSubExpr()))
4756 return false;
4757 if (!Result.Base && Result.Offset.isZero())
4758 return true;
4759 return HandleBaseToDerivedCast(Info, E, Result);
4760
Richard Smith0b0a0b62011-10-29 20:57:55 +00004761 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004762 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004763 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004764
John McCalle3027922010-08-25 11:45:40 +00004765 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004766 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4767
Richard Smith2e312c82012-03-03 22:46:17 +00004768 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004769 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004770 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004771
John McCall45d55e42010-05-07 21:00:08 +00004772 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004773 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4774 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004775 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004776 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004777 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004778 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004779 return true;
4780 } else {
4781 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004782 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004783 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004784 }
4785 }
John McCalle3027922010-08-25 11:45:40 +00004786 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004787 if (SubExpr->isGLValue()) {
4788 if (!EvaluateLValue(SubExpr, Result, Info))
4789 return false;
4790 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004791 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004792 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004793 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004794 return false;
4795 }
Richard Smith96e0c102011-11-04 02:25:55 +00004796 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004797 if (const ConstantArrayType *CAT
4798 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4799 Result.addArray(Info, E, CAT);
4800 else
4801 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004802 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004803
John McCalle3027922010-08-25 11:45:40 +00004804 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004805 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004806 }
4807
Richard Smith11562c52011-10-28 17:51:58 +00004808 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004809}
Chris Lattner05706e882008-07-11 18:11:29 +00004810
Peter Collingbournee9200682011-05-13 03:29:01 +00004811bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004812 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004813 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004814
Alp Tokera724cff2013-12-28 21:59:02 +00004815 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004816 case Builtin::BI__builtin_addressof:
4817 return EvaluateLValue(E->getArg(0), Result, Info);
4818
4819 default:
4820 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4821 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004822}
Chris Lattner05706e882008-07-11 18:11:29 +00004823
4824//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004825// Member Pointer Evaluation
4826//===----------------------------------------------------------------------===//
4827
4828namespace {
4829class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004830 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004831 MemberPtr &Result;
4832
4833 bool Success(const ValueDecl *D) {
4834 Result = MemberPtr(D);
4835 return true;
4836 }
4837public:
4838
4839 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4840 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4841
Richard Smith2e312c82012-03-03 22:46:17 +00004842 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004843 Result.setFrom(V);
4844 return true;
4845 }
Richard Smithfddd3842011-12-30 21:15:51 +00004846 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004847 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00004848 }
4849
4850 bool VisitCastExpr(const CastExpr *E);
4851 bool VisitUnaryAddrOf(const UnaryOperator *E);
4852};
4853} // end anonymous namespace
4854
4855static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4856 EvalInfo &Info) {
4857 assert(E->isRValue() && E->getType()->isMemberPointerType());
4858 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4859}
4860
4861bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4862 switch (E->getCastKind()) {
4863 default:
4864 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4865
4866 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004867 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004868 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004869
4870 case CK_BaseToDerivedMemberPointer: {
4871 if (!Visit(E->getSubExpr()))
4872 return false;
4873 if (E->path_empty())
4874 return true;
4875 // Base-to-derived member pointer casts store the path in derived-to-base
4876 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4877 // the wrong end of the derived->base arc, so stagger the path by one class.
4878 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4879 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4880 PathI != PathE; ++PathI) {
4881 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4882 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4883 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004884 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004885 }
4886 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4887 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004888 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004889 return true;
4890 }
4891
4892 case CK_DerivedToBaseMemberPointer:
4893 if (!Visit(E->getSubExpr()))
4894 return false;
4895 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4896 PathE = E->path_end(); PathI != PathE; ++PathI) {
4897 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4898 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4899 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004900 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004901 }
4902 return true;
4903 }
4904}
4905
4906bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4907 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4908 // member can be formed.
4909 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4910}
4911
4912//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004913// Record Evaluation
4914//===----------------------------------------------------------------------===//
4915
4916namespace {
4917 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004919 const LValue &This;
4920 APValue &Result;
4921 public:
4922
4923 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4924 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4925
Richard Smith2e312c82012-03-03 22:46:17 +00004926 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004927 Result = V;
4928 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004929 }
Richard Smithfddd3842011-12-30 21:15:51 +00004930 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004931
Richard Smithe97cbd72011-11-11 04:05:33 +00004932 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004933 bool VisitInitListExpr(const InitListExpr *E);
4934 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004935 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004936 };
4937}
4938
Richard Smithfddd3842011-12-30 21:15:51 +00004939/// Perform zero-initialization on an object of non-union class type.
4940/// C++11 [dcl.init]p5:
4941/// To zero-initialize an object or reference of type T means:
4942/// [...]
4943/// -- if T is a (possibly cv-qualified) non-union class type,
4944/// each non-static data member and each base-class subobject is
4945/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004946static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4947 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004948 const LValue &This, APValue &Result) {
4949 assert(!RD->isUnion() && "Expected non-union class type");
4950 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4951 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00004952 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00004953
John McCalld7bca762012-05-01 00:38:49 +00004954 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004955 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4956
4957 if (CD) {
4958 unsigned Index = 0;
4959 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004960 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004961 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4962 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004963 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4964 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004965 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004966 Result.getStructBase(Index)))
4967 return false;
4968 }
4969 }
4970
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004971 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00004972 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004973 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004974 continue;
4975
4976 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004977 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004978 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004979
David Blaikie2d7c57e2012-04-30 02:36:29 +00004980 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004981 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004982 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004983 return false;
4984 }
4985
4986 return true;
4987}
4988
4989bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4990 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004991 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004992 if (RD->isUnion()) {
4993 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4994 // object's first non-static named data member is zero-initialized
4995 RecordDecl::field_iterator I = RD->field_begin();
4996 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00004997 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00004998 return true;
4999 }
5000
5001 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005002 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005003 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005004 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005005 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005006 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005007 }
5008
Richard Smith5d108602012-02-17 00:44:16 +00005009 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005010 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005011 return false;
5012 }
5013
Richard Smitha8105bc2012-01-06 16:39:00 +00005014 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005015}
5016
Richard Smithe97cbd72011-11-11 04:05:33 +00005017bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5018 switch (E->getCastKind()) {
5019 default:
5020 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5021
5022 case CK_ConstructorConversion:
5023 return Visit(E->getSubExpr());
5024
5025 case CK_DerivedToBase:
5026 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005027 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005028 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005029 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005030 if (!DerivedObject.isStruct())
5031 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005032
5033 // Derived-to-base rvalue conversion: just slice off the derived part.
5034 APValue *Value = &DerivedObject;
5035 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5036 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5037 PathE = E->path_end(); PathI != PathE; ++PathI) {
5038 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5039 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5040 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5041 RD = Base;
5042 }
5043 Result = *Value;
5044 return true;
5045 }
5046 }
5047}
5048
Richard Smithd62306a2011-11-10 06:34:14 +00005049bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5050 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005051 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005052 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5053
5054 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005055 const FieldDecl *Field = E->getInitializedFieldInUnion();
5056 Result = APValue(Field);
5057 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005058 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005059
5060 // If the initializer list for a union does not contain any elements, the
5061 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005062 // FIXME: The element should be initialized from an initializer list.
5063 // Is this difference ever observable for initializer lists which
5064 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005065 ImplicitValueInitExpr VIE(Field->getType());
5066 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5067
Richard Smithd62306a2011-11-10 06:34:14 +00005068 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005069 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5070 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005071
5072 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5073 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5074 isa<CXXDefaultInitExpr>(InitExpr));
5075
Richard Smithb228a862012-02-15 02:18:13 +00005076 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005077 }
5078
5079 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5080 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005081 Result = APValue(APValue::UninitStruct(), 0,
5082 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005083 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005084 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005085 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005086 // Anonymous bit-fields are not considered members of the class for
5087 // purposes of aggregate initialization.
5088 if (Field->isUnnamedBitfield())
5089 continue;
5090
5091 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005092
Richard Smith253c2a32012-01-27 01:14:48 +00005093 bool HaveInit = ElementNo < E->getNumInits();
5094
5095 // FIXME: Diagnostics here should point to the end of the initializer
5096 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005097 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005098 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005099 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005100
5101 // Perform an implicit value-initialization for members beyond the end of
5102 // the initializer list.
5103 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005104 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005105
Richard Smith852c9db2013-04-20 22:23:05 +00005106 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5107 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5108 isa<CXXDefaultInitExpr>(Init));
5109
Richard Smith49ca8aa2013-08-06 07:09:20 +00005110 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5111 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5112 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005113 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005114 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005115 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005116 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005117 }
5118 }
5119
Richard Smith253c2a32012-01-27 01:14:48 +00005120 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005121}
5122
5123bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5124 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005125 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5126
Richard Smithfddd3842011-12-30 21:15:51 +00005127 bool ZeroInit = E->requiresZeroInitialization();
5128 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005129 // If we've already performed zero-initialization, we're already done.
5130 if (!Result.isUninit())
5131 return true;
5132
Richard Smithda3f4fd2014-03-05 23:32:50 +00005133 // We can get here in two different ways:
5134 // 1) We're performing value-initialization, and should zero-initialize
5135 // the object, or
5136 // 2) We're performing default-initialization of an object with a trivial
5137 // constexpr default constructor, in which case we should start the
5138 // lifetimes of all the base subobjects (there can be no data member
5139 // subobjects in this case) per [basic.life]p1.
5140 // Either way, ZeroInitialization is appropriate.
5141 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005142 }
5143
Craig Topper36250ad2014-05-12 05:36:57 +00005144 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005145 FD->getBody(Definition);
5146
Richard Smith357362d2011-12-13 06:39:58 +00005147 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5148 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005149
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005150 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005151 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005152 if (const MaterializeTemporaryExpr *ME
5153 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5154 return Visit(ME->GetTemporaryExpr());
5155
Richard Smithfddd3842011-12-30 21:15:51 +00005156 if (ZeroInit && !ZeroInitialization(E))
5157 return false;
5158
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005159 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005160 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005161 cast<CXXConstructorDecl>(Definition), Info,
5162 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005163}
5164
Richard Smithcc1b96d2013-06-12 22:31:48 +00005165bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5166 const CXXStdInitializerListExpr *E) {
5167 const ConstantArrayType *ArrayType =
5168 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5169
5170 LValue Array;
5171 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5172 return false;
5173
5174 // Get a pointer to the first element of the array.
5175 Array.addArray(Info, E, ArrayType);
5176
5177 // FIXME: Perform the checks on the field types in SemaInit.
5178 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5179 RecordDecl::field_iterator Field = Record->field_begin();
5180 if (Field == Record->field_end())
5181 return Error(E);
5182
5183 // Start pointer.
5184 if (!Field->getType()->isPointerType() ||
5185 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5186 ArrayType->getElementType()))
5187 return Error(E);
5188
5189 // FIXME: What if the initializer_list type has base classes, etc?
5190 Result = APValue(APValue::UninitStruct(), 0, 2);
5191 Array.moveInto(Result.getStructField(0));
5192
5193 if (++Field == Record->field_end())
5194 return Error(E);
5195
5196 if (Field->getType()->isPointerType() &&
5197 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5198 ArrayType->getElementType())) {
5199 // End pointer.
5200 if (!HandleLValueArrayAdjustment(Info, E, Array,
5201 ArrayType->getElementType(),
5202 ArrayType->getSize().getZExtValue()))
5203 return false;
5204 Array.moveInto(Result.getStructField(1));
5205 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5206 // Length.
5207 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5208 else
5209 return Error(E);
5210
5211 if (++Field != Record->field_end())
5212 return Error(E);
5213
5214 return true;
5215}
5216
Richard Smithd62306a2011-11-10 06:34:14 +00005217static bool EvaluateRecord(const Expr *E, const LValue &This,
5218 APValue &Result, EvalInfo &Info) {
5219 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005220 "can't evaluate expression as a record rvalue");
5221 return RecordExprEvaluator(Info, This, Result).Visit(E);
5222}
5223
5224//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005225// Temporary Evaluation
5226//
5227// Temporaries are represented in the AST as rvalues, but generally behave like
5228// lvalues. The full-object of which the temporary is a subobject is implicitly
5229// materialized so that a reference can bind to it.
5230//===----------------------------------------------------------------------===//
5231namespace {
5232class TemporaryExprEvaluator
5233 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5234public:
5235 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5236 LValueExprEvaluatorBaseTy(Info, Result) {}
5237
5238 /// Visit an expression which constructs the value of this temporary.
5239 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005240 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005241 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5242 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005243 }
5244
5245 bool VisitCastExpr(const CastExpr *E) {
5246 switch (E->getCastKind()) {
5247 default:
5248 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5249
5250 case CK_ConstructorConversion:
5251 return VisitConstructExpr(E->getSubExpr());
5252 }
5253 }
5254 bool VisitInitListExpr(const InitListExpr *E) {
5255 return VisitConstructExpr(E);
5256 }
5257 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5258 return VisitConstructExpr(E);
5259 }
5260 bool VisitCallExpr(const CallExpr *E) {
5261 return VisitConstructExpr(E);
5262 }
5263};
5264} // end anonymous namespace
5265
5266/// Evaluate an expression of record type as a temporary.
5267static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005268 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005269 return TemporaryExprEvaluator(Info, Result).Visit(E);
5270}
5271
5272//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005273// Vector Evaluation
5274//===----------------------------------------------------------------------===//
5275
5276namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005277 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005278 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005279 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005280 public:
Mike Stump11289f42009-09-09 15:08:12 +00005281
Richard Smith2d406342011-10-22 21:10:00 +00005282 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5283 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005284
Richard Smith2d406342011-10-22 21:10:00 +00005285 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5286 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5287 // FIXME: remove this APValue copy.
5288 Result = APValue(V.data(), V.size());
5289 return true;
5290 }
Richard Smith2e312c82012-03-03 22:46:17 +00005291 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005292 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005293 Result = V;
5294 return true;
5295 }
Richard Smithfddd3842011-12-30 21:15:51 +00005296 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005297
Richard Smith2d406342011-10-22 21:10:00 +00005298 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005299 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005300 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005301 bool VisitInitListExpr(const InitListExpr *E);
5302 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005303 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005304 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005305 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005306 };
5307} // end anonymous namespace
5308
5309static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005310 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005311 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005312}
5313
Richard Smith2d406342011-10-22 21:10:00 +00005314bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5315 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005316 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005317
Richard Smith161f09a2011-12-06 22:44:34 +00005318 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005319 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005320
Eli Friedmanc757de22011-03-25 00:43:55 +00005321 switch (E->getCastKind()) {
5322 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005323 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005324 if (SETy->isIntegerType()) {
5325 APSInt IntResult;
5326 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005327 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005328 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005329 } else if (SETy->isRealFloatingType()) {
5330 APFloat F(0.0);
5331 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005333 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005334 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005335 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005336 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005337
5338 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005339 SmallVector<APValue, 4> Elts(NElts, Val);
5340 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005341 }
Eli Friedman803acb32011-12-22 03:51:45 +00005342 case CK_BitCast: {
5343 // Evaluate the operand into an APInt we can extract from.
5344 llvm::APInt SValInt;
5345 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5346 return false;
5347 // Extract the elements
5348 QualType EltTy = VTy->getElementType();
5349 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5350 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5351 SmallVector<APValue, 4> Elts;
5352 if (EltTy->isRealFloatingType()) {
5353 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005354 unsigned FloatEltSize = EltSize;
5355 if (&Sem == &APFloat::x87DoubleExtended)
5356 FloatEltSize = 80;
5357 for (unsigned i = 0; i < NElts; i++) {
5358 llvm::APInt Elt;
5359 if (BigEndian)
5360 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5361 else
5362 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005363 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005364 }
5365 } else if (EltTy->isIntegerType()) {
5366 for (unsigned i = 0; i < NElts; i++) {
5367 llvm::APInt Elt;
5368 if (BigEndian)
5369 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5370 else
5371 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5372 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5373 }
5374 } else {
5375 return Error(E);
5376 }
5377 return Success(Elts, E);
5378 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005379 default:
Richard Smith11562c52011-10-28 17:51:58 +00005380 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005381 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005382}
5383
Richard Smith2d406342011-10-22 21:10:00 +00005384bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005385VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005386 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005387 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005388 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005389
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005390 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005391 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005392
Eli Friedmanb9c71292012-01-03 23:24:20 +00005393 // The number of initializers can be less than the number of
5394 // vector elements. For OpenCL, this can be due to nested vector
5395 // initialization. For GCC compatibility, missing trailing elements
5396 // should be initialized with zeroes.
5397 unsigned CountInits = 0, CountElts = 0;
5398 while (CountElts < NumElements) {
5399 // Handle nested vector initialization.
5400 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005401 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005402 APValue v;
5403 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5404 return Error(E);
5405 unsigned vlen = v.getVectorLength();
5406 for (unsigned j = 0; j < vlen; j++)
5407 Elements.push_back(v.getVectorElt(j));
5408 CountElts += vlen;
5409 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005410 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005411 if (CountInits < NumInits) {
5412 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005413 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005414 } else // trailing integer zero.
5415 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5416 Elements.push_back(APValue(sInt));
5417 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005418 } else {
5419 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005420 if (CountInits < NumInits) {
5421 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005422 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005423 } else // trailing float zero.
5424 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5425 Elements.push_back(APValue(f));
5426 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005427 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005428 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005429 }
Richard Smith2d406342011-10-22 21:10:00 +00005430 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005431}
5432
Richard Smith2d406342011-10-22 21:10:00 +00005433bool
Richard Smithfddd3842011-12-30 21:15:51 +00005434VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005435 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005436 QualType EltTy = VT->getElementType();
5437 APValue ZeroElement;
5438 if (EltTy->isIntegerType())
5439 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5440 else
5441 ZeroElement =
5442 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5443
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005444 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005445 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005446}
5447
Richard Smith2d406342011-10-22 21:10:00 +00005448bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005449 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005450 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005451}
5452
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005453//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005454// Array Evaluation
5455//===----------------------------------------------------------------------===//
5456
5457namespace {
5458 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005459 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005460 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005461 APValue &Result;
5462 public:
5463
Richard Smithd62306a2011-11-10 06:34:14 +00005464 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5465 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005466
5467 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005468 assert((V.isArray() || V.isLValue()) &&
5469 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005470 Result = V;
5471 return true;
5472 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005473
Richard Smithfddd3842011-12-30 21:15:51 +00005474 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005475 const ConstantArrayType *CAT =
5476 Info.Ctx.getAsConstantArrayType(E->getType());
5477 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005478 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005479
5480 Result = APValue(APValue::UninitArray(), 0,
5481 CAT->getSize().getZExtValue());
5482 if (!Result.hasArrayFiller()) return true;
5483
Richard Smithfddd3842011-12-30 21:15:51 +00005484 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005485 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005486 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005487 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005488 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005489 }
5490
Richard Smithf3e9e432011-11-07 09:22:26 +00005491 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005492 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005493 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5494 const LValue &Subobject,
5495 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005496 };
5497} // end anonymous namespace
5498
Richard Smithd62306a2011-11-10 06:34:14 +00005499static bool EvaluateArray(const Expr *E, const LValue &This,
5500 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005501 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005502 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005503}
5504
5505bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5506 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5507 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005508 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005509
Richard Smithca2cfbf2011-12-22 01:07:19 +00005510 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5511 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005512 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005513 LValue LV;
5514 if (!EvaluateLValue(E->getInit(0), LV, Info))
5515 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005516 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005517 LV.moveInto(Val);
5518 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005519 }
5520
Richard Smith253c2a32012-01-27 01:14:48 +00005521 bool Success = true;
5522
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005523 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5524 "zero-initialized array shouldn't have any initialized elts");
5525 APValue Filler;
5526 if (Result.isArray() && Result.hasArrayFiller())
5527 Filler = Result.getArrayFiller();
5528
Richard Smith9543c5e2013-04-22 14:44:29 +00005529 unsigned NumEltsToInit = E->getNumInits();
5530 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005531 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005532
5533 // If the initializer might depend on the array index, run it for each
5534 // array element. For now, just whitelist non-class value-initialization.
5535 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5536 NumEltsToInit = NumElts;
5537
5538 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005539
5540 // If the array was previously zero-initialized, preserve the
5541 // zero-initialized values.
5542 if (!Filler.isUninit()) {
5543 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5544 Result.getArrayInitializedElt(I) = Filler;
5545 if (Result.hasArrayFiller())
5546 Result.getArrayFiller() = Filler;
5547 }
5548
Richard Smithd62306a2011-11-10 06:34:14 +00005549 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005550 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005551 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5552 const Expr *Init =
5553 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005554 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005555 Info, Subobject, Init) ||
5556 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005557 CAT->getElementType(), 1)) {
5558 if (!Info.keepEvaluatingAfterFailure())
5559 return false;
5560 Success = false;
5561 }
Richard Smithd62306a2011-11-10 06:34:14 +00005562 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005563
Richard Smith9543c5e2013-04-22 14:44:29 +00005564 if (!Result.hasArrayFiller())
5565 return Success;
5566
5567 // If we get here, we have a trivial filler, which we can just evaluate
5568 // once and splat over the rest of the array elements.
5569 assert(FillerExpr && "no array filler for incomplete init list");
5570 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5571 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005572}
5573
Richard Smith027bf112011-11-17 22:56:20 +00005574bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005575 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5576}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005577
Richard Smith9543c5e2013-04-22 14:44:29 +00005578bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5579 const LValue &Subobject,
5580 APValue *Value,
5581 QualType Type) {
5582 bool HadZeroInit = !Value->isUninit();
5583
5584 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5585 unsigned N = CAT->getSize().getZExtValue();
5586
5587 // Preserve the array filler if we had prior zero-initialization.
5588 APValue Filler =
5589 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5590 : APValue();
5591
5592 *Value = APValue(APValue::UninitArray(), N, N);
5593
5594 if (HadZeroInit)
5595 for (unsigned I = 0; I != N; ++I)
5596 Value->getArrayInitializedElt(I) = Filler;
5597
5598 // Initialize the elements.
5599 LValue ArrayElt = Subobject;
5600 ArrayElt.addArray(Info, E, CAT);
5601 for (unsigned I = 0; I != N; ++I)
5602 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5603 CAT->getElementType()) ||
5604 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5605 CAT->getElementType(), 1))
5606 return false;
5607
5608 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005609 }
Richard Smith027bf112011-11-17 22:56:20 +00005610
Richard Smith9543c5e2013-04-22 14:44:29 +00005611 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005612 return Error(E);
5613
Richard Smith027bf112011-11-17 22:56:20 +00005614 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005615
Richard Smithfddd3842011-12-30 21:15:51 +00005616 bool ZeroInit = E->requiresZeroInitialization();
5617 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005618 if (HadZeroInit)
5619 return true;
5620
Richard Smithda3f4fd2014-03-05 23:32:50 +00005621 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5622 ImplicitValueInitExpr VIE(Type);
5623 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005624 }
5625
Craig Topper36250ad2014-05-12 05:36:57 +00005626 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005627 FD->getBody(Definition);
5628
Richard Smith357362d2011-12-13 06:39:58 +00005629 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5630 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005631
Richard Smith9eae7232012-01-12 18:54:33 +00005632 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005633 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005634 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005635 return false;
5636 }
5637
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005638 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005639 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005640 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005641 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005642}
5643
Richard Smithf3e9e432011-11-07 09:22:26 +00005644//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005645// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005646//
5647// As a GNU extension, we support casting pointers to sufficiently-wide integer
5648// types and back in constant folding. Integer values are thus represented
5649// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005650//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005651
5652namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005653class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005654 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005655 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005656public:
Richard Smith2e312c82012-03-03 22:46:17 +00005657 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005658 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005659
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005660 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005661 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005662 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005663 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005664 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005665 assert(SI.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(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005668 return true;
5669 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005670 bool Success(const llvm::APSInt &SI, const Expr *E) {
5671 return Success(SI, E, Result);
5672 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005673
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005674 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005675 assert(E->getType()->isIntegralOrEnumerationType() &&
5676 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005677 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005678 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005679 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005680 Result.getInt().setIsUnsigned(
5681 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005682 return true;
5683 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005684 bool Success(const llvm::APInt &I, const Expr *E) {
5685 return Success(I, E, Result);
5686 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005687
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005688 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005689 assert(E->getType()->isIntegralOrEnumerationType() &&
5690 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005691 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005692 return true;
5693 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005694 bool Success(uint64_t Value, const Expr *E) {
5695 return Success(Value, E, Result);
5696 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005697
Ken Dyckdbc01912011-03-11 02:13:43 +00005698 bool Success(CharUnits Size, const Expr *E) {
5699 return Success(Size.getQuantity(), E);
5700 }
5701
Richard Smith2e312c82012-03-03 22:46:17 +00005702 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005703 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005704 Result = V;
5705 return true;
5706 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005707 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005708 }
Mike Stump11289f42009-09-09 15:08:12 +00005709
Richard Smithfddd3842011-12-30 21:15:51 +00005710 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005711
Peter Collingbournee9200682011-05-13 03:29:01 +00005712 //===--------------------------------------------------------------------===//
5713 // Visitor Methods
5714 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005715
Chris Lattner7174bf32008-07-12 00:38:25 +00005716 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005717 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005718 }
5719 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005720 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005721 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005722
5723 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5724 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005725 if (CheckReferencedDecl(E, E->getDecl()))
5726 return true;
5727
5728 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005729 }
5730 bool VisitMemberExpr(const MemberExpr *E) {
5731 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005732 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005733 return true;
5734 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005735
5736 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005737 }
5738
Peter Collingbournee9200682011-05-13 03:29:01 +00005739 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005740 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005741 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005742 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005743
Peter Collingbournee9200682011-05-13 03:29:01 +00005744 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005745 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005746
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005747 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005748 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005749 }
Mike Stump11289f42009-09-09 15:08:12 +00005750
Ted Kremeneke65b0862012-03-06 20:05:56 +00005751 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5752 return Success(E->getValue(), E);
5753 }
5754
Richard Smith4ce706a2011-10-11 21:43:33 +00005755 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005756 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005757 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005758 }
5759
Douglas Gregor29c42f22012-02-24 07:38:34 +00005760 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5761 return Success(E->getValue(), E);
5762 }
5763
John Wiegley6242b6a2011-04-28 00:16:57 +00005764 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5765 return Success(E->getValue(), E);
5766 }
5767
John Wiegleyf9f65842011-04-25 06:54:41 +00005768 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5769 return Success(E->getValue(), E);
5770 }
5771
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005772 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005773 bool VisitUnaryImag(const UnaryOperator *E);
5774
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005775 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005776 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005777
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005778private:
Ken Dyck160146e2010-01-27 17:10:57 +00005779 CharUnits GetAlignOfExpr(const Expr *E);
5780 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005781 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005782 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005783 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005784};
Chris Lattner05706e882008-07-11 18:11:29 +00005785} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005786
Richard Smith11562c52011-10-28 17:51:58 +00005787/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5788/// produce either the integer value or a pointer.
5789///
5790/// GCC has a heinous extension which folds casts between pointer types and
5791/// pointer-sized integral types. We support this by allowing the evaluation of
5792/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5793/// Some simple arithmetic on such values is supported (they are treated much
5794/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005795static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005796 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005797 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005798 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005799}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005800
Richard Smithf57d8cb2011-12-09 22:58:01 +00005801static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005802 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005803 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005804 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005805 if (!Val.isInt()) {
5806 // FIXME: It would be better to produce the diagnostic for casting
5807 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005808 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005809 return false;
5810 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005811 Result = Val.getInt();
5812 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005813}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005814
Richard Smithf57d8cb2011-12-09 22:58:01 +00005815/// Check whether the given declaration can be directly converted to an integral
5816/// rvalue. If not, no diagnostic is produced; there are other things we can
5817/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005818bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005819 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005820 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005821 // Check for signedness/width mismatches between E type and ECD value.
5822 bool SameSign = (ECD->getInitVal().isSigned()
5823 == E->getType()->isSignedIntegerOrEnumerationType());
5824 bool SameWidth = (ECD->getInitVal().getBitWidth()
5825 == Info.Ctx.getIntWidth(E->getType()));
5826 if (SameSign && SameWidth)
5827 return Success(ECD->getInitVal(), E);
5828 else {
5829 // Get rid of mismatch (otherwise Success assertions will fail)
5830 // by computing a new value matching the type of E.
5831 llvm::APSInt Val = ECD->getInitVal();
5832 if (!SameSign)
5833 Val.setIsSigned(!ECD->getInitVal().isSigned());
5834 if (!SameWidth)
5835 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5836 return Success(Val, E);
5837 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005838 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005839 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005840}
5841
Chris Lattner86ee2862008-10-06 06:40:35 +00005842/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5843/// as GCC.
5844static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5845 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005846 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005847 enum gcc_type_class {
5848 no_type_class = -1,
5849 void_type_class, integer_type_class, char_type_class,
5850 enumeral_type_class, boolean_type_class,
5851 pointer_type_class, reference_type_class, offset_type_class,
5852 real_type_class, complex_type_class,
5853 function_type_class, method_type_class,
5854 record_type_class, union_type_class,
5855 array_type_class, string_type_class,
5856 lang_type_class
5857 };
Mike Stump11289f42009-09-09 15:08:12 +00005858
5859 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005860 // ideal, however it is what gcc does.
5861 if (E->getNumArgs() == 0)
5862 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005863
Chris Lattner86ee2862008-10-06 06:40:35 +00005864 QualType ArgTy = E->getArg(0)->getType();
5865 if (ArgTy->isVoidType())
5866 return void_type_class;
5867 else if (ArgTy->isEnumeralType())
5868 return enumeral_type_class;
5869 else if (ArgTy->isBooleanType())
5870 return boolean_type_class;
5871 else if (ArgTy->isCharType())
5872 return string_type_class; // gcc doesn't appear to use char_type_class
5873 else if (ArgTy->isIntegerType())
5874 return integer_type_class;
5875 else if (ArgTy->isPointerType())
5876 return pointer_type_class;
5877 else if (ArgTy->isReferenceType())
5878 return reference_type_class;
5879 else if (ArgTy->isRealType())
5880 return real_type_class;
5881 else if (ArgTy->isComplexType())
5882 return complex_type_class;
5883 else if (ArgTy->isFunctionType())
5884 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005885 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005886 return record_type_class;
5887 else if (ArgTy->isUnionType())
5888 return union_type_class;
5889 else if (ArgTy->isArrayType())
5890 return array_type_class;
5891 else if (ArgTy->isUnionType())
5892 return union_type_class;
5893 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005894 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005895}
5896
Richard Smith5fab0c92011-12-28 19:48:30 +00005897/// EvaluateBuiltinConstantPForLValue - Determine the result of
5898/// __builtin_constant_p when applied to the given lvalue.
5899///
5900/// An lvalue is only "constant" if it is a pointer or reference to the first
5901/// character of a string literal.
5902template<typename LValue>
5903static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005904 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005905 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5906}
5907
5908/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5909/// GCC as we can manage.
5910static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5911 QualType ArgType = Arg->getType();
5912
5913 // __builtin_constant_p always has one operand. The rules which gcc follows
5914 // are not precisely documented, but are as follows:
5915 //
5916 // - If the operand is of integral, floating, complex or enumeration type,
5917 // and can be folded to a known value of that type, it returns 1.
5918 // - If the operand and can be folded to a pointer to the first character
5919 // of a string literal (or such a pointer cast to an integral type), it
5920 // returns 1.
5921 //
5922 // Otherwise, it returns 0.
5923 //
5924 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5925 // its support for this does not currently work.
5926 if (ArgType->isIntegralOrEnumerationType()) {
5927 Expr::EvalResult Result;
5928 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5929 return false;
5930
5931 APValue &V = Result.Val;
5932 if (V.getKind() == APValue::Int)
5933 return true;
5934
5935 return EvaluateBuiltinConstantPForLValue(V);
5936 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5937 return Arg->isEvaluatable(Ctx);
5938 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5939 LValue LV;
5940 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005941 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005942 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5943 : EvaluatePointer(Arg, LV, Info)) &&
5944 !Status.HasSideEffects)
5945 return EvaluateBuiltinConstantPForLValue(LV);
5946 }
5947
5948 // Anything else isn't considered to be sufficiently constant.
5949 return false;
5950}
5951
John McCall95007602010-05-10 23:27:23 +00005952/// Retrieves the "underlying object type" of the given expression,
5953/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005954QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5955 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5956 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005957 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005958 } else if (const Expr *E = B.get<const Expr*>()) {
5959 if (isa<CompoundLiteralExpr>(E))
5960 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005961 }
5962
5963 return QualType();
5964}
5965
Peter Collingbournee9200682011-05-13 03:29:01 +00005966bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005967 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005968
5969 {
5970 // The operand of __builtin_object_size is never evaluated for side-effects.
5971 // If there are any, but we can determine the pointed-to object anyway, then
5972 // ignore the side-effects.
5973 SpeculativeEvaluationRAII SpeculativeEval(Info);
5974 if (!EvaluatePointer(E->getArg(0), Base, Info))
5975 return false;
5976 }
John McCall95007602010-05-10 23:27:23 +00005977
5978 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005979 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005980
Richard Smithce40ad62011-11-12 22:28:03 +00005981 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005982 if (T.isNull() ||
5983 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005984 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005985 T->isVariablyModifiedType() ||
5986 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005987 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005988
5989 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5990 CharUnits Offset = Base.getLValueOffset();
5991
5992 if (!Offset.isNegative() && Offset <= Size)
5993 Size -= Offset;
5994 else
5995 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005996 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005997}
5998
Peter Collingbournee9200682011-05-13 03:29:01 +00005999bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006000 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006001 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006002 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006003
6004 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006005 if (TryEvaluateBuiltinObjectSize(E))
6006 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006007
Richard Smith0421ce72012-08-07 04:16:51 +00006008 // If evaluating the argument has side-effects, we can't determine the size
6009 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6010 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006011 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006012 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006013 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006014 return Success(0, E);
6015 }
Mike Stump876387b2009-10-27 22:09:17 +00006016
Richard Smith01ade172012-05-23 04:13:20 +00006017 // Expression had no side effects, but we couldn't statically determine the
6018 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006019 switch (Info.EvalMode) {
6020 case EvalInfo::EM_ConstantExpression:
6021 case EvalInfo::EM_PotentialConstantExpression:
6022 case EvalInfo::EM_ConstantFold:
6023 case EvalInfo::EM_EvaluateForOverflow:
6024 case EvalInfo::EM_IgnoreSideEffects:
6025 return Error(E);
6026 case EvalInfo::EM_ConstantExpressionUnevaluated:
6027 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6028 return Success(-1ULL, E);
6029 }
Mike Stump722cedf2009-10-26 18:35:08 +00006030 }
6031
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006032 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006033 case Builtin::BI__builtin_bswap32:
6034 case Builtin::BI__builtin_bswap64: {
6035 APSInt Val;
6036 if (!EvaluateInteger(E->getArg(0), Val, Info))
6037 return false;
6038
6039 return Success(Val.byteSwap(), E);
6040 }
6041
Richard Smith8889a3d2013-06-13 06:26:32 +00006042 case Builtin::BI__builtin_classify_type:
6043 return Success(EvaluateBuiltinClassifyType(E), E);
6044
6045 // FIXME: BI__builtin_clrsb
6046 // FIXME: BI__builtin_clrsbl
6047 // FIXME: BI__builtin_clrsbll
6048
Richard Smith80b3c8e2013-06-13 05:04:16 +00006049 case Builtin::BI__builtin_clz:
6050 case Builtin::BI__builtin_clzl:
6051 case Builtin::BI__builtin_clzll: {
6052 APSInt Val;
6053 if (!EvaluateInteger(E->getArg(0), Val, Info))
6054 return false;
6055 if (!Val)
6056 return Error(E);
6057
6058 return Success(Val.countLeadingZeros(), E);
6059 }
6060
Richard Smith8889a3d2013-06-13 06:26:32 +00006061 case Builtin::BI__builtin_constant_p:
6062 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6063
Richard Smith80b3c8e2013-06-13 05:04:16 +00006064 case Builtin::BI__builtin_ctz:
6065 case Builtin::BI__builtin_ctzl:
6066 case Builtin::BI__builtin_ctzll: {
6067 APSInt Val;
6068 if (!EvaluateInteger(E->getArg(0), Val, Info))
6069 return false;
6070 if (!Val)
6071 return Error(E);
6072
6073 return Success(Val.countTrailingZeros(), E);
6074 }
6075
Richard Smith8889a3d2013-06-13 06:26:32 +00006076 case Builtin::BI__builtin_eh_return_data_regno: {
6077 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6078 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6079 return Success(Operand, E);
6080 }
6081
6082 case Builtin::BI__builtin_expect:
6083 return Visit(E->getArg(0));
6084
6085 case Builtin::BI__builtin_ffs:
6086 case Builtin::BI__builtin_ffsl:
6087 case Builtin::BI__builtin_ffsll: {
6088 APSInt Val;
6089 if (!EvaluateInteger(E->getArg(0), Val, Info))
6090 return false;
6091
6092 unsigned N = Val.countTrailingZeros();
6093 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6094 }
6095
6096 case Builtin::BI__builtin_fpclassify: {
6097 APFloat Val(0.0);
6098 if (!EvaluateFloat(E->getArg(5), Val, Info))
6099 return false;
6100 unsigned Arg;
6101 switch (Val.getCategory()) {
6102 case APFloat::fcNaN: Arg = 0; break;
6103 case APFloat::fcInfinity: Arg = 1; break;
6104 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6105 case APFloat::fcZero: Arg = 4; break;
6106 }
6107 return Visit(E->getArg(Arg));
6108 }
6109
6110 case Builtin::BI__builtin_isinf_sign: {
6111 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006112 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006113 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6114 }
6115
Richard Smithea3019d2013-10-15 19:07:14 +00006116 case Builtin::BI__builtin_isinf: {
6117 APFloat Val(0.0);
6118 return EvaluateFloat(E->getArg(0), Val, Info) &&
6119 Success(Val.isInfinity() ? 1 : 0, E);
6120 }
6121
6122 case Builtin::BI__builtin_isfinite: {
6123 APFloat Val(0.0);
6124 return EvaluateFloat(E->getArg(0), Val, Info) &&
6125 Success(Val.isFinite() ? 1 : 0, E);
6126 }
6127
6128 case Builtin::BI__builtin_isnan: {
6129 APFloat Val(0.0);
6130 return EvaluateFloat(E->getArg(0), Val, Info) &&
6131 Success(Val.isNaN() ? 1 : 0, E);
6132 }
6133
6134 case Builtin::BI__builtin_isnormal: {
6135 APFloat Val(0.0);
6136 return EvaluateFloat(E->getArg(0), Val, Info) &&
6137 Success(Val.isNormal() ? 1 : 0, E);
6138 }
6139
Richard Smith8889a3d2013-06-13 06:26:32 +00006140 case Builtin::BI__builtin_parity:
6141 case Builtin::BI__builtin_parityl:
6142 case Builtin::BI__builtin_parityll: {
6143 APSInt Val;
6144 if (!EvaluateInteger(E->getArg(0), Val, Info))
6145 return false;
6146
6147 return Success(Val.countPopulation() % 2, E);
6148 }
6149
Richard Smith80b3c8e2013-06-13 05:04:16 +00006150 case Builtin::BI__builtin_popcount:
6151 case Builtin::BI__builtin_popcountl:
6152 case Builtin::BI__builtin_popcountll: {
6153 APSInt Val;
6154 if (!EvaluateInteger(E->getArg(0), Val, Info))
6155 return false;
6156
6157 return Success(Val.countPopulation(), E);
6158 }
6159
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006160 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006161 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006162 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006163 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006164 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6165 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006166 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006167 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006168 case Builtin::BI__builtin_strlen: {
6169 // As an extension, we support __builtin_strlen() as a constant expression,
6170 // and support folding strlen() to a constant.
6171 LValue String;
6172 if (!EvaluatePointer(E->getArg(0), String, Info))
6173 return false;
6174
6175 // Fast path: if it's a string literal, search the string value.
6176 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6177 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006178 // The string literal may have embedded null characters. Find the first
6179 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006180 StringRef Str = S->getBytes();
6181 int64_t Off = String.Offset.getQuantity();
6182 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6183 S->getCharByteWidth() == 1) {
6184 Str = Str.substr(Off);
6185
6186 StringRef::size_type Pos = Str.find(0);
6187 if (Pos != StringRef::npos)
6188 Str = Str.substr(0, Pos);
6189
6190 return Success(Str.size(), E);
6191 }
6192
6193 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006194 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006195
6196 // Slow path: scan the bytes of the string looking for the terminating 0.
6197 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6198 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6199 APValue Char;
6200 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6201 !Char.isInt())
6202 return false;
6203 if (!Char.getInt())
6204 return Success(Strlen, E);
6205 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6206 return false;
6207 }
6208 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006209
Richard Smith01ba47d2012-04-13 00:45:38 +00006210 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006211 case Builtin::BI__atomic_is_lock_free:
6212 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006213 APSInt SizeVal;
6214 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6215 return false;
6216
6217 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6218 // of two less than the maximum inline atomic width, we know it is
6219 // lock-free. If the size isn't a power of two, or greater than the
6220 // maximum alignment where we promote atomics, we know it is not lock-free
6221 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6222 // the answer can only be determined at runtime; for example, 16-byte
6223 // atomics have lock-free implementations on some, but not all,
6224 // x86-64 processors.
6225
6226 // Check power-of-two.
6227 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006228 if (Size.isPowerOfTwo()) {
6229 // Check against inlining width.
6230 unsigned InlineWidthBits =
6231 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6232 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6233 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6234 Size == CharUnits::One() ||
6235 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6236 Expr::NPC_NeverValueDependent))
6237 // OK, we will inline appropriately-aligned operations of this size,
6238 // and _Atomic(T) is appropriately-aligned.
6239 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006240
Richard Smith01ba47d2012-04-13 00:45:38 +00006241 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6242 castAs<PointerType>()->getPointeeType();
6243 if (!PointeeType->isIncompleteType() &&
6244 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6245 // OK, we will inline operations on this object.
6246 return Success(1, E);
6247 }
6248 }
6249 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006250
Richard Smith01ba47d2012-04-13 00:45:38 +00006251 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6252 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006253 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006254 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006255}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006256
Richard Smith8b3497e2011-10-31 01:37:14 +00006257static bool HasSameBase(const LValue &A, const LValue &B) {
6258 if (!A.getLValueBase())
6259 return !B.getLValueBase();
6260 if (!B.getLValueBase())
6261 return false;
6262
Richard Smithce40ad62011-11-12 22:28:03 +00006263 if (A.getLValueBase().getOpaqueValue() !=
6264 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006265 const Decl *ADecl = GetLValueBaseDecl(A);
6266 if (!ADecl)
6267 return false;
6268 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006269 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006270 return false;
6271 }
6272
6273 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006274 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006275}
6276
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006277namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006278
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006279/// \brief Data recursive integer evaluator of certain binary operators.
6280///
6281/// We use a data recursive algorithm for binary operators so that we are able
6282/// to handle extreme cases of chained binary operators without causing stack
6283/// overflow.
6284class DataRecursiveIntBinOpEvaluator {
6285 struct EvalResult {
6286 APValue Val;
6287 bool Failed;
6288
6289 EvalResult() : Failed(false) { }
6290
6291 void swap(EvalResult &RHS) {
6292 Val.swap(RHS.Val);
6293 Failed = RHS.Failed;
6294 RHS.Failed = false;
6295 }
6296 };
6297
6298 struct Job {
6299 const Expr *E;
6300 EvalResult LHSResult; // meaningful only for binary operator expression.
6301 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006302
6303 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006304 void startSpeculativeEval(EvalInfo &Info) {
6305 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006306 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006307 StoredInfo = &Info;
6308 }
6309 ~Job() {
6310 if (StoredInfo) {
6311 StoredInfo->EvalStatus = OldEvalStatus;
6312 }
6313 }
6314 private:
6315 EvalInfo *StoredInfo; // non-null if status changed.
6316 Expr::EvalStatus OldEvalStatus;
6317 };
6318
6319 SmallVector<Job, 16> Queue;
6320
6321 IntExprEvaluator &IntEval;
6322 EvalInfo &Info;
6323 APValue &FinalResult;
6324
6325public:
6326 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6327 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6328
6329 /// \brief True if \param E is a binary operator that we are going to handle
6330 /// data recursively.
6331 /// We handle binary operators that are comma, logical, or that have operands
6332 /// with integral or enumeration type.
6333 static bool shouldEnqueue(const BinaryOperator *E) {
6334 return E->getOpcode() == BO_Comma ||
6335 E->isLogicalOp() ||
6336 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6337 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006338 }
6339
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006340 bool Traverse(const BinaryOperator *E) {
6341 enqueue(E);
6342 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006343 while (!Queue.empty())
6344 process(PrevResult);
6345
6346 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006347
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006348 FinalResult.swap(PrevResult.Val);
6349 return true;
6350 }
6351
6352private:
6353 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6354 return IntEval.Success(Value, E, Result);
6355 }
6356 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6357 return IntEval.Success(Value, E, Result);
6358 }
6359 bool Error(const Expr *E) {
6360 return IntEval.Error(E);
6361 }
6362 bool Error(const Expr *E, diag::kind D) {
6363 return IntEval.Error(E, D);
6364 }
6365
6366 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6367 return Info.CCEDiag(E, D);
6368 }
6369
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006370 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6371 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006372 bool &SuppressRHSDiags);
6373
6374 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6375 const BinaryOperator *E, APValue &Result);
6376
6377 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6378 Result.Failed = !Evaluate(Result.Val, Info, E);
6379 if (Result.Failed)
6380 Result.Val = APValue();
6381 }
6382
Richard Trieuba4d0872012-03-21 23:30:30 +00006383 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006384
6385 void enqueue(const Expr *E) {
6386 E = E->IgnoreParens();
6387 Queue.resize(Queue.size()+1);
6388 Queue.back().E = E;
6389 Queue.back().Kind = Job::AnyExprKind;
6390 }
6391};
6392
6393}
6394
6395bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006396 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006397 bool &SuppressRHSDiags) {
6398 if (E->getOpcode() == BO_Comma) {
6399 // Ignore LHS but note if we could not evaluate it.
6400 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006401 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006402 return true;
6403 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006404
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006405 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006406 bool LHSAsBool;
6407 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006408 // We were able to evaluate the LHS, see if we can get away with not
6409 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006410 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6411 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006412 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006413 }
6414 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006415 LHSResult.Failed = true;
6416
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006417 // Since we weren't able to evaluate the left hand side, it
6418 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006419 if (!Info.noteSideEffect())
6420 return false;
6421
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006422 // We can't evaluate the LHS; however, sometimes the result
6423 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6424 // Don't ignore RHS and suppress diagnostics from this arm.
6425 SuppressRHSDiags = true;
6426 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006427
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006428 return true;
6429 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006430
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006431 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6432 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006433
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006434 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006435 return false; // Ignore RHS;
6436
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006437 return true;
6438}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006439
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006440bool DataRecursiveIntBinOpEvaluator::
6441 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6442 const BinaryOperator *E, APValue &Result) {
6443 if (E->getOpcode() == BO_Comma) {
6444 if (RHSResult.Failed)
6445 return false;
6446 Result = RHSResult.Val;
6447 return true;
6448 }
6449
6450 if (E->isLogicalOp()) {
6451 bool lhsResult, rhsResult;
6452 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6453 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6454
6455 if (LHSIsOK) {
6456 if (RHSIsOK) {
6457 if (E->getOpcode() == BO_LOr)
6458 return Success(lhsResult || rhsResult, E, Result);
6459 else
6460 return Success(lhsResult && rhsResult, E, Result);
6461 }
6462 } else {
6463 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006464 // We can't evaluate the LHS; however, sometimes the result
6465 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6466 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006467 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006468 }
6469 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006470
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006471 return false;
6472 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006473
6474 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6475 E->getRHS()->getType()->isIntegralOrEnumerationType());
6476
6477 if (LHSResult.Failed || RHSResult.Failed)
6478 return false;
6479
6480 const APValue &LHSVal = LHSResult.Val;
6481 const APValue &RHSVal = RHSResult.Val;
6482
6483 // Handle cases like (unsigned long)&a + 4.
6484 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6485 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006486 CharUnits AdditionalOffset =
6487 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006488 if (E->getOpcode() == BO_Add)
6489 Result.getLValueOffset() += AdditionalOffset;
6490 else
6491 Result.getLValueOffset() -= AdditionalOffset;
6492 return true;
6493 }
6494
6495 // Handle cases like 4 + (unsigned long)&a
6496 if (E->getOpcode() == BO_Add &&
6497 RHSVal.isLValue() && LHSVal.isInt()) {
6498 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006499 Result.getLValueOffset() +=
6500 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006501 return true;
6502 }
6503
6504 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6505 // Handle (intptr_t)&&A - (intptr_t)&&B.
6506 if (!LHSVal.getLValueOffset().isZero() ||
6507 !RHSVal.getLValueOffset().isZero())
6508 return false;
6509 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6510 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6511 if (!LHSExpr || !RHSExpr)
6512 return false;
6513 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6514 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6515 if (!LHSAddrExpr || !RHSAddrExpr)
6516 return false;
6517 // Make sure both labels come from the same function.
6518 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6519 RHSAddrExpr->getLabel()->getDeclContext())
6520 return false;
6521 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6522 return true;
6523 }
Richard Smith43e77732013-05-07 04:50:00 +00006524
6525 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006526 if (!LHSVal.isInt() || !RHSVal.isInt())
6527 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006528
6529 // Set up the width and signedness manually, in case it can't be deduced
6530 // from the operation we're performing.
6531 // FIXME: Don't do this in the cases where we can deduce it.
6532 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6533 E->getType()->isUnsignedIntegerOrEnumerationType());
6534 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6535 RHSVal.getInt(), Value))
6536 return false;
6537 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006538}
6539
Richard Trieuba4d0872012-03-21 23:30:30 +00006540void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006541 Job &job = Queue.back();
6542
6543 switch (job.Kind) {
6544 case Job::AnyExprKind: {
6545 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6546 if (shouldEnqueue(Bop)) {
6547 job.Kind = Job::BinOpKind;
6548 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006549 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006550 }
6551 }
6552
6553 EvaluateExpr(job.E, Result);
6554 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006555 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006556 }
6557
6558 case Job::BinOpKind: {
6559 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006560 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006561 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006562 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006563 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006564 }
6565 if (SuppressRHSDiags)
6566 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006567 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006568 job.Kind = Job::BinOpVisitedLHSKind;
6569 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006570 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006571 }
6572
6573 case Job::BinOpVisitedLHSKind: {
6574 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6575 EvalResult RHS;
6576 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006577 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006578 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006579 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006580 }
6581 }
6582
6583 llvm_unreachable("Invalid Job::Kind!");
6584}
6585
6586bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6587 if (E->isAssignmentOp())
6588 return Error(E);
6589
6590 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6591 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006592
Anders Carlssonacc79812008-11-16 07:17:21 +00006593 QualType LHSTy = E->getLHS()->getType();
6594 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006595
6596 if (LHSTy->isAnyComplexType()) {
6597 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006598 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006599
Richard Smith253c2a32012-01-27 01:14:48 +00006600 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6601 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006602 return false;
6603
Richard Smith253c2a32012-01-27 01:14:48 +00006604 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006605 return false;
6606
6607 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006608 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006609 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006610 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006611 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6612
John McCalle3027922010-08-25 11:45:40 +00006613 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006614 return Success((CR_r == APFloat::cmpEqual &&
6615 CR_i == APFloat::cmpEqual), E);
6616 else {
John McCalle3027922010-08-25 11:45:40 +00006617 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006618 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006619 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006620 CR_r == APFloat::cmpLessThan ||
6621 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006622 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006623 CR_i == APFloat::cmpLessThan ||
6624 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006625 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006626 } else {
John McCalle3027922010-08-25 11:45:40 +00006627 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006628 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6629 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6630 else {
John McCalle3027922010-08-25 11:45:40 +00006631 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006632 "Invalid compex comparison.");
6633 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6634 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6635 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006636 }
6637 }
Mike Stump11289f42009-09-09 15:08:12 +00006638
Anders Carlssonacc79812008-11-16 07:17:21 +00006639 if (LHSTy->isRealFloatingType() &&
6640 RHSTy->isRealFloatingType()) {
6641 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006642
Richard Smith253c2a32012-01-27 01:14:48 +00006643 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6644 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006645 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006646
Richard Smith253c2a32012-01-27 01:14:48 +00006647 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006648 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006649
Anders Carlssonacc79812008-11-16 07:17:21 +00006650 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006651
Anders Carlssonacc79812008-11-16 07:17:21 +00006652 switch (E->getOpcode()) {
6653 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006654 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006655 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006656 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006657 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006658 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006659 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006660 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006661 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006662 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006663 E);
John McCalle3027922010-08-25 11:45:40 +00006664 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006665 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006666 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006667 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006668 || CR == APFloat::cmpLessThan
6669 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006670 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006671 }
Mike Stump11289f42009-09-09 15:08:12 +00006672
Eli Friedmana38da572009-04-28 19:17:36 +00006673 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006674 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006675 LValue LHSValue, RHSValue;
6676
6677 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6678 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006679 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006680
Richard Smith253c2a32012-01-27 01:14:48 +00006681 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006682 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006683
Richard Smith8b3497e2011-10-31 01:37:14 +00006684 // Reject differing bases from the normal codepath; we special-case
6685 // comparisons to null.
6686 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006687 if (E->getOpcode() == BO_Sub) {
6688 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006689 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6690 return false;
6691 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006692 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006693 if (!LHSExpr || !RHSExpr)
6694 return false;
6695 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6696 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6697 if (!LHSAddrExpr || !RHSAddrExpr)
6698 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006699 // Make sure both labels come from the same function.
6700 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6701 RHSAddrExpr->getLabel()->getDeclContext())
6702 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006703 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006704 return true;
6705 }
Richard Smith83c68212011-10-31 05:11:32 +00006706 // Inequalities and subtractions between unrelated pointers have
6707 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006708 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006709 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006710 // A constant address may compare equal to the address of a symbol.
6711 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006712 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006713 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6714 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006715 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006716 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006717 // distinct addresses. In clang, the result of such a comparison is
6718 // unspecified, so it is not a constant expression. However, we do know
6719 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006720 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6721 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006722 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006723 // We can't tell whether weak symbols will end up pointing to the same
6724 // object.
6725 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006726 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006727 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006728 // (Note that clang defaults to -fmerge-all-constants, which can
6729 // lead to inconsistent results for comparisons involving the address
6730 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006731 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006732 }
Eli Friedman64004332009-03-23 04:38:34 +00006733
Richard Smith1b470412012-02-01 08:10:20 +00006734 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6735 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6736
Richard Smith84f6dcf2012-02-02 01:16:57 +00006737 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6738 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6739
John McCalle3027922010-08-25 11:45:40 +00006740 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006741 // C++11 [expr.add]p6:
6742 // Unless both pointers point to elements of the same array object, or
6743 // one past the last element of the array object, the behavior is
6744 // undefined.
6745 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6746 !AreElementsOfSameArray(getType(LHSValue.Base),
6747 LHSDesignator, RHSDesignator))
6748 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6749
Chris Lattner882bdf22010-04-20 17:13:14 +00006750 QualType Type = E->getLHS()->getType();
6751 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006752
Richard Smithd62306a2011-11-10 06:34:14 +00006753 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006754 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006755 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006756
Richard Smith84c6b3d2013-09-10 21:34:14 +00006757 // As an extension, a type may have zero size (empty struct or union in
6758 // C, array of zero length). Pointer subtraction in such cases has
6759 // undefined behavior, so is not constant.
6760 if (ElementSize.isZero()) {
6761 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6762 << ElementType;
6763 return false;
6764 }
6765
Richard Smith1b470412012-02-01 08:10:20 +00006766 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6767 // and produce incorrect results when it overflows. Such behavior
6768 // appears to be non-conforming, but is common, so perhaps we should
6769 // assume the standard intended for such cases to be undefined behavior
6770 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006771
Richard Smith1b470412012-02-01 08:10:20 +00006772 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6773 // overflow in the final conversion to ptrdiff_t.
6774 APSInt LHS(
6775 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6776 APSInt RHS(
6777 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6778 APSInt ElemSize(
6779 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6780 APSInt TrueResult = (LHS - RHS) / ElemSize;
6781 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6782
6783 if (Result.extend(65) != TrueResult)
6784 HandleOverflow(Info, E, TrueResult, E->getType());
6785 return Success(Result, E);
6786 }
Richard Smithde21b242012-01-31 06:41:30 +00006787
6788 // C++11 [expr.rel]p3:
6789 // Pointers to void (after pointer conversions) can be compared, with a
6790 // result defined as follows: If both pointers represent the same
6791 // address or are both the null pointer value, the result is true if the
6792 // operator is <= or >= and false otherwise; otherwise the result is
6793 // unspecified.
6794 // We interpret this as applying to pointers to *cv* void.
6795 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006796 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006797 CCEDiag(E, diag::note_constexpr_void_comparison);
6798
Richard Smith84f6dcf2012-02-02 01:16:57 +00006799 // C++11 [expr.rel]p2:
6800 // - If two pointers point to non-static data members of the same object,
6801 // or to subobjects or array elements fo such members, recursively, the
6802 // pointer to the later declared member compares greater provided the
6803 // two members have the same access control and provided their class is
6804 // not a union.
6805 // [...]
6806 // - Otherwise pointer comparisons are unspecified.
6807 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6808 E->isRelationalOp()) {
6809 bool WasArrayIndex;
6810 unsigned Mismatch =
6811 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6812 RHSDesignator, WasArrayIndex);
6813 // At the point where the designators diverge, the comparison has a
6814 // specified value if:
6815 // - we are comparing array indices
6816 // - we are comparing fields of a union, or fields with the same access
6817 // Otherwise, the result is unspecified and thus the comparison is not a
6818 // constant expression.
6819 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6820 Mismatch < RHSDesignator.Entries.size()) {
6821 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6822 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6823 if (!LF && !RF)
6824 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6825 else if (!LF)
6826 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6827 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6828 << RF->getParent() << RF;
6829 else if (!RF)
6830 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6831 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6832 << LF->getParent() << LF;
6833 else if (!LF->getParent()->isUnion() &&
6834 LF->getAccess() != RF->getAccess())
6835 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6836 << LF << LF->getAccess() << RF << RF->getAccess()
6837 << LF->getParent();
6838 }
6839 }
6840
Eli Friedman6c31cb42012-04-16 04:30:08 +00006841 // The comparison here must be unsigned, and performed with the same
6842 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006843 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6844 uint64_t CompareLHS = LHSOffset.getQuantity();
6845 uint64_t CompareRHS = RHSOffset.getQuantity();
6846 assert(PtrSize <= 64 && "Unexpected pointer width");
6847 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6848 CompareLHS &= Mask;
6849 CompareRHS &= Mask;
6850
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006851 // If there is a base and this is a relational operator, we can only
6852 // compare pointers within the object in question; otherwise, the result
6853 // depends on where the object is located in memory.
6854 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6855 QualType BaseTy = getType(LHSValue.Base);
6856 if (BaseTy->isIncompleteType())
6857 return Error(E);
6858 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6859 uint64_t OffsetLimit = Size.getQuantity();
6860 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6861 return Error(E);
6862 }
6863
Richard Smith8b3497e2011-10-31 01:37:14 +00006864 switch (E->getOpcode()) {
6865 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006866 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6867 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6868 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6869 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6870 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6871 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006872 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006873 }
6874 }
Richard Smith7bb00672012-02-01 01:42:44 +00006875
6876 if (LHSTy->isMemberPointerType()) {
6877 assert(E->isEqualityOp() && "unexpected member pointer operation");
6878 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6879
6880 MemberPtr LHSValue, RHSValue;
6881
6882 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6883 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6884 return false;
6885
6886 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6887 return false;
6888
6889 // C++11 [expr.eq]p2:
6890 // If both operands are null, they compare equal. Otherwise if only one is
6891 // null, they compare unequal.
6892 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6893 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6894 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6895 }
6896
6897 // Otherwise if either is a pointer to a virtual member function, the
6898 // result is unspecified.
6899 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6900 if (MD->isVirtual())
6901 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6902 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6903 if (MD->isVirtual())
6904 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6905
6906 // Otherwise they compare equal if and only if they would refer to the
6907 // same member of the same most derived object or the same subobject if
6908 // they were dereferenced with a hypothetical object of the associated
6909 // class type.
6910 bool Equal = LHSValue == RHSValue;
6911 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6912 }
6913
Richard Smithab44d9b2012-02-14 22:35:28 +00006914 if (LHSTy->isNullPtrType()) {
6915 assert(E->isComparisonOp() && "unexpected nullptr operation");
6916 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6917 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6918 // are compared, the result is true of the operator is <=, >= or ==, and
6919 // false otherwise.
6920 BinaryOperator::Opcode Opcode = E->getOpcode();
6921 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6922 }
6923
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006924 assert((!LHSTy->isIntegralOrEnumerationType() ||
6925 !RHSTy->isIntegralOrEnumerationType()) &&
6926 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6927 // We can't continue from here for non-integral types.
6928 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006929}
6930
Ken Dyck160146e2010-01-27 17:10:57 +00006931CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Richard Smithf6d70302014-06-10 23:34:28 +00006932 // C++ [expr.alignof]p3:
6933 // When alignof is applied to a reference type, the result is the
6934 // alignment of the referenced type.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006935 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6936 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006937
6938 // __alignof is defined to return the preferred alignment.
6939 return Info.Ctx.toCharUnitsFromBits(
6940 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006941}
6942
Ken Dyck160146e2010-01-27 17:10:57 +00006943CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006944 E = E->IgnoreParens();
6945
John McCall768439e2013-05-06 07:40:34 +00006946 // The kinds of expressions that we have special-case logic here for
6947 // should be kept up to date with the special checks for those
6948 // expressions in Sema.
6949
Chris Lattner68061312009-01-24 21:53:27 +00006950 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006951 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006952 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithf6d70302014-06-10 23:34:28 +00006953 return Info.Ctx.getDeclAlign(DRE->getDecl(),
Ken Dyck160146e2010-01-27 17:10:57 +00006954 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006955
Chris Lattner68061312009-01-24 21:53:27 +00006956 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006957 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6958 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006959
Chris Lattner24aeeab2009-01-24 21:09:06 +00006960 return GetAlignOfType(E->getType());
6961}
6962
6963
Peter Collingbournee190dee2011-03-11 19:24:49 +00006964/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6965/// a result as the expression's type.
6966bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6967 const UnaryExprOrTypeTraitExpr *E) {
6968 switch(E->getKind()) {
6969 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006970 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006971 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006972 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006973 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006974 }
Eli Friedman64004332009-03-23 04:38:34 +00006975
Peter Collingbournee190dee2011-03-11 19:24:49 +00006976 case UETT_VecStep: {
6977 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006978
Peter Collingbournee190dee2011-03-11 19:24:49 +00006979 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006980 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006981
Peter Collingbournee190dee2011-03-11 19:24:49 +00006982 // The vec_step built-in functions that take a 3-component
6983 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6984 if (n == 3)
6985 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006986
Peter Collingbournee190dee2011-03-11 19:24:49 +00006987 return Success(n, E);
6988 } else
6989 return Success(1, E);
6990 }
6991
6992 case UETT_SizeOf: {
6993 QualType SrcTy = E->getTypeOfArgument();
6994 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6995 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006996 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6997 SrcTy = Ref->getPointeeType();
6998
Richard Smithd62306a2011-11-10 06:34:14 +00006999 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007000 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007001 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007002 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007003 }
7004 }
7005
7006 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007007}
7008
Peter Collingbournee9200682011-05-13 03:29:01 +00007009bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007010 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007011 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007012 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007013 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007014 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007015 for (unsigned i = 0; i != n; ++i) {
7016 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7017 switch (ON.getKind()) {
7018 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007019 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007020 APSInt IdxResult;
7021 if (!EvaluateInteger(Idx, IdxResult, Info))
7022 return false;
7023 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7024 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007026 CurrentType = AT->getElementType();
7027 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7028 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007029 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007030 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007031
Douglas Gregor882211c2010-04-28 22:16:22 +00007032 case OffsetOfExpr::OffsetOfNode::Field: {
7033 FieldDecl *MemberDecl = ON.getField();
7034 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007035 if (!RT)
7036 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007037 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007038 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007039 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007040 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007041 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007042 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007043 CurrentType = MemberDecl->getType().getNonReferenceType();
7044 break;
7045 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007046
Douglas Gregor882211c2010-04-28 22:16:22 +00007047 case OffsetOfExpr::OffsetOfNode::Identifier:
7048 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007049
Douglas Gregord1702062010-04-29 00:18:15 +00007050 case OffsetOfExpr::OffsetOfNode::Base: {
7051 CXXBaseSpecifier *BaseSpec = ON.getBase();
7052 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007053 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007054
7055 // Find the layout of the class whose base we are looking into.
7056 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007057 if (!RT)
7058 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007059 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007060 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007061 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7062
7063 // Find the base class itself.
7064 CurrentType = BaseSpec->getType();
7065 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7066 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007067 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007068
7069 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007070 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007071 break;
7072 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007073 }
7074 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007075 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007076}
7077
Chris Lattnere13042c2008-07-11 19:10:17 +00007078bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007079 switch (E->getOpcode()) {
7080 default:
7081 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7082 // See C99 6.6p3.
7083 return Error(E);
7084 case UO_Extension:
7085 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7086 // If so, we could clear the diagnostic ID.
7087 return Visit(E->getSubExpr());
7088 case UO_Plus:
7089 // The result is just the value.
7090 return Visit(E->getSubExpr());
7091 case UO_Minus: {
7092 if (!Visit(E->getSubExpr()))
7093 return false;
7094 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007095 const APSInt &Value = Result.getInt();
7096 if (Value.isSigned() && Value.isMinSignedValue())
7097 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7098 E->getType());
7099 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007100 }
7101 case UO_Not: {
7102 if (!Visit(E->getSubExpr()))
7103 return false;
7104 if (!Result.isInt()) return Error(E);
7105 return Success(~Result.getInt(), E);
7106 }
7107 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007108 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007109 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007110 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007111 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007112 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007113 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007114}
Mike Stump11289f42009-09-09 15:08:12 +00007115
Chris Lattner477c4be2008-07-12 01:15:53 +00007116/// HandleCast - This is used to evaluate implicit or explicit casts where the
7117/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007118bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7119 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007120 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007121 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007122
Eli Friedmanc757de22011-03-25 00:43:55 +00007123 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007124 case CK_BaseToDerived:
7125 case CK_DerivedToBase:
7126 case CK_UncheckedDerivedToBase:
7127 case CK_Dynamic:
7128 case CK_ToUnion:
7129 case CK_ArrayToPointerDecay:
7130 case CK_FunctionToPointerDecay:
7131 case CK_NullToPointer:
7132 case CK_NullToMemberPointer:
7133 case CK_BaseToDerivedMemberPointer:
7134 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007135 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007136 case CK_ConstructorConversion:
7137 case CK_IntegralToPointer:
7138 case CK_ToVoid:
7139 case CK_VectorSplat:
7140 case CK_IntegralToFloating:
7141 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007142 case CK_CPointerToObjCPointerCast:
7143 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007144 case CK_AnyPointerToBlockPointerCast:
7145 case CK_ObjCObjectLValueCast:
7146 case CK_FloatingRealToComplex:
7147 case CK_FloatingComplexToReal:
7148 case CK_FloatingComplexCast:
7149 case CK_FloatingComplexToIntegralComplex:
7150 case CK_IntegralRealToComplex:
7151 case CK_IntegralComplexCast:
7152 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007153 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007154 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007155 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007156 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007157 llvm_unreachable("invalid cast kind for integral value");
7158
Eli Friedman9faf2f92011-03-25 19:07:11 +00007159 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007160 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007161 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007162 case CK_ARCProduceObject:
7163 case CK_ARCConsumeObject:
7164 case CK_ARCReclaimReturnedObject:
7165 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007166 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007167 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007168
Richard Smith4ef685b2012-01-17 21:17:26 +00007169 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007170 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007171 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007172 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007173 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007174
7175 case CK_MemberPointerToBoolean:
7176 case CK_PointerToBoolean:
7177 case CK_IntegralToBoolean:
7178 case CK_FloatingToBoolean:
7179 case CK_FloatingComplexToBoolean:
7180 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007181 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007182 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007183 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007184 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007185 }
7186
Eli Friedmanc757de22011-03-25 00:43:55 +00007187 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007188 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007189 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007190
Eli Friedman742421e2009-02-20 01:15:07 +00007191 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007192 // Allow casts of address-of-label differences if they are no-ops
7193 // or narrowing. (The narrowing case isn't actually guaranteed to
7194 // be constant-evaluatable except in some narrow cases which are hard
7195 // to detect here. We let it through on the assumption the user knows
7196 // what they are doing.)
7197 if (Result.isAddrLabelDiff())
7198 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007199 // Only allow casts of lvalues if they are lossless.
7200 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7201 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007202
Richard Smith911e1422012-01-30 22:27:01 +00007203 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7204 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007205 }
Mike Stump11289f42009-09-09 15:08:12 +00007206
Eli Friedmanc757de22011-03-25 00:43:55 +00007207 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007208 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7209
John McCall45d55e42010-05-07 21:00:08 +00007210 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007211 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007212 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007213
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007214 if (LV.getLValueBase()) {
7215 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007216 // FIXME: Allow a larger integer size than the pointer size, and allow
7217 // narrowing back down to pointer width in subsequent integral casts.
7218 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007219 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007220 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007221
Richard Smithcf74da72011-11-16 07:18:12 +00007222 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007223 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007224 return true;
7225 }
7226
Ken Dyck02990832010-01-15 12:37:54 +00007227 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7228 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007229 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007230 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007231
Eli Friedmanc757de22011-03-25 00:43:55 +00007232 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007233 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007234 if (!EvaluateComplex(SubExpr, C, Info))
7235 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007236 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007237 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007238
Eli Friedmanc757de22011-03-25 00:43:55 +00007239 case CK_FloatingToIntegral: {
7240 APFloat F(0.0);
7241 if (!EvaluateFloat(SubExpr, F, Info))
7242 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007243
Richard Smith357362d2011-12-13 06:39:58 +00007244 APSInt Value;
7245 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7246 return false;
7247 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007248 }
7249 }
Mike Stump11289f42009-09-09 15:08:12 +00007250
Eli Friedmanc757de22011-03-25 00:43:55 +00007251 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007252}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007253
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007254bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7255 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007256 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007257 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7258 return false;
7259 if (!LV.isComplexInt())
7260 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007261 return Success(LV.getComplexIntReal(), E);
7262 }
7263
7264 return Visit(E->getSubExpr());
7265}
7266
Eli Friedman4e7a2412009-02-27 04:45:43 +00007267bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007268 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007269 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007270 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7271 return false;
7272 if (!LV.isComplexInt())
7273 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007274 return Success(LV.getComplexIntImag(), E);
7275 }
7276
Richard Smith4a678122011-10-24 18:44:57 +00007277 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007278 return Success(0, E);
7279}
7280
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007281bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7282 return Success(E->getPackLength(), E);
7283}
7284
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007285bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7286 return Success(E->getValue(), E);
7287}
7288
Chris Lattner05706e882008-07-11 18:11:29 +00007289//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007290// Float Evaluation
7291//===----------------------------------------------------------------------===//
7292
7293namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007294class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007295 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007296 APFloat &Result;
7297public:
7298 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007299 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007300
Richard Smith2e312c82012-03-03 22:46:17 +00007301 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007302 Result = V.getFloat();
7303 return true;
7304 }
Eli Friedman24c01542008-08-22 00:06:13 +00007305
Richard Smithfddd3842011-12-30 21:15:51 +00007306 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007307 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7308 return true;
7309 }
7310
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007311 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007312
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007313 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007314 bool VisitBinaryOperator(const BinaryOperator *E);
7315 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007316 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007317
John McCallb1fb0d32010-05-07 22:08:54 +00007318 bool VisitUnaryReal(const UnaryOperator *E);
7319 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007320
Richard Smithfddd3842011-12-30 21:15:51 +00007321 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007322};
7323} // end anonymous namespace
7324
7325static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007326 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007327 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007328}
7329
Jay Foad39c79802011-01-12 09:06:06 +00007330static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007331 QualType ResultTy,
7332 const Expr *Arg,
7333 bool SNaN,
7334 llvm::APFloat &Result) {
7335 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7336 if (!S) return false;
7337
7338 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7339
7340 llvm::APInt fill;
7341
7342 // Treat empty strings as if they were zero.
7343 if (S->getString().empty())
7344 fill = llvm::APInt(32, 0);
7345 else if (S->getString().getAsInteger(0, fill))
7346 return false;
7347
7348 if (SNaN)
7349 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7350 else
7351 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7352 return true;
7353}
7354
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007355bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007356 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007357 default:
7358 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7359
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007360 case Builtin::BI__builtin_huge_val:
7361 case Builtin::BI__builtin_huge_valf:
7362 case Builtin::BI__builtin_huge_vall:
7363 case Builtin::BI__builtin_inf:
7364 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007365 case Builtin::BI__builtin_infl: {
7366 const llvm::fltSemantics &Sem =
7367 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007368 Result = llvm::APFloat::getInf(Sem);
7369 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007370 }
Mike Stump11289f42009-09-09 15:08:12 +00007371
John McCall16291492010-02-28 13:00:19 +00007372 case Builtin::BI__builtin_nans:
7373 case Builtin::BI__builtin_nansf:
7374 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007375 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7376 true, Result))
7377 return Error(E);
7378 return true;
John McCall16291492010-02-28 13:00:19 +00007379
Chris Lattner0b7282e2008-10-06 06:31:58 +00007380 case Builtin::BI__builtin_nan:
7381 case Builtin::BI__builtin_nanf:
7382 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007383 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007384 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007385 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7386 false, Result))
7387 return Error(E);
7388 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007389
7390 case Builtin::BI__builtin_fabs:
7391 case Builtin::BI__builtin_fabsf:
7392 case Builtin::BI__builtin_fabsl:
7393 if (!EvaluateFloat(E->getArg(0), Result, Info))
7394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007395
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007396 if (Result.isNegative())
7397 Result.changeSign();
7398 return true;
7399
Richard Smith8889a3d2013-06-13 06:26:32 +00007400 // FIXME: Builtin::BI__builtin_powi
7401 // FIXME: Builtin::BI__builtin_powif
7402 // FIXME: Builtin::BI__builtin_powil
7403
Mike Stump11289f42009-09-09 15:08:12 +00007404 case Builtin::BI__builtin_copysign:
7405 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007406 case Builtin::BI__builtin_copysignl: {
7407 APFloat RHS(0.);
7408 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7409 !EvaluateFloat(E->getArg(1), RHS, Info))
7410 return false;
7411 Result.copySign(RHS);
7412 return true;
7413 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007414 }
7415}
7416
John McCallb1fb0d32010-05-07 22:08:54 +00007417bool FloatExprEvaluator::VisitUnaryReal(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.FloatReal;
7423 return true;
7424 }
7425
7426 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007427}
7428
7429bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007430 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7431 ComplexValue CV;
7432 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7433 return false;
7434 Result = CV.FloatImag;
7435 return true;
7436 }
7437
Richard Smith4a678122011-10-24 18:44:57 +00007438 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007439 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7440 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007441 return true;
7442}
7443
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007444bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007445 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007446 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007447 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007448 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007449 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007450 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7451 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007452 Result.changeSign();
7453 return true;
7454 }
7455}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007456
Eli Friedman24c01542008-08-22 00:06:13 +00007457bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007458 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7459 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007460
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007461 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007462 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7463 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007464 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007465 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7466 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007467}
7468
7469bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7470 Result = E->getValue();
7471 return true;
7472}
7473
Peter Collingbournee9200682011-05-13 03:29:01 +00007474bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7475 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007476
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007477 switch (E->getCastKind()) {
7478 default:
Richard Smith11562c52011-10-28 17:51:58 +00007479 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007480
7481 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007482 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007483 return EvaluateInteger(SubExpr, IntResult, Info) &&
7484 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7485 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007486 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007487
7488 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007489 if (!Visit(SubExpr))
7490 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007491 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7492 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007493 }
John McCalld7646252010-11-14 08:17:51 +00007494
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007495 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007496 ComplexValue V;
7497 if (!EvaluateComplex(SubExpr, V, Info))
7498 return false;
7499 Result = V.getComplexFloatReal();
7500 return true;
7501 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007502 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007503}
7504
Eli Friedman24c01542008-08-22 00:06:13 +00007505//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007506// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007507//===----------------------------------------------------------------------===//
7508
7509namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007510class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007511 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007512 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007513
Anders Carlsson537969c2008-11-16 20:27:53 +00007514public:
John McCall93d91dc2010-05-07 17:22:02 +00007515 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007516 : ExprEvaluatorBaseTy(info), Result(Result) {}
7517
Richard Smith2e312c82012-03-03 22:46:17 +00007518 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007519 Result.setFrom(V);
7520 return true;
7521 }
Mike Stump11289f42009-09-09 15:08:12 +00007522
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007523 bool ZeroInitialization(const Expr *E);
7524
Anders Carlsson537969c2008-11-16 20:27:53 +00007525 //===--------------------------------------------------------------------===//
7526 // Visitor Methods
7527 //===--------------------------------------------------------------------===//
7528
Peter Collingbournee9200682011-05-13 03:29:01 +00007529 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007530 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007531 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007532 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007533 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007534};
7535} // end anonymous namespace
7536
John McCall93d91dc2010-05-07 17:22:02 +00007537static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7538 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007539 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007540 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007541}
7542
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007543bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007544 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007545 if (ElemTy->isRealFloatingType()) {
7546 Result.makeComplexFloat();
7547 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7548 Result.FloatReal = Zero;
7549 Result.FloatImag = Zero;
7550 } else {
7551 Result.makeComplexInt();
7552 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7553 Result.IntReal = Zero;
7554 Result.IntImag = Zero;
7555 }
7556 return true;
7557}
7558
Peter Collingbournee9200682011-05-13 03:29:01 +00007559bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7560 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007561
7562 if (SubExpr->getType()->isRealFloatingType()) {
7563 Result.makeComplexFloat();
7564 APFloat &Imag = Result.FloatImag;
7565 if (!EvaluateFloat(SubExpr, Imag, Info))
7566 return false;
7567
7568 Result.FloatReal = APFloat(Imag.getSemantics());
7569 return true;
7570 } else {
7571 assert(SubExpr->getType()->isIntegerType() &&
7572 "Unexpected imaginary literal.");
7573
7574 Result.makeComplexInt();
7575 APSInt &Imag = Result.IntImag;
7576 if (!EvaluateInteger(SubExpr, Imag, Info))
7577 return false;
7578
7579 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7580 return true;
7581 }
7582}
7583
Peter Collingbournee9200682011-05-13 03:29:01 +00007584bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007585
John McCallfcef3cf2010-12-14 17:51:41 +00007586 switch (E->getCastKind()) {
7587 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007588 case CK_BaseToDerived:
7589 case CK_DerivedToBase:
7590 case CK_UncheckedDerivedToBase:
7591 case CK_Dynamic:
7592 case CK_ToUnion:
7593 case CK_ArrayToPointerDecay:
7594 case CK_FunctionToPointerDecay:
7595 case CK_NullToPointer:
7596 case CK_NullToMemberPointer:
7597 case CK_BaseToDerivedMemberPointer:
7598 case CK_DerivedToBaseMemberPointer:
7599 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007600 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007601 case CK_ConstructorConversion:
7602 case CK_IntegralToPointer:
7603 case CK_PointerToIntegral:
7604 case CK_PointerToBoolean:
7605 case CK_ToVoid:
7606 case CK_VectorSplat:
7607 case CK_IntegralCast:
7608 case CK_IntegralToBoolean:
7609 case CK_IntegralToFloating:
7610 case CK_FloatingToIntegral:
7611 case CK_FloatingToBoolean:
7612 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007613 case CK_CPointerToObjCPointerCast:
7614 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007615 case CK_AnyPointerToBlockPointerCast:
7616 case CK_ObjCObjectLValueCast:
7617 case CK_FloatingComplexToReal:
7618 case CK_FloatingComplexToBoolean:
7619 case CK_IntegralComplexToReal:
7620 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007621 case CK_ARCProduceObject:
7622 case CK_ARCConsumeObject:
7623 case CK_ARCReclaimReturnedObject:
7624 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007625 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007626 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007627 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007628 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007629 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007630 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007631
John McCallfcef3cf2010-12-14 17:51:41 +00007632 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007633 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007634 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007635 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007636
7637 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007638 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007639 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007640 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007641
7642 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007643 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007644 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007645 return false;
7646
John McCallfcef3cf2010-12-14 17:51:41 +00007647 Result.makeComplexFloat();
7648 Result.FloatImag = APFloat(Real.getSemantics());
7649 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007650 }
7651
John McCallfcef3cf2010-12-14 17:51:41 +00007652 case CK_FloatingComplexCast: {
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
Richard Smith357362d2011-12-13 06:39:58 +00007660 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7661 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007662 }
7663
7664 case CK_FloatingComplexToIntegralComplex: {
7665 if (!Visit(E->getSubExpr()))
7666 return false;
7667
7668 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7669 QualType From
7670 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7671 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007672 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7673 To, Result.IntReal) &&
7674 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7675 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007676 }
7677
7678 case CK_IntegralRealToComplex: {
7679 APSInt &Real = Result.IntReal;
7680 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7681 return false;
7682
7683 Result.makeComplexInt();
7684 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7685 return true;
7686 }
7687
7688 case CK_IntegralComplexCast: {
7689 if (!Visit(E->getSubExpr()))
7690 return false;
7691
7692 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7693 QualType From
7694 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7695
Richard Smith911e1422012-01-30 22:27:01 +00007696 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7697 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007698 return true;
7699 }
7700
7701 case CK_IntegralComplexToFloatingComplex: {
7702 if (!Visit(E->getSubExpr()))
7703 return false;
7704
Ted Kremenek28831752012-08-23 20:46:57 +00007705 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007706 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007707 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007708 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007709 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7710 To, Result.FloatReal) &&
7711 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7712 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007713 }
7714 }
7715
7716 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007717}
7718
John McCall93d91dc2010-05-07 17:22:02 +00007719bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007720 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007721 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7722
Richard Smith253c2a32012-01-27 01:14:48 +00007723 bool LHSOK = Visit(E->getLHS());
7724 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007725 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007726
John McCall93d91dc2010-05-07 17:22:02 +00007727 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007728 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007729 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007730
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007731 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7732 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007733 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007734 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007735 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007736 if (Result.isComplexFloat()) {
7737 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7738 APFloat::rmNearestTiesToEven);
7739 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7740 APFloat::rmNearestTiesToEven);
7741 } else {
7742 Result.getComplexIntReal() += RHS.getComplexIntReal();
7743 Result.getComplexIntImag() += RHS.getComplexIntImag();
7744 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007745 break;
John McCalle3027922010-08-25 11:45:40 +00007746 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007747 if (Result.isComplexFloat()) {
7748 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7749 APFloat::rmNearestTiesToEven);
7750 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7751 APFloat::rmNearestTiesToEven);
7752 } else {
7753 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7754 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7755 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007756 break;
John McCalle3027922010-08-25 11:45:40 +00007757 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007758 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007759 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007760 APFloat &LHS_r = LHS.getComplexFloatReal();
7761 APFloat &LHS_i = LHS.getComplexFloatImag();
7762 APFloat &RHS_r = RHS.getComplexFloatReal();
7763 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007764
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007765 APFloat Tmp = LHS_r;
7766 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7767 Result.getComplexFloatReal() = Tmp;
7768 Tmp = LHS_i;
7769 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7770 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7771
7772 Tmp = LHS_r;
7773 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7774 Result.getComplexFloatImag() = Tmp;
7775 Tmp = LHS_i;
7776 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7777 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7778 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007779 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007780 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007781 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7782 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007783 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007784 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7785 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7786 }
7787 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007788 case BO_Div:
7789 if (Result.isComplexFloat()) {
7790 ComplexValue LHS = Result;
7791 APFloat &LHS_r = LHS.getComplexFloatReal();
7792 APFloat &LHS_i = LHS.getComplexFloatImag();
7793 APFloat &RHS_r = RHS.getComplexFloatReal();
7794 APFloat &RHS_i = RHS.getComplexFloatImag();
7795 APFloat &Res_r = Result.getComplexFloatReal();
7796 APFloat &Res_i = Result.getComplexFloatImag();
7797
7798 APFloat Den = RHS_r;
7799 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7800 APFloat Tmp = RHS_i;
7801 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7802 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7803
7804 Res_r = LHS_r;
7805 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7806 Tmp = LHS_i;
7807 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7808 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7809 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7810
7811 Res_i = LHS_i;
7812 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7813 Tmp = LHS_r;
7814 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7815 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7816 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7817 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007818 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7819 return Error(E, diag::note_expr_divide_by_zero);
7820
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007821 ComplexValue LHS = Result;
7822 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7823 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7824 Result.getComplexIntReal() =
7825 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7826 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7827 Result.getComplexIntImag() =
7828 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7829 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7830 }
7831 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007832 }
7833
John McCall93d91dc2010-05-07 17:22:02 +00007834 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007835}
7836
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007837bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7838 // Get the operand value into 'Result'.
7839 if (!Visit(E->getSubExpr()))
7840 return false;
7841
7842 switch (E->getOpcode()) {
7843 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007844 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007845 case UO_Extension:
7846 return true;
7847 case UO_Plus:
7848 // The result is always just the subexpr.
7849 return true;
7850 case UO_Minus:
7851 if (Result.isComplexFloat()) {
7852 Result.getComplexFloatReal().changeSign();
7853 Result.getComplexFloatImag().changeSign();
7854 }
7855 else {
7856 Result.getComplexIntReal() = -Result.getComplexIntReal();
7857 Result.getComplexIntImag() = -Result.getComplexIntImag();
7858 }
7859 return true;
7860 case UO_Not:
7861 if (Result.isComplexFloat())
7862 Result.getComplexFloatImag().changeSign();
7863 else
7864 Result.getComplexIntImag() = -Result.getComplexIntImag();
7865 return true;
7866 }
7867}
7868
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007869bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7870 if (E->getNumInits() == 2) {
7871 if (E->getType()->isComplexType()) {
7872 Result.makeComplexFloat();
7873 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7874 return false;
7875 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7876 return false;
7877 } else {
7878 Result.makeComplexInt();
7879 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7880 return false;
7881 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7882 return false;
7883 }
7884 return true;
7885 }
7886 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7887}
7888
Anders Carlsson537969c2008-11-16 20:27:53 +00007889//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007890// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7891// implicit conversion.
7892//===----------------------------------------------------------------------===//
7893
7894namespace {
7895class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007896 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007897 APValue &Result;
7898public:
7899 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7900 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7901
7902 bool Success(const APValue &V, const Expr *E) {
7903 Result = V;
7904 return true;
7905 }
7906
7907 bool ZeroInitialization(const Expr *E) {
7908 ImplicitValueInitExpr VIE(
7909 E->getType()->castAs<AtomicType>()->getValueType());
7910 return Evaluate(Result, Info, &VIE);
7911 }
7912
7913 bool VisitCastExpr(const CastExpr *E) {
7914 switch (E->getCastKind()) {
7915 default:
7916 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7917 case CK_NonAtomicToAtomic:
7918 return Evaluate(Result, Info, E->getSubExpr());
7919 }
7920 }
7921};
7922} // end anonymous namespace
7923
7924static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7925 assert(E->isRValue() && E->getType()->isAtomicType());
7926 return AtomicExprEvaluator(Info, Result).Visit(E);
7927}
7928
7929//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007930// Void expression evaluation, primarily for a cast to void on the LHS of a
7931// comma operator
7932//===----------------------------------------------------------------------===//
7933
7934namespace {
7935class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007936 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007937public:
7938 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7939
Richard Smith2e312c82012-03-03 22:46:17 +00007940 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007941
7942 bool VisitCastExpr(const CastExpr *E) {
7943 switch (E->getCastKind()) {
7944 default:
7945 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7946 case CK_ToVoid:
7947 VisitIgnoredValue(E->getSubExpr());
7948 return true;
7949 }
7950 }
7951};
7952} // end anonymous namespace
7953
7954static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7955 assert(E->isRValue() && E->getType()->isVoidType());
7956 return VoidExprEvaluator(Info).Visit(E);
7957}
7958
7959//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007960// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007961//===----------------------------------------------------------------------===//
7962
Richard Smith2e312c82012-03-03 22:46:17 +00007963static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007964 // In C, function designators are not lvalues, but we evaluate them as if they
7965 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007966 QualType T = E->getType();
7967 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007968 LValue LV;
7969 if (!EvaluateLValue(E, LV, Info))
7970 return false;
7971 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007972 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007973 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007974 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007975 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007976 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007977 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007978 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007979 LValue LV;
7980 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007981 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007982 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007983 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007984 llvm::APFloat F(0.0);
7985 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007986 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007987 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007988 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007989 ComplexValue C;
7990 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007991 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007992 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007993 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007994 MemberPtr P;
7995 if (!EvaluateMemberPointer(E, P, Info))
7996 return false;
7997 P.moveInto(Result);
7998 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007999 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008000 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008001 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008002 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8003 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008004 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008005 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008006 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008007 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008008 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008009 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8010 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008011 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008012 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008013 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008014 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008015 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008016 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008017 if (!EvaluateVoid(E, Info))
8018 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008019 } else if (T->isAtomicType()) {
8020 if (!EvaluateAtomic(E, Result, Info))
8021 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008022 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008023 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008024 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008025 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008026 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008027 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008028 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008029
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008030 return true;
8031}
8032
Richard Smithb228a862012-02-15 02:18:13 +00008033/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8034/// cases, the in-place evaluation is essential, since later initializers for
8035/// an object can indirectly refer to subobjects which were initialized earlier.
8036static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008037 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008038 assert(!E->isValueDependent());
8039
Richard Smith7525ff62013-05-09 07:14:00 +00008040 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008041 return false;
8042
8043 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008044 // Evaluate arrays and record types in-place, so that later initializers can
8045 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008046 if (E->getType()->isArrayType())
8047 return EvaluateArray(E, This, Result, Info);
8048 else if (E->getType()->isRecordType())
8049 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008050 }
8051
8052 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008053 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008054}
8055
Richard Smithf57d8cb2011-12-09 22:58:01 +00008056/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8057/// lvalue-to-rvalue cast if it is an lvalue.
8058static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008059 if (E->getType().isNull())
8060 return false;
8061
Richard Smithfddd3842011-12-30 21:15:51 +00008062 if (!CheckLiteralType(Info, E))
8063 return false;
8064
Richard Smith2e312c82012-03-03 22:46:17 +00008065 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008066 return false;
8067
8068 if (E->isGLValue()) {
8069 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008070 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008071 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008072 return false;
8073 }
8074
Richard Smith2e312c82012-03-03 22:46:17 +00008075 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008076 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008077}
Richard Smith11562c52011-10-28 17:51:58 +00008078
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008079static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8080 const ASTContext &Ctx, bool &IsConst) {
8081 // Fast-path evaluations of integer literals, since we sometimes see files
8082 // containing vast quantities of these.
8083 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8084 Result.Val = APValue(APSInt(L->getValue(),
8085 L->getType()->isUnsignedIntegerType()));
8086 IsConst = true;
8087 return true;
8088 }
James Dennett0492ef02014-03-14 17:44:10 +00008089
8090 // This case should be rare, but we need to check it before we check on
8091 // the type below.
8092 if (Exp->getType().isNull()) {
8093 IsConst = false;
8094 return true;
8095 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008096
8097 // FIXME: Evaluating values of large array and record types can cause
8098 // performance problems. Only do so in C++11 for now.
8099 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8100 Exp->getType()->isRecordType()) &&
8101 !Ctx.getLangOpts().CPlusPlus11) {
8102 IsConst = false;
8103 return true;
8104 }
8105 return false;
8106}
8107
8108
Richard Smith7b553f12011-10-29 00:50:52 +00008109/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008110/// any crazy technique (that has nothing to do with language standards) that
8111/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008112/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8113/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008114bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008115 bool IsConst;
8116 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8117 return IsConst;
8118
Richard Smith6d4c6582013-11-05 22:18:15 +00008119 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008120 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008121}
8122
Jay Foad39c79802011-01-12 09:06:06 +00008123bool Expr::EvaluateAsBooleanCondition(bool &Result,
8124 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008125 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008126 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008127 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008128}
8129
Richard Smith5fab0c92011-12-28 19:48:30 +00008130bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8131 SideEffectsKind AllowSideEffects) const {
8132 if (!getType()->isIntegralOrEnumerationType())
8133 return false;
8134
Richard Smith11562c52011-10-28 17:51:58 +00008135 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008136 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8137 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008138 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008139
Richard Smith11562c52011-10-28 17:51:58 +00008140 Result = ExprResult.Val.getInt();
8141 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008142}
8143
Jay Foad39c79802011-01-12 09:06:06 +00008144bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008145 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008146
John McCall45d55e42010-05-07 21:00:08 +00008147 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008148 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8149 !CheckLValueConstantExpression(Info, getExprLoc(),
8150 Ctx.getLValueReferenceType(getType()), LV))
8151 return false;
8152
Richard Smith2e312c82012-03-03 22:46:17 +00008153 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008154 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008155}
8156
Richard Smithd0b4dd62011-12-19 06:19:21 +00008157bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8158 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008159 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008160 // FIXME: Evaluating initializers for large array and record types can cause
8161 // performance problems. Only do so in C++11 for now.
8162 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008163 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008164 return false;
8165
Richard Smithd0b4dd62011-12-19 06:19:21 +00008166 Expr::EvalStatus EStatus;
8167 EStatus.Diag = &Notes;
8168
Richard Smith6d4c6582013-11-05 22:18:15 +00008169 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008170 InitInfo.setEvaluatingDecl(VD, Value);
8171
8172 LValue LVal;
8173 LVal.set(VD);
8174
Richard Smithfddd3842011-12-30 21:15:51 +00008175 // C++11 [basic.start.init]p2:
8176 // Variables with static storage duration or thread storage duration shall be
8177 // zero-initialized before any other initialization takes place.
8178 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008179 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008180 !VD->getType()->isReferenceType()) {
8181 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008182 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008183 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008184 return false;
8185 }
8186
Richard Smith7525ff62013-05-09 07:14:00 +00008187 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8188 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008189 EStatus.HasSideEffects)
8190 return false;
8191
8192 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8193 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008194}
8195
Richard Smith7b553f12011-10-29 00:50:52 +00008196/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8197/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008198bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008199 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008200 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008201}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008202
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008203APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008204 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008205 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008206 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008207 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008208 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008209 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008210 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008211
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008212 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008213}
John McCall864e3962010-05-07 05:32:02 +00008214
Richard Smithe9ff7702013-11-05 22:23:30 +00008215void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008216 bool IsConst;
8217 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008218 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008219 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008220 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8221 }
8222}
8223
Richard Smithe6c01442013-06-05 00:46:14 +00008224bool Expr::EvalResult::isGlobalLValue() const {
8225 assert(Val.isLValue());
8226 return IsGlobalLValue(Val.getLValueBase());
8227}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008228
8229
John McCall864e3962010-05-07 05:32:02 +00008230/// isIntegerConstantExpr - this recursive routine will test if an expression is
8231/// an integer constant expression.
8232
8233/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8234/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008235
8236// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008237// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8238// and a (possibly null) SourceLocation indicating the location of the problem.
8239//
John McCall864e3962010-05-07 05:32:02 +00008240// Note that to reduce code duplication, this helper does no evaluation
8241// itself; the caller checks whether the expression is evaluatable, and
8242// in the rare cases where CheckICE actually cares about the evaluated
8243// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008244
Dan Gohman28ade552010-07-26 21:25:24 +00008245namespace {
8246
Richard Smith9e575da2012-12-28 13:25:52 +00008247enum ICEKind {
8248 /// This expression is an ICE.
8249 IK_ICE,
8250 /// This expression is not an ICE, but if it isn't evaluated, it's
8251 /// a legal subexpression for an ICE. This return value is used to handle
8252 /// the comma operator in C99 mode, and non-constant subexpressions.
8253 IK_ICEIfUnevaluated,
8254 /// This expression is not an ICE, and is not a legal subexpression for one.
8255 IK_NotICE
8256};
8257
John McCall864e3962010-05-07 05:32:02 +00008258struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008259 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008260 SourceLocation Loc;
8261
Richard Smith9e575da2012-12-28 13:25:52 +00008262 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008263};
8264
Dan Gohman28ade552010-07-26 21:25:24 +00008265}
8266
Richard Smith9e575da2012-12-28 13:25:52 +00008267static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8268
8269static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008270
Craig Toppera31a8822013-08-22 07:09:37 +00008271static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008272 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008273 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008274 !EVResult.Val.isInt())
8275 return ICEDiag(IK_NotICE, E->getLocStart());
8276
John McCall864e3962010-05-07 05:32:02 +00008277 return NoDiag();
8278}
8279
Craig Toppera31a8822013-08-22 07:09:37 +00008280static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008281 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008282 if (!E->getType()->isIntegralOrEnumerationType())
8283 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008284
8285 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008286#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008287#define STMT(Node, Base) case Expr::Node##Class:
8288#define EXPR(Node, Base)
8289#include "clang/AST/StmtNodes.inc"
8290 case Expr::PredefinedExprClass:
8291 case Expr::FloatingLiteralClass:
8292 case Expr::ImaginaryLiteralClass:
8293 case Expr::StringLiteralClass:
8294 case Expr::ArraySubscriptExprClass:
8295 case Expr::MemberExprClass:
8296 case Expr::CompoundAssignOperatorClass:
8297 case Expr::CompoundLiteralExprClass:
8298 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008299 case Expr::DesignatedInitExprClass:
8300 case Expr::ImplicitValueInitExprClass:
8301 case Expr::ParenListExprClass:
8302 case Expr::VAArgExprClass:
8303 case Expr::AddrLabelExprClass:
8304 case Expr::StmtExprClass:
8305 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008306 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008307 case Expr::CXXDynamicCastExprClass:
8308 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008309 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008310 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008311 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008312 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008313 case Expr::CXXThisExprClass:
8314 case Expr::CXXThrowExprClass:
8315 case Expr::CXXNewExprClass:
8316 case Expr::CXXDeleteExprClass:
8317 case Expr::CXXPseudoDestructorExprClass:
8318 case Expr::UnresolvedLookupExprClass:
8319 case Expr::DependentScopeDeclRefExprClass:
8320 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008321 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008322 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008323 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008324 case Expr::CXXTemporaryObjectExprClass:
8325 case Expr::CXXUnresolvedConstructExprClass:
8326 case Expr::CXXDependentScopeMemberExprClass:
8327 case Expr::UnresolvedMemberExprClass:
8328 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008329 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008330 case Expr::ObjCArrayLiteralClass:
8331 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008332 case Expr::ObjCEncodeExprClass:
8333 case Expr::ObjCMessageExprClass:
8334 case Expr::ObjCSelectorExprClass:
8335 case Expr::ObjCProtocolExprClass:
8336 case Expr::ObjCIvarRefExprClass:
8337 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008338 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008339 case Expr::ObjCIsaExprClass:
8340 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008341 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008342 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008343 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008344 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008345 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008346 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008347 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008348 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008349 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008350 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008351 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008352 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008353 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008354 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008355
Richard Smithf137f932014-01-25 20:50:08 +00008356 case Expr::InitListExprClass: {
8357 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8358 // form "T x = { a };" is equivalent to "T x = a;".
8359 // Unless we're initializing a reference, T is a scalar as it is known to be
8360 // of integral or enumeration type.
8361 if (E->isRValue())
8362 if (cast<InitListExpr>(E)->getNumInits() == 1)
8363 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8364 return ICEDiag(IK_NotICE, E->getLocStart());
8365 }
8366
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008367 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008368 case Expr::GNUNullExprClass:
8369 // GCC considers the GNU __null value to be an integral constant expression.
8370 return NoDiag();
8371
John McCall7c454bb2011-07-15 05:09:51 +00008372 case Expr::SubstNonTypeTemplateParmExprClass:
8373 return
8374 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8375
John McCall864e3962010-05-07 05:32:02 +00008376 case Expr::ParenExprClass:
8377 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008378 case Expr::GenericSelectionExprClass:
8379 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008380 case Expr::IntegerLiteralClass:
8381 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008382 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008383 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008384 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008385 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008386 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008387 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008388 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008389 return NoDiag();
8390 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008391 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008392 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8393 // constant expressions, but they can never be ICEs because an ICE cannot
8394 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008395 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008396 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008397 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008398 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008399 }
Richard Smith6365c912012-02-24 22:12:32 +00008400 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008401 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8402 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008403 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008404 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008405 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008406 // Parameter variables are never constants. Without this check,
8407 // getAnyInitializer() can find a default argument, which leads
8408 // to chaos.
8409 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008410 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008411
8412 // C++ 7.1.5.1p2
8413 // A variable of non-volatile const-qualified integral or enumeration
8414 // type initialized by an ICE can be used in ICEs.
8415 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008416 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008417 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008418
Richard Smithd0b4dd62011-12-19 06:19:21 +00008419 const VarDecl *VD;
8420 // Look for a declaration of this variable that has an initializer, and
8421 // check whether it is an ICE.
8422 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8423 return NoDiag();
8424 else
Richard Smith9e575da2012-12-28 13:25:52 +00008425 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008426 }
8427 }
Richard Smith9e575da2012-12-28 13:25:52 +00008428 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008429 }
John McCall864e3962010-05-07 05:32:02 +00008430 case Expr::UnaryOperatorClass: {
8431 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8432 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008433 case UO_PostInc:
8434 case UO_PostDec:
8435 case UO_PreInc:
8436 case UO_PreDec:
8437 case UO_AddrOf:
8438 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008439 // C99 6.6/3 allows increment and decrement within unevaluated
8440 // subexpressions of constant expressions, but they can never be ICEs
8441 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008442 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008443 case UO_Extension:
8444 case UO_LNot:
8445 case UO_Plus:
8446 case UO_Minus:
8447 case UO_Not:
8448 case UO_Real:
8449 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008450 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008451 }
Richard Smith9e575da2012-12-28 13:25:52 +00008452
John McCall864e3962010-05-07 05:32:02 +00008453 // OffsetOf falls through here.
8454 }
8455 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008456 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8457 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8458 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8459 // compliance: we should warn earlier for offsetof expressions with
8460 // array subscripts that aren't ICEs, and if the array subscripts
8461 // are ICEs, the value of the offsetof must be an integer constant.
8462 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008463 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008464 case Expr::UnaryExprOrTypeTraitExprClass: {
8465 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8466 if ((Exp->getKind() == UETT_SizeOf) &&
8467 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008468 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008469 return NoDiag();
8470 }
8471 case Expr::BinaryOperatorClass: {
8472 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8473 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008474 case BO_PtrMemD:
8475 case BO_PtrMemI:
8476 case BO_Assign:
8477 case BO_MulAssign:
8478 case BO_DivAssign:
8479 case BO_RemAssign:
8480 case BO_AddAssign:
8481 case BO_SubAssign:
8482 case BO_ShlAssign:
8483 case BO_ShrAssign:
8484 case BO_AndAssign:
8485 case BO_XorAssign:
8486 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008487 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8488 // constant expressions, but they can never be ICEs because an ICE cannot
8489 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008490 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008491
John McCalle3027922010-08-25 11:45:40 +00008492 case BO_Mul:
8493 case BO_Div:
8494 case BO_Rem:
8495 case BO_Add:
8496 case BO_Sub:
8497 case BO_Shl:
8498 case BO_Shr:
8499 case BO_LT:
8500 case BO_GT:
8501 case BO_LE:
8502 case BO_GE:
8503 case BO_EQ:
8504 case BO_NE:
8505 case BO_And:
8506 case BO_Xor:
8507 case BO_Or:
8508 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008509 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8510 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008511 if (Exp->getOpcode() == BO_Div ||
8512 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008513 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008514 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008515 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008516 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008517 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008518 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008519 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008520 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008521 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008522 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008523 }
8524 }
8525 }
John McCalle3027922010-08-25 11:45:40 +00008526 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008527 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008528 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8529 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008530 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8531 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008532 } else {
8533 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008534 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008535 }
8536 }
Richard Smith9e575da2012-12-28 13:25:52 +00008537 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008538 }
John McCalle3027922010-08-25 11:45:40 +00008539 case BO_LAnd:
8540 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008541 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8542 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008543 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008544 // Rare case where the RHS has a comma "side-effect"; we need
8545 // to actually check the condition to see whether the side
8546 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008547 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008548 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008549 return RHSResult;
8550 return NoDiag();
8551 }
8552
Richard Smith9e575da2012-12-28 13:25:52 +00008553 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008554 }
8555 }
8556 }
8557 case Expr::ImplicitCastExprClass:
8558 case Expr::CStyleCastExprClass:
8559 case Expr::CXXFunctionalCastExprClass:
8560 case Expr::CXXStaticCastExprClass:
8561 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008562 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008563 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008564 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008565 if (isa<ExplicitCastExpr>(E)) {
8566 if (const FloatingLiteral *FL
8567 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8568 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8569 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8570 APSInt IgnoredVal(DestWidth, !DestSigned);
8571 bool Ignored;
8572 // If the value does not fit in the destination type, the behavior is
8573 // undefined, so we are not required to treat it as a constant
8574 // expression.
8575 if (FL->getValue().convertToInteger(IgnoredVal,
8576 llvm::APFloat::rmTowardZero,
8577 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008578 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008579 return NoDiag();
8580 }
8581 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008582 switch (cast<CastExpr>(E)->getCastKind()) {
8583 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008584 case CK_AtomicToNonAtomic:
8585 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008586 case CK_NoOp:
8587 case CK_IntegralToBoolean:
8588 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008589 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008590 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008591 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008592 }
John McCall864e3962010-05-07 05:32:02 +00008593 }
John McCallc07a0c72011-02-17 10:25:35 +00008594 case Expr::BinaryConditionalOperatorClass: {
8595 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8596 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008597 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008598 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008599 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8600 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8601 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008602 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008603 return FalseResult;
8604 }
John McCall864e3962010-05-07 05:32:02 +00008605 case Expr::ConditionalOperatorClass: {
8606 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8607 // If the condition (ignoring parens) is a __builtin_constant_p call,
8608 // then only the true side is actually considered in an integer constant
8609 // expression, and it is fully evaluated. This is an important GNU
8610 // extension. See GCC PR38377 for discussion.
8611 if (const CallExpr *CallCE
8612 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008613 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008614 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008615 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008616 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008617 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008618
Richard Smithf57d8cb2011-12-09 22:58:01 +00008619 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8620 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008621
Richard Smith9e575da2012-12-28 13:25:52 +00008622 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008623 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008624 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008625 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008626 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008627 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008628 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008629 return NoDiag();
8630 // Rare case where the diagnostics depend on which side is evaluated
8631 // Note that if we get here, CondResult is 0, and at least one of
8632 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008633 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008634 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008635 return TrueResult;
8636 }
8637 case Expr::CXXDefaultArgExprClass:
8638 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008639 case Expr::CXXDefaultInitExprClass:
8640 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008641 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008642 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008643 }
8644 }
8645
David Blaikiee4d798f2012-01-20 21:50:17 +00008646 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008647}
8648
Richard Smithf57d8cb2011-12-09 22:58:01 +00008649/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008650static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008651 const Expr *E,
8652 llvm::APSInt *Value,
8653 SourceLocation *Loc) {
8654 if (!E->getType()->isIntegralOrEnumerationType()) {
8655 if (Loc) *Loc = E->getExprLoc();
8656 return false;
8657 }
8658
Richard Smith66e05fe2012-01-18 05:21:49 +00008659 APValue Result;
8660 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008661 return false;
8662
Richard Smith66e05fe2012-01-18 05:21:49 +00008663 assert(Result.isInt() && "pointer cast to int is not an ICE");
8664 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008665 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008666}
8667
Craig Toppera31a8822013-08-22 07:09:37 +00008668bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8669 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008670 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008671 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008672
Richard Smith9e575da2012-12-28 13:25:52 +00008673 ICEDiag D = CheckICE(this, Ctx);
8674 if (D.Kind != IK_ICE) {
8675 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008676 return false;
8677 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008678 return true;
8679}
8680
Craig Toppera31a8822013-08-22 07:09:37 +00008681bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008682 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008683 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008684 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8685
8686 if (!isIntegerConstantExpr(Ctx, Loc))
8687 return false;
8688 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008689 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008690 return true;
8691}
Richard Smith66e05fe2012-01-18 05:21:49 +00008692
Craig Toppera31a8822013-08-22 07:09:37 +00008693bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008694 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008695}
8696
Craig Toppera31a8822013-08-22 07:09:37 +00008697bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008698 SourceLocation *Loc) const {
8699 // We support this checking in C++98 mode in order to diagnose compatibility
8700 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008701 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008702
Richard Smith98a0a492012-02-14 21:38:30 +00008703 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008704 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008705 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008706 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008707 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008708
8709 APValue Scratch;
8710 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8711
8712 if (!Diags.empty()) {
8713 IsConstExpr = false;
8714 if (Loc) *Loc = Diags[0].first;
8715 } else if (!IsConstExpr) {
8716 // FIXME: This shouldn't happen.
8717 if (Loc) *Loc = getExprLoc();
8718 }
8719
8720 return IsConstExpr;
8721}
Richard Smith253c2a32012-01-27 01:14:48 +00008722
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008723bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8724 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00008725 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008726 Expr::EvalStatus Status;
8727 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8728
8729 ArgVector ArgValues(Args.size());
8730 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8731 I != E; ++I) {
8732 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8733 // If evaluation fails, throw away the argument entirely.
8734 ArgValues[I - Args.begin()] = APValue();
8735 if (Info.EvalStatus.HasSideEffects)
8736 return false;
8737 }
8738
8739 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00008740 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008741 ArgValues.data());
8742 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8743}
8744
Richard Smith253c2a32012-01-27 01:14:48 +00008745bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008746 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008747 PartialDiagnosticAt> &Diags) {
8748 // FIXME: It would be useful to check constexpr function templates, but at the
8749 // moment the constant expression evaluator cannot cope with the non-rigorous
8750 // ASTs which we build for dependent expressions.
8751 if (FD->isDependentContext())
8752 return true;
8753
8754 Expr::EvalStatus Status;
8755 Status.Diag = &Diags;
8756
Richard Smith6d4c6582013-11-05 22:18:15 +00008757 EvalInfo Info(FD->getASTContext(), Status,
8758 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008759
8760 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00008761 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00008762
Richard Smith7525ff62013-05-09 07:14:00 +00008763 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008764 // is a temporary being used as the 'this' pointer.
8765 LValue This;
8766 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008767 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008768
Richard Smith253c2a32012-01-27 01:14:48 +00008769 ArrayRef<const Expr*> Args;
8770
8771 SourceLocation Loc = FD->getLocation();
8772
Richard Smith2e312c82012-03-03 22:46:17 +00008773 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008774 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8775 // Evaluate the call as a constant initializer, to allow the construction
8776 // of objects of non-literal types.
8777 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008778 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008779 } else
Craig Topper36250ad2014-05-12 05:36:57 +00008780 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00008781 Args, FD->getBody(), Info, Scratch);
8782
8783 return Diags.empty();
8784}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008785
8786bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8787 const FunctionDecl *FD,
8788 SmallVectorImpl<
8789 PartialDiagnosticAt> &Diags) {
8790 Expr::EvalStatus Status;
8791 Status.Diag = &Diags;
8792
8793 EvalInfo Info(FD->getASTContext(), Status,
8794 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8795
8796 // Fabricate a call stack frame to give the arguments a plausible cover story.
8797 ArrayRef<const Expr*> Args;
8798 ArgVector ArgValues(0);
8799 bool Success = EvaluateArgs(Args, ArgValues, Info);
8800 (void)Success;
8801 assert(Success &&
8802 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00008803 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008804
8805 APValue ResultScratch;
8806 Evaluate(ResultScratch, Info, E);
8807 return Diags.empty();
8808}