blob: 3e8a0d0dc14d845e50696de06464031d3e6742ef [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 Smith22a5d612014-07-07 06:00:13 +00004669 if (!Info.CurrentCall->This) {
4670 if (Info.getLangOpts().CPlusPlus11)
4671 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4672 else
4673 Info.Diag(E);
4674 return false;
4675 }
Richard Smithd62306a2011-11-10 06:34:14 +00004676 Result = *Info.CurrentCall->This;
4677 return true;
4678 }
John McCallc07a0c72011-02-17 10:25:35 +00004679
Eli Friedman449fe542009-03-23 04:56:01 +00004680 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004681};
Chris Lattner05706e882008-07-11 18:11:29 +00004682} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004683
John McCall45d55e42010-05-07 21:00:08 +00004684static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004685 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004686 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004687}
4688
John McCall45d55e42010-05-07 21:00:08 +00004689bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004690 if (E->getOpcode() != BO_Add &&
4691 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004692 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004693
Chris Lattner05706e882008-07-11 18:11:29 +00004694 const Expr *PExp = E->getLHS();
4695 const Expr *IExp = E->getRHS();
4696 if (IExp->getType()->isPointerType())
4697 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004698
Richard Smith253c2a32012-01-27 01:14:48 +00004699 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4700 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004701 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004702
John McCall45d55e42010-05-07 21:00:08 +00004703 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004704 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004705 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004706
4707 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004708 if (E->getOpcode() == BO_Sub)
4709 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004710
Ted Kremenek28831752012-08-23 20:46:57 +00004711 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004712 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4713 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004714}
Eli Friedman9a156e52008-11-12 09:44:48 +00004715
John McCall45d55e42010-05-07 21:00:08 +00004716bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4717 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004718}
Mike Stump11289f42009-09-09 15:08:12 +00004719
Peter Collingbournee9200682011-05-13 03:29:01 +00004720bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4721 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004722
Eli Friedman847a2bc2009-12-27 05:43:15 +00004723 switch (E->getCastKind()) {
4724 default:
4725 break;
4726
John McCalle3027922010-08-25 11:45:40 +00004727 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004728 case CK_CPointerToObjCPointerCast:
4729 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004730 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004731 if (!Visit(SubExpr))
4732 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004733 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4734 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4735 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004736 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004737 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004738 if (SubExpr->getType()->isVoidPointerType())
4739 CCEDiag(E, diag::note_constexpr_invalid_cast)
4740 << 3 << SubExpr->getType();
4741 else
4742 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4743 }
Richard Smith96e0c102011-11-04 02:25:55 +00004744 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004745
Anders Carlsson18275092010-10-31 20:41:46 +00004746 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004747 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004748 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004749 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004750 if (!Result.Base && Result.Offset.isZero())
4751 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004752
Richard Smithd62306a2011-11-10 06:34:14 +00004753 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004754 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004755 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4756 castAs<PointerType>()->getPointeeType(),
4757 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004758
Richard Smith027bf112011-11-17 22:56:20 +00004759 case CK_BaseToDerived:
4760 if (!Visit(E->getSubExpr()))
4761 return false;
4762 if (!Result.Base && Result.Offset.isZero())
4763 return true;
4764 return HandleBaseToDerivedCast(Info, E, Result);
4765
Richard Smith0b0a0b62011-10-29 20:57:55 +00004766 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004767 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004768 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004769
John McCalle3027922010-08-25 11:45:40 +00004770 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004771 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4772
Richard Smith2e312c82012-03-03 22:46:17 +00004773 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004774 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004775 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004776
John McCall45d55e42010-05-07 21:00:08 +00004777 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004778 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4779 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004780 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004781 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004782 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004783 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004784 return true;
4785 } else {
4786 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004787 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004788 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004789 }
4790 }
John McCalle3027922010-08-25 11:45:40 +00004791 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004792 if (SubExpr->isGLValue()) {
4793 if (!EvaluateLValue(SubExpr, Result, Info))
4794 return false;
4795 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004796 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004797 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004798 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004799 return false;
4800 }
Richard Smith96e0c102011-11-04 02:25:55 +00004801 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004802 if (const ConstantArrayType *CAT
4803 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4804 Result.addArray(Info, E, CAT);
4805 else
4806 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004807 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004808
John McCalle3027922010-08-25 11:45:40 +00004809 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004810 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004811 }
4812
Richard Smith11562c52011-10-28 17:51:58 +00004813 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004814}
Chris Lattner05706e882008-07-11 18:11:29 +00004815
Peter Collingbournee9200682011-05-13 03:29:01 +00004816bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004817 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004818 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004819
Alp Tokera724cff2013-12-28 21:59:02 +00004820 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004821 case Builtin::BI__builtin_addressof:
4822 return EvaluateLValue(E->getArg(0), Result, Info);
4823
4824 default:
4825 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4826 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004827}
Chris Lattner05706e882008-07-11 18:11:29 +00004828
4829//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004830// Member Pointer Evaluation
4831//===----------------------------------------------------------------------===//
4832
4833namespace {
4834class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004836 MemberPtr &Result;
4837
4838 bool Success(const ValueDecl *D) {
4839 Result = MemberPtr(D);
4840 return true;
4841 }
4842public:
4843
4844 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4845 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4846
Richard Smith2e312c82012-03-03 22:46:17 +00004847 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004848 Result.setFrom(V);
4849 return true;
4850 }
Richard Smithfddd3842011-12-30 21:15:51 +00004851 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004852 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00004853 }
4854
4855 bool VisitCastExpr(const CastExpr *E);
4856 bool VisitUnaryAddrOf(const UnaryOperator *E);
4857};
4858} // end anonymous namespace
4859
4860static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4861 EvalInfo &Info) {
4862 assert(E->isRValue() && E->getType()->isMemberPointerType());
4863 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4864}
4865
4866bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4867 switch (E->getCastKind()) {
4868 default:
4869 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4870
4871 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004872 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004873 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004874
4875 case CK_BaseToDerivedMemberPointer: {
4876 if (!Visit(E->getSubExpr()))
4877 return false;
4878 if (E->path_empty())
4879 return true;
4880 // Base-to-derived member pointer casts store the path in derived-to-base
4881 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4882 // the wrong end of the derived->base arc, so stagger the path by one class.
4883 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4884 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4885 PathI != PathE; ++PathI) {
4886 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4887 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4888 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004889 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004890 }
4891 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4892 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004893 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004894 return true;
4895 }
4896
4897 case CK_DerivedToBaseMemberPointer:
4898 if (!Visit(E->getSubExpr()))
4899 return false;
4900 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4901 PathE = E->path_end(); PathI != PathE; ++PathI) {
4902 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4903 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4904 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004905 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004906 }
4907 return true;
4908 }
4909}
4910
4911bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4912 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4913 // member can be formed.
4914 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4915}
4916
4917//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004918// Record Evaluation
4919//===----------------------------------------------------------------------===//
4920
4921namespace {
4922 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004923 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004924 const LValue &This;
4925 APValue &Result;
4926 public:
4927
4928 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4929 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4930
Richard Smith2e312c82012-03-03 22:46:17 +00004931 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004932 Result = V;
4933 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004934 }
Richard Smithfddd3842011-12-30 21:15:51 +00004935 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004936
Richard Smithe97cbd72011-11-11 04:05:33 +00004937 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004938 bool VisitInitListExpr(const InitListExpr *E);
4939 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004940 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004941 };
4942}
4943
Richard Smithfddd3842011-12-30 21:15:51 +00004944/// Perform zero-initialization on an object of non-union class type.
4945/// C++11 [dcl.init]p5:
4946/// To zero-initialize an object or reference of type T means:
4947/// [...]
4948/// -- if T is a (possibly cv-qualified) non-union class type,
4949/// each non-static data member and each base-class subobject is
4950/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004951static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4952 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004953 const LValue &This, APValue &Result) {
4954 assert(!RD->isUnion() && "Expected non-union class type");
4955 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4956 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00004957 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00004958
John McCalld7bca762012-05-01 00:38:49 +00004959 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004960 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4961
4962 if (CD) {
4963 unsigned Index = 0;
4964 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004965 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004966 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4967 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004968 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4969 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004970 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004971 Result.getStructBase(Index)))
4972 return false;
4973 }
4974 }
4975
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004976 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00004977 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004978 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004979 continue;
4980
4981 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004982 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004983 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004984
David Blaikie2d7c57e2012-04-30 02:36:29 +00004985 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004986 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004987 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004988 return false;
4989 }
4990
4991 return true;
4992}
4993
4994bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4995 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004996 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004997 if (RD->isUnion()) {
4998 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4999 // object's first non-static named data member is zero-initialized
5000 RecordDecl::field_iterator I = RD->field_begin();
5001 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005002 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005003 return true;
5004 }
5005
5006 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005007 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005008 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005009 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005010 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005011 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005012 }
5013
Richard Smith5d108602012-02-17 00:44:16 +00005014 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005015 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005016 return false;
5017 }
5018
Richard Smitha8105bc2012-01-06 16:39:00 +00005019 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005020}
5021
Richard Smithe97cbd72011-11-11 04:05:33 +00005022bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5023 switch (E->getCastKind()) {
5024 default:
5025 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5026
5027 case CK_ConstructorConversion:
5028 return Visit(E->getSubExpr());
5029
5030 case CK_DerivedToBase:
5031 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005032 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005033 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005034 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005035 if (!DerivedObject.isStruct())
5036 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005037
5038 // Derived-to-base rvalue conversion: just slice off the derived part.
5039 APValue *Value = &DerivedObject;
5040 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5041 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5042 PathE = E->path_end(); PathI != PathE; ++PathI) {
5043 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5044 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5045 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5046 RD = Base;
5047 }
5048 Result = *Value;
5049 return true;
5050 }
5051 }
5052}
5053
Richard Smithd62306a2011-11-10 06:34:14 +00005054bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5055 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005056 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005057 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5058
5059 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005060 const FieldDecl *Field = E->getInitializedFieldInUnion();
5061 Result = APValue(Field);
5062 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005063 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005064
5065 // If the initializer list for a union does not contain any elements, the
5066 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005067 // FIXME: The element should be initialized from an initializer list.
5068 // Is this difference ever observable for initializer lists which
5069 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005070 ImplicitValueInitExpr VIE(Field->getType());
5071 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5072
Richard Smithd62306a2011-11-10 06:34:14 +00005073 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005074 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5075 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005076
5077 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5078 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5079 isa<CXXDefaultInitExpr>(InitExpr));
5080
Richard Smithb228a862012-02-15 02:18:13 +00005081 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005082 }
5083
5084 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5085 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005086 Result = APValue(APValue::UninitStruct(), 0,
5087 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005088 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005089 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005090 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005091 // Anonymous bit-fields are not considered members of the class for
5092 // purposes of aggregate initialization.
5093 if (Field->isUnnamedBitfield())
5094 continue;
5095
5096 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005097
Richard Smith253c2a32012-01-27 01:14:48 +00005098 bool HaveInit = ElementNo < E->getNumInits();
5099
5100 // FIXME: Diagnostics here should point to the end of the initializer
5101 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005102 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005103 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005104 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005105
5106 // Perform an implicit value-initialization for members beyond the end of
5107 // the initializer list.
5108 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005109 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005110
Richard Smith852c9db2013-04-20 22:23:05 +00005111 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5112 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5113 isa<CXXDefaultInitExpr>(Init));
5114
Richard Smith49ca8aa2013-08-06 07:09:20 +00005115 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5116 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5117 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005118 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005119 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005120 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005121 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005122 }
5123 }
5124
Richard Smith253c2a32012-01-27 01:14:48 +00005125 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005126}
5127
5128bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5129 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005130 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5131
Richard Smithfddd3842011-12-30 21:15:51 +00005132 bool ZeroInit = E->requiresZeroInitialization();
5133 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005134 // If we've already performed zero-initialization, we're already done.
5135 if (!Result.isUninit())
5136 return true;
5137
Richard Smithda3f4fd2014-03-05 23:32:50 +00005138 // We can get here in two different ways:
5139 // 1) We're performing value-initialization, and should zero-initialize
5140 // the object, or
5141 // 2) We're performing default-initialization of an object with a trivial
5142 // constexpr default constructor, in which case we should start the
5143 // lifetimes of all the base subobjects (there can be no data member
5144 // subobjects in this case) per [basic.life]p1.
5145 // Either way, ZeroInitialization is appropriate.
5146 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005147 }
5148
Craig Topper36250ad2014-05-12 05:36:57 +00005149 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005150 FD->getBody(Definition);
5151
Richard Smith357362d2011-12-13 06:39:58 +00005152 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5153 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005154
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005155 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005156 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005157 if (const MaterializeTemporaryExpr *ME
5158 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5159 return Visit(ME->GetTemporaryExpr());
5160
Richard Smithfddd3842011-12-30 21:15:51 +00005161 if (ZeroInit && !ZeroInitialization(E))
5162 return false;
5163
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005164 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005165 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005166 cast<CXXConstructorDecl>(Definition), Info,
5167 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005168}
5169
Richard Smithcc1b96d2013-06-12 22:31:48 +00005170bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5171 const CXXStdInitializerListExpr *E) {
5172 const ConstantArrayType *ArrayType =
5173 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5174
5175 LValue Array;
5176 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5177 return false;
5178
5179 // Get a pointer to the first element of the array.
5180 Array.addArray(Info, E, ArrayType);
5181
5182 // FIXME: Perform the checks on the field types in SemaInit.
5183 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5184 RecordDecl::field_iterator Field = Record->field_begin();
5185 if (Field == Record->field_end())
5186 return Error(E);
5187
5188 // Start pointer.
5189 if (!Field->getType()->isPointerType() ||
5190 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5191 ArrayType->getElementType()))
5192 return Error(E);
5193
5194 // FIXME: What if the initializer_list type has base classes, etc?
5195 Result = APValue(APValue::UninitStruct(), 0, 2);
5196 Array.moveInto(Result.getStructField(0));
5197
5198 if (++Field == Record->field_end())
5199 return Error(E);
5200
5201 if (Field->getType()->isPointerType() &&
5202 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5203 ArrayType->getElementType())) {
5204 // End pointer.
5205 if (!HandleLValueArrayAdjustment(Info, E, Array,
5206 ArrayType->getElementType(),
5207 ArrayType->getSize().getZExtValue()))
5208 return false;
5209 Array.moveInto(Result.getStructField(1));
5210 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5211 // Length.
5212 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5213 else
5214 return Error(E);
5215
5216 if (++Field != Record->field_end())
5217 return Error(E);
5218
5219 return true;
5220}
5221
Richard Smithd62306a2011-11-10 06:34:14 +00005222static bool EvaluateRecord(const Expr *E, const LValue &This,
5223 APValue &Result, EvalInfo &Info) {
5224 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005225 "can't evaluate expression as a record rvalue");
5226 return RecordExprEvaluator(Info, This, Result).Visit(E);
5227}
5228
5229//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005230// Temporary Evaluation
5231//
5232// Temporaries are represented in the AST as rvalues, but generally behave like
5233// lvalues. The full-object of which the temporary is a subobject is implicitly
5234// materialized so that a reference can bind to it.
5235//===----------------------------------------------------------------------===//
5236namespace {
5237class TemporaryExprEvaluator
5238 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5239public:
5240 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5241 LValueExprEvaluatorBaseTy(Info, Result) {}
5242
5243 /// Visit an expression which constructs the value of this temporary.
5244 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005245 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005246 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5247 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005248 }
5249
5250 bool VisitCastExpr(const CastExpr *E) {
5251 switch (E->getCastKind()) {
5252 default:
5253 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5254
5255 case CK_ConstructorConversion:
5256 return VisitConstructExpr(E->getSubExpr());
5257 }
5258 }
5259 bool VisitInitListExpr(const InitListExpr *E) {
5260 return VisitConstructExpr(E);
5261 }
5262 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5263 return VisitConstructExpr(E);
5264 }
5265 bool VisitCallExpr(const CallExpr *E) {
5266 return VisitConstructExpr(E);
5267 }
5268};
5269} // end anonymous namespace
5270
5271/// Evaluate an expression of record type as a temporary.
5272static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005273 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005274 return TemporaryExprEvaluator(Info, Result).Visit(E);
5275}
5276
5277//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005278// Vector Evaluation
5279//===----------------------------------------------------------------------===//
5280
5281namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005282 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005283 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005284 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005285 public:
Mike Stump11289f42009-09-09 15:08:12 +00005286
Richard Smith2d406342011-10-22 21:10:00 +00005287 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5288 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005289
Richard Smith2d406342011-10-22 21:10:00 +00005290 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5291 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5292 // FIXME: remove this APValue copy.
5293 Result = APValue(V.data(), V.size());
5294 return true;
5295 }
Richard Smith2e312c82012-03-03 22:46:17 +00005296 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005297 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005298 Result = V;
5299 return true;
5300 }
Richard Smithfddd3842011-12-30 21:15:51 +00005301 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005302
Richard Smith2d406342011-10-22 21:10:00 +00005303 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005304 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005305 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005306 bool VisitInitListExpr(const InitListExpr *E);
5307 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005308 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005309 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005310 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005311 };
5312} // end anonymous namespace
5313
5314static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005315 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005316 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005317}
5318
Richard Smith2d406342011-10-22 21:10:00 +00005319bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5320 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005321 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005322
Richard Smith161f09a2011-12-06 22:44:34 +00005323 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005324 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005325
Eli Friedmanc757de22011-03-25 00:43:55 +00005326 switch (E->getCastKind()) {
5327 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005328 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005329 if (SETy->isIntegerType()) {
5330 APSInt IntResult;
5331 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005333 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005334 } else if (SETy->isRealFloatingType()) {
5335 APFloat F(0.0);
5336 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005337 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005338 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005339 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005340 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005341 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005342
5343 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005344 SmallVector<APValue, 4> Elts(NElts, Val);
5345 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005346 }
Eli Friedman803acb32011-12-22 03:51:45 +00005347 case CK_BitCast: {
5348 // Evaluate the operand into an APInt we can extract from.
5349 llvm::APInt SValInt;
5350 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5351 return false;
5352 // Extract the elements
5353 QualType EltTy = VTy->getElementType();
5354 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5355 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5356 SmallVector<APValue, 4> Elts;
5357 if (EltTy->isRealFloatingType()) {
5358 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005359 unsigned FloatEltSize = EltSize;
5360 if (&Sem == &APFloat::x87DoubleExtended)
5361 FloatEltSize = 80;
5362 for (unsigned i = 0; i < NElts; i++) {
5363 llvm::APInt Elt;
5364 if (BigEndian)
5365 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5366 else
5367 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005368 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005369 }
5370 } else if (EltTy->isIntegerType()) {
5371 for (unsigned i = 0; i < NElts; i++) {
5372 llvm::APInt Elt;
5373 if (BigEndian)
5374 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5375 else
5376 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5377 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5378 }
5379 } else {
5380 return Error(E);
5381 }
5382 return Success(Elts, E);
5383 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005384 default:
Richard Smith11562c52011-10-28 17:51:58 +00005385 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005386 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005387}
5388
Richard Smith2d406342011-10-22 21:10:00 +00005389bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005390VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005391 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005392 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005393 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005394
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005395 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005396 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005397
Eli Friedmanb9c71292012-01-03 23:24:20 +00005398 // The number of initializers can be less than the number of
5399 // vector elements. For OpenCL, this can be due to nested vector
5400 // initialization. For GCC compatibility, missing trailing elements
5401 // should be initialized with zeroes.
5402 unsigned CountInits = 0, CountElts = 0;
5403 while (CountElts < NumElements) {
5404 // Handle nested vector initialization.
5405 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005406 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005407 APValue v;
5408 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5409 return Error(E);
5410 unsigned vlen = v.getVectorLength();
5411 for (unsigned j = 0; j < vlen; j++)
5412 Elements.push_back(v.getVectorElt(j));
5413 CountElts += vlen;
5414 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005415 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005416 if (CountInits < NumInits) {
5417 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005418 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005419 } else // trailing integer zero.
5420 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5421 Elements.push_back(APValue(sInt));
5422 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005423 } else {
5424 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005425 if (CountInits < NumInits) {
5426 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005427 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005428 } else // trailing float zero.
5429 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5430 Elements.push_back(APValue(f));
5431 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005432 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005433 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005434 }
Richard Smith2d406342011-10-22 21:10:00 +00005435 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005436}
5437
Richard Smith2d406342011-10-22 21:10:00 +00005438bool
Richard Smithfddd3842011-12-30 21:15:51 +00005439VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005440 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005441 QualType EltTy = VT->getElementType();
5442 APValue ZeroElement;
5443 if (EltTy->isIntegerType())
5444 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5445 else
5446 ZeroElement =
5447 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5448
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005449 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005450 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005451}
5452
Richard Smith2d406342011-10-22 21:10:00 +00005453bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005454 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005455 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005456}
5457
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005458//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005459// Array Evaluation
5460//===----------------------------------------------------------------------===//
5461
5462namespace {
5463 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005464 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005465 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005466 APValue &Result;
5467 public:
5468
Richard Smithd62306a2011-11-10 06:34:14 +00005469 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5470 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005471
5472 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005473 assert((V.isArray() || V.isLValue()) &&
5474 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005475 Result = V;
5476 return true;
5477 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005478
Richard Smithfddd3842011-12-30 21:15:51 +00005479 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005480 const ConstantArrayType *CAT =
5481 Info.Ctx.getAsConstantArrayType(E->getType());
5482 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005483 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005484
5485 Result = APValue(APValue::UninitArray(), 0,
5486 CAT->getSize().getZExtValue());
5487 if (!Result.hasArrayFiller()) return true;
5488
Richard Smithfddd3842011-12-30 21:15:51 +00005489 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005490 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005491 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005492 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005493 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005494 }
5495
Richard Smithf3e9e432011-11-07 09:22:26 +00005496 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005497 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005498 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5499 const LValue &Subobject,
5500 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005501 };
5502} // end anonymous namespace
5503
Richard Smithd62306a2011-11-10 06:34:14 +00005504static bool EvaluateArray(const Expr *E, const LValue &This,
5505 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005506 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005507 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005508}
5509
5510bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5511 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5512 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005513 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005514
Richard Smithca2cfbf2011-12-22 01:07:19 +00005515 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5516 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005517 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005518 LValue LV;
5519 if (!EvaluateLValue(E->getInit(0), LV, Info))
5520 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005521 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005522 LV.moveInto(Val);
5523 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005524 }
5525
Richard Smith253c2a32012-01-27 01:14:48 +00005526 bool Success = true;
5527
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005528 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5529 "zero-initialized array shouldn't have any initialized elts");
5530 APValue Filler;
5531 if (Result.isArray() && Result.hasArrayFiller())
5532 Filler = Result.getArrayFiller();
5533
Richard Smith9543c5e2013-04-22 14:44:29 +00005534 unsigned NumEltsToInit = E->getNumInits();
5535 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005536 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005537
5538 // If the initializer might depend on the array index, run it for each
5539 // array element. For now, just whitelist non-class value-initialization.
5540 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5541 NumEltsToInit = NumElts;
5542
5543 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005544
5545 // If the array was previously zero-initialized, preserve the
5546 // zero-initialized values.
5547 if (!Filler.isUninit()) {
5548 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5549 Result.getArrayInitializedElt(I) = Filler;
5550 if (Result.hasArrayFiller())
5551 Result.getArrayFiller() = Filler;
5552 }
5553
Richard Smithd62306a2011-11-10 06:34:14 +00005554 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005555 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005556 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5557 const Expr *Init =
5558 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005559 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005560 Info, Subobject, Init) ||
5561 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005562 CAT->getElementType(), 1)) {
5563 if (!Info.keepEvaluatingAfterFailure())
5564 return false;
5565 Success = false;
5566 }
Richard Smithd62306a2011-11-10 06:34:14 +00005567 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005568
Richard Smith9543c5e2013-04-22 14:44:29 +00005569 if (!Result.hasArrayFiller())
5570 return Success;
5571
5572 // If we get here, we have a trivial filler, which we can just evaluate
5573 // once and splat over the rest of the array elements.
5574 assert(FillerExpr && "no array filler for incomplete init list");
5575 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5576 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005577}
5578
Richard Smith027bf112011-11-17 22:56:20 +00005579bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005580 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5581}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005582
Richard Smith9543c5e2013-04-22 14:44:29 +00005583bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5584 const LValue &Subobject,
5585 APValue *Value,
5586 QualType Type) {
5587 bool HadZeroInit = !Value->isUninit();
5588
5589 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5590 unsigned N = CAT->getSize().getZExtValue();
5591
5592 // Preserve the array filler if we had prior zero-initialization.
5593 APValue Filler =
5594 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5595 : APValue();
5596
5597 *Value = APValue(APValue::UninitArray(), N, N);
5598
5599 if (HadZeroInit)
5600 for (unsigned I = 0; I != N; ++I)
5601 Value->getArrayInitializedElt(I) = Filler;
5602
5603 // Initialize the elements.
5604 LValue ArrayElt = Subobject;
5605 ArrayElt.addArray(Info, E, CAT);
5606 for (unsigned I = 0; I != N; ++I)
5607 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5608 CAT->getElementType()) ||
5609 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5610 CAT->getElementType(), 1))
5611 return false;
5612
5613 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005614 }
Richard Smith027bf112011-11-17 22:56:20 +00005615
Richard Smith9543c5e2013-04-22 14:44:29 +00005616 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005617 return Error(E);
5618
Richard Smith027bf112011-11-17 22:56:20 +00005619 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005620
Richard Smithfddd3842011-12-30 21:15:51 +00005621 bool ZeroInit = E->requiresZeroInitialization();
5622 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005623 if (HadZeroInit)
5624 return true;
5625
Richard Smithda3f4fd2014-03-05 23:32:50 +00005626 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5627 ImplicitValueInitExpr VIE(Type);
5628 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005629 }
5630
Craig Topper36250ad2014-05-12 05:36:57 +00005631 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005632 FD->getBody(Definition);
5633
Richard Smith357362d2011-12-13 06:39:58 +00005634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5635 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005636
Richard Smith9eae7232012-01-12 18:54:33 +00005637 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005638 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005639 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005640 return false;
5641 }
5642
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005643 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005644 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005645 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005646 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005647}
5648
Richard Smithf3e9e432011-11-07 09:22:26 +00005649//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005650// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005651//
5652// As a GNU extension, we support casting pointers to sufficiently-wide integer
5653// types and back in constant folding. Integer values are thus represented
5654// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005655//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005656
5657namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005658class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005659 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005660 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005661public:
Richard Smith2e312c82012-03-03 22:46:17 +00005662 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005663 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005664
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005665 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005666 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005667 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005668 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005669 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005670 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005671 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005672 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005673 return true;
5674 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005675 bool Success(const llvm::APSInt &SI, const Expr *E) {
5676 return Success(SI, E, Result);
5677 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005678
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005679 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005680 assert(E->getType()->isIntegralOrEnumerationType() &&
5681 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005682 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005683 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005684 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005685 Result.getInt().setIsUnsigned(
5686 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005687 return true;
5688 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005689 bool Success(const llvm::APInt &I, const Expr *E) {
5690 return Success(I, E, Result);
5691 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005692
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005693 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005694 assert(E->getType()->isIntegralOrEnumerationType() &&
5695 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005696 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005697 return true;
5698 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005699 bool Success(uint64_t Value, const Expr *E) {
5700 return Success(Value, E, Result);
5701 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005702
Ken Dyckdbc01912011-03-11 02:13:43 +00005703 bool Success(CharUnits Size, const Expr *E) {
5704 return Success(Size.getQuantity(), E);
5705 }
5706
Richard Smith2e312c82012-03-03 22:46:17 +00005707 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005708 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005709 Result = V;
5710 return true;
5711 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005712 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005713 }
Mike Stump11289f42009-09-09 15:08:12 +00005714
Richard Smithfddd3842011-12-30 21:15:51 +00005715 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005716
Peter Collingbournee9200682011-05-13 03:29:01 +00005717 //===--------------------------------------------------------------------===//
5718 // Visitor Methods
5719 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005720
Chris Lattner7174bf32008-07-12 00:38:25 +00005721 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005722 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005723 }
5724 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005725 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005726 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005727
5728 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5729 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005730 if (CheckReferencedDecl(E, E->getDecl()))
5731 return true;
5732
5733 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005734 }
5735 bool VisitMemberExpr(const MemberExpr *E) {
5736 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005737 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005738 return true;
5739 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005740
5741 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005742 }
5743
Peter Collingbournee9200682011-05-13 03:29:01 +00005744 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005745 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005746 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005747 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005748
Peter Collingbournee9200682011-05-13 03:29:01 +00005749 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005750 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005751
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005752 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005753 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005754 }
Mike Stump11289f42009-09-09 15:08:12 +00005755
Ted Kremeneke65b0862012-03-06 20:05:56 +00005756 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5757 return Success(E->getValue(), E);
5758 }
5759
Richard Smith4ce706a2011-10-11 21:43:33 +00005760 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005761 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005762 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005763 }
5764
Douglas Gregor29c42f22012-02-24 07:38:34 +00005765 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5766 return Success(E->getValue(), E);
5767 }
5768
John Wiegley6242b6a2011-04-28 00:16:57 +00005769 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5770 return Success(E->getValue(), E);
5771 }
5772
John Wiegleyf9f65842011-04-25 06:54:41 +00005773 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5774 return Success(E->getValue(), E);
5775 }
5776
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005777 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005778 bool VisitUnaryImag(const UnaryOperator *E);
5779
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005780 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005781 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005782
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005783private:
Ken Dyck160146e2010-01-27 17:10:57 +00005784 CharUnits GetAlignOfExpr(const Expr *E);
5785 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005786 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005787 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005788 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005789};
Chris Lattner05706e882008-07-11 18:11:29 +00005790} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005791
Richard Smith11562c52011-10-28 17:51:58 +00005792/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5793/// produce either the integer value or a pointer.
5794///
5795/// GCC has a heinous extension which folds casts between pointer types and
5796/// pointer-sized integral types. We support this by allowing the evaluation of
5797/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5798/// Some simple arithmetic on such values is supported (they are treated much
5799/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005800static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005801 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005802 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005803 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005804}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005805
Richard Smithf57d8cb2011-12-09 22:58:01 +00005806static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005807 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005808 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005809 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005810 if (!Val.isInt()) {
5811 // FIXME: It would be better to produce the diagnostic for casting
5812 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005813 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005814 return false;
5815 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005816 Result = Val.getInt();
5817 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005818}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005819
Richard Smithf57d8cb2011-12-09 22:58:01 +00005820/// Check whether the given declaration can be directly converted to an integral
5821/// rvalue. If not, no diagnostic is produced; there are other things we can
5822/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005823bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005824 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005825 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005826 // Check for signedness/width mismatches between E type and ECD value.
5827 bool SameSign = (ECD->getInitVal().isSigned()
5828 == E->getType()->isSignedIntegerOrEnumerationType());
5829 bool SameWidth = (ECD->getInitVal().getBitWidth()
5830 == Info.Ctx.getIntWidth(E->getType()));
5831 if (SameSign && SameWidth)
5832 return Success(ECD->getInitVal(), E);
5833 else {
5834 // Get rid of mismatch (otherwise Success assertions will fail)
5835 // by computing a new value matching the type of E.
5836 llvm::APSInt Val = ECD->getInitVal();
5837 if (!SameSign)
5838 Val.setIsSigned(!ECD->getInitVal().isSigned());
5839 if (!SameWidth)
5840 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5841 return Success(Val, E);
5842 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005843 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005844 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005845}
5846
Chris Lattner86ee2862008-10-06 06:40:35 +00005847/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5848/// as GCC.
5849static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5850 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005851 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005852 enum gcc_type_class {
5853 no_type_class = -1,
5854 void_type_class, integer_type_class, char_type_class,
5855 enumeral_type_class, boolean_type_class,
5856 pointer_type_class, reference_type_class, offset_type_class,
5857 real_type_class, complex_type_class,
5858 function_type_class, method_type_class,
5859 record_type_class, union_type_class,
5860 array_type_class, string_type_class,
5861 lang_type_class
5862 };
Mike Stump11289f42009-09-09 15:08:12 +00005863
5864 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005865 // ideal, however it is what gcc does.
5866 if (E->getNumArgs() == 0)
5867 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005868
Chris Lattner86ee2862008-10-06 06:40:35 +00005869 QualType ArgTy = E->getArg(0)->getType();
5870 if (ArgTy->isVoidType())
5871 return void_type_class;
5872 else if (ArgTy->isEnumeralType())
5873 return enumeral_type_class;
5874 else if (ArgTy->isBooleanType())
5875 return boolean_type_class;
5876 else if (ArgTy->isCharType())
5877 return string_type_class; // gcc doesn't appear to use char_type_class
5878 else if (ArgTy->isIntegerType())
5879 return integer_type_class;
5880 else if (ArgTy->isPointerType())
5881 return pointer_type_class;
5882 else if (ArgTy->isReferenceType())
5883 return reference_type_class;
5884 else if (ArgTy->isRealType())
5885 return real_type_class;
5886 else if (ArgTy->isComplexType())
5887 return complex_type_class;
5888 else if (ArgTy->isFunctionType())
5889 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005890 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005891 return record_type_class;
5892 else if (ArgTy->isUnionType())
5893 return union_type_class;
5894 else if (ArgTy->isArrayType())
5895 return array_type_class;
5896 else if (ArgTy->isUnionType())
5897 return union_type_class;
5898 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005899 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005900}
5901
Richard Smith5fab0c92011-12-28 19:48:30 +00005902/// EvaluateBuiltinConstantPForLValue - Determine the result of
5903/// __builtin_constant_p when applied to the given lvalue.
5904///
5905/// An lvalue is only "constant" if it is a pointer or reference to the first
5906/// character of a string literal.
5907template<typename LValue>
5908static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005909 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005910 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5911}
5912
5913/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5914/// GCC as we can manage.
5915static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5916 QualType ArgType = Arg->getType();
5917
5918 // __builtin_constant_p always has one operand. The rules which gcc follows
5919 // are not precisely documented, but are as follows:
5920 //
5921 // - If the operand is of integral, floating, complex or enumeration type,
5922 // and can be folded to a known value of that type, it returns 1.
5923 // - If the operand and can be folded to a pointer to the first character
5924 // of a string literal (or such a pointer cast to an integral type), it
5925 // returns 1.
5926 //
5927 // Otherwise, it returns 0.
5928 //
5929 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5930 // its support for this does not currently work.
5931 if (ArgType->isIntegralOrEnumerationType()) {
5932 Expr::EvalResult Result;
5933 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5934 return false;
5935
5936 APValue &V = Result.Val;
5937 if (V.getKind() == APValue::Int)
5938 return true;
5939
5940 return EvaluateBuiltinConstantPForLValue(V);
5941 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5942 return Arg->isEvaluatable(Ctx);
5943 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5944 LValue LV;
5945 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005946 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005947 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5948 : EvaluatePointer(Arg, LV, Info)) &&
5949 !Status.HasSideEffects)
5950 return EvaluateBuiltinConstantPForLValue(LV);
5951 }
5952
5953 // Anything else isn't considered to be sufficiently constant.
5954 return false;
5955}
5956
John McCall95007602010-05-10 23:27:23 +00005957/// Retrieves the "underlying object type" of the given expression,
5958/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005959QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5960 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5961 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005962 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005963 } else if (const Expr *E = B.get<const Expr*>()) {
5964 if (isa<CompoundLiteralExpr>(E))
5965 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005966 }
5967
5968 return QualType();
5969}
5970
Peter Collingbournee9200682011-05-13 03:29:01 +00005971bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005972 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005973
5974 {
5975 // The operand of __builtin_object_size is never evaluated for side-effects.
5976 // If there are any, but we can determine the pointed-to object anyway, then
5977 // ignore the side-effects.
5978 SpeculativeEvaluationRAII SpeculativeEval(Info);
5979 if (!EvaluatePointer(E->getArg(0), Base, Info))
5980 return false;
5981 }
John McCall95007602010-05-10 23:27:23 +00005982
5983 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005984 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005985
Richard Smithce40ad62011-11-12 22:28:03 +00005986 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005987 if (T.isNull() ||
5988 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005989 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005990 T->isVariablyModifiedType() ||
5991 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005992 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005993
5994 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5995 CharUnits Offset = Base.getLValueOffset();
5996
5997 if (!Offset.isNegative() && Offset <= Size)
5998 Size -= Offset;
5999 else
6000 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00006001 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00006002}
6003
Peter Collingbournee9200682011-05-13 03:29:01 +00006004bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006005 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006006 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006007 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006008
6009 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006010 if (TryEvaluateBuiltinObjectSize(E))
6011 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006012
Richard Smith0421ce72012-08-07 04:16:51 +00006013 // If evaluating the argument has side-effects, we can't determine the size
6014 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6015 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006016 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006017 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006018 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006019 return Success(0, E);
6020 }
Mike Stump876387b2009-10-27 22:09:17 +00006021
Richard Smith01ade172012-05-23 04:13:20 +00006022 // Expression had no side effects, but we couldn't statically determine the
6023 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006024 switch (Info.EvalMode) {
6025 case EvalInfo::EM_ConstantExpression:
6026 case EvalInfo::EM_PotentialConstantExpression:
6027 case EvalInfo::EM_ConstantFold:
6028 case EvalInfo::EM_EvaluateForOverflow:
6029 case EvalInfo::EM_IgnoreSideEffects:
6030 return Error(E);
6031 case EvalInfo::EM_ConstantExpressionUnevaluated:
6032 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6033 return Success(-1ULL, E);
6034 }
Mike Stump722cedf2009-10-26 18:35:08 +00006035 }
6036
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006037 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006038 case Builtin::BI__builtin_bswap32:
6039 case Builtin::BI__builtin_bswap64: {
6040 APSInt Val;
6041 if (!EvaluateInteger(E->getArg(0), Val, Info))
6042 return false;
6043
6044 return Success(Val.byteSwap(), E);
6045 }
6046
Richard Smith8889a3d2013-06-13 06:26:32 +00006047 case Builtin::BI__builtin_classify_type:
6048 return Success(EvaluateBuiltinClassifyType(E), E);
6049
6050 // FIXME: BI__builtin_clrsb
6051 // FIXME: BI__builtin_clrsbl
6052 // FIXME: BI__builtin_clrsbll
6053
Richard Smith80b3c8e2013-06-13 05:04:16 +00006054 case Builtin::BI__builtin_clz:
6055 case Builtin::BI__builtin_clzl:
6056 case Builtin::BI__builtin_clzll: {
6057 APSInt Val;
6058 if (!EvaluateInteger(E->getArg(0), Val, Info))
6059 return false;
6060 if (!Val)
6061 return Error(E);
6062
6063 return Success(Val.countLeadingZeros(), E);
6064 }
6065
Richard Smith8889a3d2013-06-13 06:26:32 +00006066 case Builtin::BI__builtin_constant_p:
6067 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6068
Richard Smith80b3c8e2013-06-13 05:04:16 +00006069 case Builtin::BI__builtin_ctz:
6070 case Builtin::BI__builtin_ctzl:
6071 case Builtin::BI__builtin_ctzll: {
6072 APSInt Val;
6073 if (!EvaluateInteger(E->getArg(0), Val, Info))
6074 return false;
6075 if (!Val)
6076 return Error(E);
6077
6078 return Success(Val.countTrailingZeros(), E);
6079 }
6080
Richard Smith8889a3d2013-06-13 06:26:32 +00006081 case Builtin::BI__builtin_eh_return_data_regno: {
6082 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6083 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6084 return Success(Operand, E);
6085 }
6086
6087 case Builtin::BI__builtin_expect:
6088 return Visit(E->getArg(0));
6089
6090 case Builtin::BI__builtin_ffs:
6091 case Builtin::BI__builtin_ffsl:
6092 case Builtin::BI__builtin_ffsll: {
6093 APSInt Val;
6094 if (!EvaluateInteger(E->getArg(0), Val, Info))
6095 return false;
6096
6097 unsigned N = Val.countTrailingZeros();
6098 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6099 }
6100
6101 case Builtin::BI__builtin_fpclassify: {
6102 APFloat Val(0.0);
6103 if (!EvaluateFloat(E->getArg(5), Val, Info))
6104 return false;
6105 unsigned Arg;
6106 switch (Val.getCategory()) {
6107 case APFloat::fcNaN: Arg = 0; break;
6108 case APFloat::fcInfinity: Arg = 1; break;
6109 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6110 case APFloat::fcZero: Arg = 4; break;
6111 }
6112 return Visit(E->getArg(Arg));
6113 }
6114
6115 case Builtin::BI__builtin_isinf_sign: {
6116 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006117 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006118 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6119 }
6120
Richard Smithea3019d2013-10-15 19:07:14 +00006121 case Builtin::BI__builtin_isinf: {
6122 APFloat Val(0.0);
6123 return EvaluateFloat(E->getArg(0), Val, Info) &&
6124 Success(Val.isInfinity() ? 1 : 0, E);
6125 }
6126
6127 case Builtin::BI__builtin_isfinite: {
6128 APFloat Val(0.0);
6129 return EvaluateFloat(E->getArg(0), Val, Info) &&
6130 Success(Val.isFinite() ? 1 : 0, E);
6131 }
6132
6133 case Builtin::BI__builtin_isnan: {
6134 APFloat Val(0.0);
6135 return EvaluateFloat(E->getArg(0), Val, Info) &&
6136 Success(Val.isNaN() ? 1 : 0, E);
6137 }
6138
6139 case Builtin::BI__builtin_isnormal: {
6140 APFloat Val(0.0);
6141 return EvaluateFloat(E->getArg(0), Val, Info) &&
6142 Success(Val.isNormal() ? 1 : 0, E);
6143 }
6144
Richard Smith8889a3d2013-06-13 06:26:32 +00006145 case Builtin::BI__builtin_parity:
6146 case Builtin::BI__builtin_parityl:
6147 case Builtin::BI__builtin_parityll: {
6148 APSInt Val;
6149 if (!EvaluateInteger(E->getArg(0), Val, Info))
6150 return false;
6151
6152 return Success(Val.countPopulation() % 2, E);
6153 }
6154
Richard Smith80b3c8e2013-06-13 05:04:16 +00006155 case Builtin::BI__builtin_popcount:
6156 case Builtin::BI__builtin_popcountl:
6157 case Builtin::BI__builtin_popcountll: {
6158 APSInt Val;
6159 if (!EvaluateInteger(E->getArg(0), Val, Info))
6160 return false;
6161
6162 return Success(Val.countPopulation(), E);
6163 }
6164
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006165 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006166 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006167 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006168 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006169 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6170 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006171 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006172 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006173 case Builtin::BI__builtin_strlen: {
6174 // As an extension, we support __builtin_strlen() as a constant expression,
6175 // and support folding strlen() to a constant.
6176 LValue String;
6177 if (!EvaluatePointer(E->getArg(0), String, Info))
6178 return false;
6179
6180 // Fast path: if it's a string literal, search the string value.
6181 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6182 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006183 // The string literal may have embedded null characters. Find the first
6184 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006185 StringRef Str = S->getBytes();
6186 int64_t Off = String.Offset.getQuantity();
6187 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6188 S->getCharByteWidth() == 1) {
6189 Str = Str.substr(Off);
6190
6191 StringRef::size_type Pos = Str.find(0);
6192 if (Pos != StringRef::npos)
6193 Str = Str.substr(0, Pos);
6194
6195 return Success(Str.size(), E);
6196 }
6197
6198 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006199 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006200
6201 // Slow path: scan the bytes of the string looking for the terminating 0.
6202 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6203 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6204 APValue Char;
6205 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6206 !Char.isInt())
6207 return false;
6208 if (!Char.getInt())
6209 return Success(Strlen, E);
6210 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6211 return false;
6212 }
6213 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006214
Richard Smith01ba47d2012-04-13 00:45:38 +00006215 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006216 case Builtin::BI__atomic_is_lock_free:
6217 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006218 APSInt SizeVal;
6219 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6220 return false;
6221
6222 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6223 // of two less than the maximum inline atomic width, we know it is
6224 // lock-free. If the size isn't a power of two, or greater than the
6225 // maximum alignment where we promote atomics, we know it is not lock-free
6226 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6227 // the answer can only be determined at runtime; for example, 16-byte
6228 // atomics have lock-free implementations on some, but not all,
6229 // x86-64 processors.
6230
6231 // Check power-of-two.
6232 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006233 if (Size.isPowerOfTwo()) {
6234 // Check against inlining width.
6235 unsigned InlineWidthBits =
6236 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6237 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6238 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6239 Size == CharUnits::One() ||
6240 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6241 Expr::NPC_NeverValueDependent))
6242 // OK, we will inline appropriately-aligned operations of this size,
6243 // and _Atomic(T) is appropriately-aligned.
6244 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006245
Richard Smith01ba47d2012-04-13 00:45:38 +00006246 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6247 castAs<PointerType>()->getPointeeType();
6248 if (!PointeeType->isIncompleteType() &&
6249 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6250 // OK, we will inline operations on this object.
6251 return Success(1, E);
6252 }
6253 }
6254 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006255
Richard Smith01ba47d2012-04-13 00:45:38 +00006256 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6257 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006258 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006259 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006260}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006261
Richard Smith8b3497e2011-10-31 01:37:14 +00006262static bool HasSameBase(const LValue &A, const LValue &B) {
6263 if (!A.getLValueBase())
6264 return !B.getLValueBase();
6265 if (!B.getLValueBase())
6266 return false;
6267
Richard Smithce40ad62011-11-12 22:28:03 +00006268 if (A.getLValueBase().getOpaqueValue() !=
6269 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006270 const Decl *ADecl = GetLValueBaseDecl(A);
6271 if (!ADecl)
6272 return false;
6273 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006274 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006275 return false;
6276 }
6277
6278 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006279 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006280}
6281
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006282namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006283
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006284/// \brief Data recursive integer evaluator of certain binary operators.
6285///
6286/// We use a data recursive algorithm for binary operators so that we are able
6287/// to handle extreme cases of chained binary operators without causing stack
6288/// overflow.
6289class DataRecursiveIntBinOpEvaluator {
6290 struct EvalResult {
6291 APValue Val;
6292 bool Failed;
6293
6294 EvalResult() : Failed(false) { }
6295
6296 void swap(EvalResult &RHS) {
6297 Val.swap(RHS.Val);
6298 Failed = RHS.Failed;
6299 RHS.Failed = false;
6300 }
6301 };
6302
6303 struct Job {
6304 const Expr *E;
6305 EvalResult LHSResult; // meaningful only for binary operator expression.
6306 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006307
6308 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006309 void startSpeculativeEval(EvalInfo &Info) {
6310 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006311 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006312 StoredInfo = &Info;
6313 }
6314 ~Job() {
6315 if (StoredInfo) {
6316 StoredInfo->EvalStatus = OldEvalStatus;
6317 }
6318 }
6319 private:
6320 EvalInfo *StoredInfo; // non-null if status changed.
6321 Expr::EvalStatus OldEvalStatus;
6322 };
6323
6324 SmallVector<Job, 16> Queue;
6325
6326 IntExprEvaluator &IntEval;
6327 EvalInfo &Info;
6328 APValue &FinalResult;
6329
6330public:
6331 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6332 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6333
6334 /// \brief True if \param E is a binary operator that we are going to handle
6335 /// data recursively.
6336 /// We handle binary operators that are comma, logical, or that have operands
6337 /// with integral or enumeration type.
6338 static bool shouldEnqueue(const BinaryOperator *E) {
6339 return E->getOpcode() == BO_Comma ||
6340 E->isLogicalOp() ||
6341 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6342 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006343 }
6344
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006345 bool Traverse(const BinaryOperator *E) {
6346 enqueue(E);
6347 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006348 while (!Queue.empty())
6349 process(PrevResult);
6350
6351 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006352
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006353 FinalResult.swap(PrevResult.Val);
6354 return true;
6355 }
6356
6357private:
6358 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6359 return IntEval.Success(Value, E, Result);
6360 }
6361 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6362 return IntEval.Success(Value, E, Result);
6363 }
6364 bool Error(const Expr *E) {
6365 return IntEval.Error(E);
6366 }
6367 bool Error(const Expr *E, diag::kind D) {
6368 return IntEval.Error(E, D);
6369 }
6370
6371 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6372 return Info.CCEDiag(E, D);
6373 }
6374
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006375 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6376 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006377 bool &SuppressRHSDiags);
6378
6379 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6380 const BinaryOperator *E, APValue &Result);
6381
6382 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6383 Result.Failed = !Evaluate(Result.Val, Info, E);
6384 if (Result.Failed)
6385 Result.Val = APValue();
6386 }
6387
Richard Trieuba4d0872012-03-21 23:30:30 +00006388 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006389
6390 void enqueue(const Expr *E) {
6391 E = E->IgnoreParens();
6392 Queue.resize(Queue.size()+1);
6393 Queue.back().E = E;
6394 Queue.back().Kind = Job::AnyExprKind;
6395 }
6396};
6397
6398}
6399
6400bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006401 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006402 bool &SuppressRHSDiags) {
6403 if (E->getOpcode() == BO_Comma) {
6404 // Ignore LHS but note if we could not evaluate it.
6405 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006406 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006407 return true;
6408 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006409
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006411 bool LHSAsBool;
6412 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006413 // We were able to evaluate the LHS, see if we can get away with not
6414 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006415 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6416 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006417 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006418 }
6419 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006420 LHSResult.Failed = true;
6421
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006422 // Since we weren't able to evaluate the left hand side, it
6423 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006424 if (!Info.noteSideEffect())
6425 return false;
6426
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006427 // We can't evaluate the LHS; however, sometimes the result
6428 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6429 // Don't ignore RHS and suppress diagnostics from this arm.
6430 SuppressRHSDiags = true;
6431 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006432
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006433 return true;
6434 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006435
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006436 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6437 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006438
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006439 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006440 return false; // Ignore RHS;
6441
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006442 return true;
6443}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006444
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006445bool DataRecursiveIntBinOpEvaluator::
6446 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6447 const BinaryOperator *E, APValue &Result) {
6448 if (E->getOpcode() == BO_Comma) {
6449 if (RHSResult.Failed)
6450 return false;
6451 Result = RHSResult.Val;
6452 return true;
6453 }
6454
6455 if (E->isLogicalOp()) {
6456 bool lhsResult, rhsResult;
6457 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6458 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6459
6460 if (LHSIsOK) {
6461 if (RHSIsOK) {
6462 if (E->getOpcode() == BO_LOr)
6463 return Success(lhsResult || rhsResult, E, Result);
6464 else
6465 return Success(lhsResult && rhsResult, E, Result);
6466 }
6467 } else {
6468 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006469 // We can't evaluate the LHS; however, sometimes the result
6470 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6471 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006472 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006473 }
6474 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006475
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006476 return false;
6477 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006478
6479 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6480 E->getRHS()->getType()->isIntegralOrEnumerationType());
6481
6482 if (LHSResult.Failed || RHSResult.Failed)
6483 return false;
6484
6485 const APValue &LHSVal = LHSResult.Val;
6486 const APValue &RHSVal = RHSResult.Val;
6487
6488 // Handle cases like (unsigned long)&a + 4.
6489 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6490 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006491 CharUnits AdditionalOffset =
6492 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006493 if (E->getOpcode() == BO_Add)
6494 Result.getLValueOffset() += AdditionalOffset;
6495 else
6496 Result.getLValueOffset() -= AdditionalOffset;
6497 return true;
6498 }
6499
6500 // Handle cases like 4 + (unsigned long)&a
6501 if (E->getOpcode() == BO_Add &&
6502 RHSVal.isLValue() && LHSVal.isInt()) {
6503 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006504 Result.getLValueOffset() +=
6505 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006506 return true;
6507 }
6508
6509 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6510 // Handle (intptr_t)&&A - (intptr_t)&&B.
6511 if (!LHSVal.getLValueOffset().isZero() ||
6512 !RHSVal.getLValueOffset().isZero())
6513 return false;
6514 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6515 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6516 if (!LHSExpr || !RHSExpr)
6517 return false;
6518 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6519 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6520 if (!LHSAddrExpr || !RHSAddrExpr)
6521 return false;
6522 // Make sure both labels come from the same function.
6523 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6524 RHSAddrExpr->getLabel()->getDeclContext())
6525 return false;
6526 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6527 return true;
6528 }
Richard Smith43e77732013-05-07 04:50:00 +00006529
6530 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006531 if (!LHSVal.isInt() || !RHSVal.isInt())
6532 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006533
6534 // Set up the width and signedness manually, in case it can't be deduced
6535 // from the operation we're performing.
6536 // FIXME: Don't do this in the cases where we can deduce it.
6537 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6538 E->getType()->isUnsignedIntegerOrEnumerationType());
6539 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6540 RHSVal.getInt(), Value))
6541 return false;
6542 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006543}
6544
Richard Trieuba4d0872012-03-21 23:30:30 +00006545void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006546 Job &job = Queue.back();
6547
6548 switch (job.Kind) {
6549 case Job::AnyExprKind: {
6550 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6551 if (shouldEnqueue(Bop)) {
6552 job.Kind = Job::BinOpKind;
6553 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006554 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006555 }
6556 }
6557
6558 EvaluateExpr(job.E, Result);
6559 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006560 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006561 }
6562
6563 case Job::BinOpKind: {
6564 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006565 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006566 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006567 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006568 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006569 }
6570 if (SuppressRHSDiags)
6571 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006572 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006573 job.Kind = Job::BinOpVisitedLHSKind;
6574 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006575 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006576 }
6577
6578 case Job::BinOpVisitedLHSKind: {
6579 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6580 EvalResult RHS;
6581 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006582 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006583 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006584 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006585 }
6586 }
6587
6588 llvm_unreachable("Invalid Job::Kind!");
6589}
6590
6591bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6592 if (E->isAssignmentOp())
6593 return Error(E);
6594
6595 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6596 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006597
Anders Carlssonacc79812008-11-16 07:17:21 +00006598 QualType LHSTy = E->getLHS()->getType();
6599 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006600
6601 if (LHSTy->isAnyComplexType()) {
6602 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006603 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006604
Richard Smith253c2a32012-01-27 01:14:48 +00006605 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6606 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006607 return false;
6608
Richard Smith253c2a32012-01-27 01:14:48 +00006609 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006610 return false;
6611
6612 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006613 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006614 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006615 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006616 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6617
John McCalle3027922010-08-25 11:45:40 +00006618 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006619 return Success((CR_r == APFloat::cmpEqual &&
6620 CR_i == APFloat::cmpEqual), E);
6621 else {
John McCalle3027922010-08-25 11:45:40 +00006622 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006623 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006624 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006625 CR_r == APFloat::cmpLessThan ||
6626 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006627 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006628 CR_i == APFloat::cmpLessThan ||
6629 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006630 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006631 } else {
John McCalle3027922010-08-25 11:45:40 +00006632 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006633 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6634 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6635 else {
John McCalle3027922010-08-25 11:45:40 +00006636 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006637 "Invalid compex comparison.");
6638 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6639 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6640 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006641 }
6642 }
Mike Stump11289f42009-09-09 15:08:12 +00006643
Anders Carlssonacc79812008-11-16 07:17:21 +00006644 if (LHSTy->isRealFloatingType() &&
6645 RHSTy->isRealFloatingType()) {
6646 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006647
Richard Smith253c2a32012-01-27 01:14:48 +00006648 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6649 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006650 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006651
Richard Smith253c2a32012-01-27 01:14:48 +00006652 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006653 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006654
Anders Carlssonacc79812008-11-16 07:17:21 +00006655 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006656
Anders Carlssonacc79812008-11-16 07:17:21 +00006657 switch (E->getOpcode()) {
6658 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006659 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006660 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006661 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006662 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006663 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006664 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006665 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006666 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006667 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006668 E);
John McCalle3027922010-08-25 11:45:40 +00006669 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006670 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006671 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006672 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006673 || CR == APFloat::cmpLessThan
6674 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006675 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677
Eli Friedmana38da572009-04-28 19:17:36 +00006678 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006679 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006680 LValue LHSValue, RHSValue;
6681
6682 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6683 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006684 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006685
Richard Smith253c2a32012-01-27 01:14:48 +00006686 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006687 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006688
Richard Smith8b3497e2011-10-31 01:37:14 +00006689 // Reject differing bases from the normal codepath; we special-case
6690 // comparisons to null.
6691 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006692 if (E->getOpcode() == BO_Sub) {
6693 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006694 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6695 return false;
6696 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006697 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006698 if (!LHSExpr || !RHSExpr)
6699 return false;
6700 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6701 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6702 if (!LHSAddrExpr || !RHSAddrExpr)
6703 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006704 // Make sure both labels come from the same function.
6705 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6706 RHSAddrExpr->getLabel()->getDeclContext())
6707 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006708 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006709 return true;
6710 }
Richard Smith83c68212011-10-31 05:11:32 +00006711 // Inequalities and subtractions between unrelated pointers have
6712 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006713 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006714 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006715 // A constant address may compare equal to the address of a symbol.
6716 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006717 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006718 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6719 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006720 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006721 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006722 // distinct addresses. In clang, the result of such a comparison is
6723 // unspecified, so it is not a constant expression. However, we do know
6724 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006725 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6726 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006727 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006728 // We can't tell whether weak symbols will end up pointing to the same
6729 // object.
6730 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006731 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006732 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006733 // (Note that clang defaults to -fmerge-all-constants, which can
6734 // lead to inconsistent results for comparisons involving the address
6735 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006736 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006737 }
Eli Friedman64004332009-03-23 04:38:34 +00006738
Richard Smith1b470412012-02-01 08:10:20 +00006739 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6740 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6741
Richard Smith84f6dcf2012-02-02 01:16:57 +00006742 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6743 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6744
John McCalle3027922010-08-25 11:45:40 +00006745 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006746 // C++11 [expr.add]p6:
6747 // Unless both pointers point to elements of the same array object, or
6748 // one past the last element of the array object, the behavior is
6749 // undefined.
6750 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6751 !AreElementsOfSameArray(getType(LHSValue.Base),
6752 LHSDesignator, RHSDesignator))
6753 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6754
Chris Lattner882bdf22010-04-20 17:13:14 +00006755 QualType Type = E->getLHS()->getType();
6756 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006757
Richard Smithd62306a2011-11-10 06:34:14 +00006758 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006759 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006760 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006761
Richard Smith84c6b3d2013-09-10 21:34:14 +00006762 // As an extension, a type may have zero size (empty struct or union in
6763 // C, array of zero length). Pointer subtraction in such cases has
6764 // undefined behavior, so is not constant.
6765 if (ElementSize.isZero()) {
6766 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6767 << ElementType;
6768 return false;
6769 }
6770
Richard Smith1b470412012-02-01 08:10:20 +00006771 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6772 // and produce incorrect results when it overflows. Such behavior
6773 // appears to be non-conforming, but is common, so perhaps we should
6774 // assume the standard intended for such cases to be undefined behavior
6775 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006776
Richard Smith1b470412012-02-01 08:10:20 +00006777 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6778 // overflow in the final conversion to ptrdiff_t.
6779 APSInt LHS(
6780 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6781 APSInt RHS(
6782 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6783 APSInt ElemSize(
6784 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6785 APSInt TrueResult = (LHS - RHS) / ElemSize;
6786 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6787
6788 if (Result.extend(65) != TrueResult)
6789 HandleOverflow(Info, E, TrueResult, E->getType());
6790 return Success(Result, E);
6791 }
Richard Smithde21b242012-01-31 06:41:30 +00006792
6793 // C++11 [expr.rel]p3:
6794 // Pointers to void (after pointer conversions) can be compared, with a
6795 // result defined as follows: If both pointers represent the same
6796 // address or are both the null pointer value, the result is true if the
6797 // operator is <= or >= and false otherwise; otherwise the result is
6798 // unspecified.
6799 // We interpret this as applying to pointers to *cv* void.
6800 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006801 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006802 CCEDiag(E, diag::note_constexpr_void_comparison);
6803
Richard Smith84f6dcf2012-02-02 01:16:57 +00006804 // C++11 [expr.rel]p2:
6805 // - If two pointers point to non-static data members of the same object,
6806 // or to subobjects or array elements fo such members, recursively, the
6807 // pointer to the later declared member compares greater provided the
6808 // two members have the same access control and provided their class is
6809 // not a union.
6810 // [...]
6811 // - Otherwise pointer comparisons are unspecified.
6812 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6813 E->isRelationalOp()) {
6814 bool WasArrayIndex;
6815 unsigned Mismatch =
6816 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6817 RHSDesignator, WasArrayIndex);
6818 // At the point where the designators diverge, the comparison has a
6819 // specified value if:
6820 // - we are comparing array indices
6821 // - we are comparing fields of a union, or fields with the same access
6822 // Otherwise, the result is unspecified and thus the comparison is not a
6823 // constant expression.
6824 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6825 Mismatch < RHSDesignator.Entries.size()) {
6826 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6827 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6828 if (!LF && !RF)
6829 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6830 else if (!LF)
6831 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6832 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6833 << RF->getParent() << RF;
6834 else if (!RF)
6835 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6836 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6837 << LF->getParent() << LF;
6838 else if (!LF->getParent()->isUnion() &&
6839 LF->getAccess() != RF->getAccess())
6840 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6841 << LF << LF->getAccess() << RF << RF->getAccess()
6842 << LF->getParent();
6843 }
6844 }
6845
Eli Friedman6c31cb42012-04-16 04:30:08 +00006846 // The comparison here must be unsigned, and performed with the same
6847 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006848 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6849 uint64_t CompareLHS = LHSOffset.getQuantity();
6850 uint64_t CompareRHS = RHSOffset.getQuantity();
6851 assert(PtrSize <= 64 && "Unexpected pointer width");
6852 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6853 CompareLHS &= Mask;
6854 CompareRHS &= Mask;
6855
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006856 // If there is a base and this is a relational operator, we can only
6857 // compare pointers within the object in question; otherwise, the result
6858 // depends on where the object is located in memory.
6859 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6860 QualType BaseTy = getType(LHSValue.Base);
6861 if (BaseTy->isIncompleteType())
6862 return Error(E);
6863 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6864 uint64_t OffsetLimit = Size.getQuantity();
6865 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6866 return Error(E);
6867 }
6868
Richard Smith8b3497e2011-10-31 01:37:14 +00006869 switch (E->getOpcode()) {
6870 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006871 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6872 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6873 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6874 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6875 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6876 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006877 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006878 }
6879 }
Richard Smith7bb00672012-02-01 01:42:44 +00006880
6881 if (LHSTy->isMemberPointerType()) {
6882 assert(E->isEqualityOp() && "unexpected member pointer operation");
6883 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6884
6885 MemberPtr LHSValue, RHSValue;
6886
6887 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6888 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6889 return false;
6890
6891 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6892 return false;
6893
6894 // C++11 [expr.eq]p2:
6895 // If both operands are null, they compare equal. Otherwise if only one is
6896 // null, they compare unequal.
6897 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6898 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6899 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6900 }
6901
6902 // Otherwise if either is a pointer to a virtual member function, the
6903 // result is unspecified.
6904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6905 if (MD->isVirtual())
6906 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6907 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6908 if (MD->isVirtual())
6909 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6910
6911 // Otherwise they compare equal if and only if they would refer to the
6912 // same member of the same most derived object or the same subobject if
6913 // they were dereferenced with a hypothetical object of the associated
6914 // class type.
6915 bool Equal = LHSValue == RHSValue;
6916 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6917 }
6918
Richard Smithab44d9b2012-02-14 22:35:28 +00006919 if (LHSTy->isNullPtrType()) {
6920 assert(E->isComparisonOp() && "unexpected nullptr operation");
6921 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6922 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6923 // are compared, the result is true of the operator is <=, >= or ==, and
6924 // false otherwise.
6925 BinaryOperator::Opcode Opcode = E->getOpcode();
6926 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6927 }
6928
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006929 assert((!LHSTy->isIntegralOrEnumerationType() ||
6930 !RHSTy->isIntegralOrEnumerationType()) &&
6931 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6932 // We can't continue from here for non-integral types.
6933 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006934}
6935
Ken Dyck160146e2010-01-27 17:10:57 +00006936CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Richard Smithf6d70302014-06-10 23:34:28 +00006937 // C++ [expr.alignof]p3:
6938 // When alignof is applied to a reference type, the result is the
6939 // alignment of the referenced type.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006940 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6941 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006942
6943 // __alignof is defined to return the preferred alignment.
6944 return Info.Ctx.toCharUnitsFromBits(
6945 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006946}
6947
Ken Dyck160146e2010-01-27 17:10:57 +00006948CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006949 E = E->IgnoreParens();
6950
John McCall768439e2013-05-06 07:40:34 +00006951 // The kinds of expressions that we have special-case logic here for
6952 // should be kept up to date with the special checks for those
6953 // expressions in Sema.
6954
Chris Lattner68061312009-01-24 21:53:27 +00006955 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006956 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006957 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithf6d70302014-06-10 23:34:28 +00006958 return Info.Ctx.getDeclAlign(DRE->getDecl(),
Ken Dyck160146e2010-01-27 17:10:57 +00006959 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006960
Chris Lattner68061312009-01-24 21:53:27 +00006961 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006962 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6963 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006964
Chris Lattner24aeeab2009-01-24 21:09:06 +00006965 return GetAlignOfType(E->getType());
6966}
6967
6968
Peter Collingbournee190dee2011-03-11 19:24:49 +00006969/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6970/// a result as the expression's type.
6971bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6972 const UnaryExprOrTypeTraitExpr *E) {
6973 switch(E->getKind()) {
6974 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006975 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006976 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006977 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006978 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006979 }
Eli Friedman64004332009-03-23 04:38:34 +00006980
Peter Collingbournee190dee2011-03-11 19:24:49 +00006981 case UETT_VecStep: {
6982 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006983
Peter Collingbournee190dee2011-03-11 19:24:49 +00006984 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006985 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006986
Peter Collingbournee190dee2011-03-11 19:24:49 +00006987 // The vec_step built-in functions that take a 3-component
6988 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6989 if (n == 3)
6990 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006991
Peter Collingbournee190dee2011-03-11 19:24:49 +00006992 return Success(n, E);
6993 } else
6994 return Success(1, E);
6995 }
6996
6997 case UETT_SizeOf: {
6998 QualType SrcTy = E->getTypeOfArgument();
6999 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7000 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007001 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7002 SrcTy = Ref->getPointeeType();
7003
Richard Smithd62306a2011-11-10 06:34:14 +00007004 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007005 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007006 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007007 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007008 }
7009 }
7010
7011 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007012}
7013
Peter Collingbournee9200682011-05-13 03:29:01 +00007014bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007015 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007016 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007017 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007018 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007019 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007020 for (unsigned i = 0; i != n; ++i) {
7021 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7022 switch (ON.getKind()) {
7023 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007024 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007025 APSInt IdxResult;
7026 if (!EvaluateInteger(Idx, IdxResult, Info))
7027 return false;
7028 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7029 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007030 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007031 CurrentType = AT->getElementType();
7032 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7033 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007034 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007035 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007036
Douglas Gregor882211c2010-04-28 22:16:22 +00007037 case OffsetOfExpr::OffsetOfNode::Field: {
7038 FieldDecl *MemberDecl = ON.getField();
7039 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007040 if (!RT)
7041 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007042 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007043 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007044 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007045 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007046 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007047 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007048 CurrentType = MemberDecl->getType().getNonReferenceType();
7049 break;
7050 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007051
Douglas Gregor882211c2010-04-28 22:16:22 +00007052 case OffsetOfExpr::OffsetOfNode::Identifier:
7053 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007054
Douglas Gregord1702062010-04-29 00:18:15 +00007055 case OffsetOfExpr::OffsetOfNode::Base: {
7056 CXXBaseSpecifier *BaseSpec = ON.getBase();
7057 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007058 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007059
7060 // Find the layout of the class whose base we are looking into.
7061 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007062 if (!RT)
7063 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007064 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007065 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007066 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7067
7068 // Find the base class itself.
7069 CurrentType = BaseSpec->getType();
7070 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7071 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007072 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007073
7074 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007075 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007076 break;
7077 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007078 }
7079 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007080 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007081}
7082
Chris Lattnere13042c2008-07-11 19:10:17 +00007083bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007084 switch (E->getOpcode()) {
7085 default:
7086 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7087 // See C99 6.6p3.
7088 return Error(E);
7089 case UO_Extension:
7090 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7091 // If so, we could clear the diagnostic ID.
7092 return Visit(E->getSubExpr());
7093 case UO_Plus:
7094 // The result is just the value.
7095 return Visit(E->getSubExpr());
7096 case UO_Minus: {
7097 if (!Visit(E->getSubExpr()))
7098 return false;
7099 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007100 const APSInt &Value = Result.getInt();
7101 if (Value.isSigned() && Value.isMinSignedValue())
7102 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7103 E->getType());
7104 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007105 }
7106 case UO_Not: {
7107 if (!Visit(E->getSubExpr()))
7108 return false;
7109 if (!Result.isInt()) return Error(E);
7110 return Success(~Result.getInt(), E);
7111 }
7112 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007113 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007114 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007115 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007116 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007117 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007118 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007119}
Mike Stump11289f42009-09-09 15:08:12 +00007120
Chris Lattner477c4be2008-07-12 01:15:53 +00007121/// HandleCast - This is used to evaluate implicit or explicit casts where the
7122/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007123bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7124 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007125 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007126 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007127
Eli Friedmanc757de22011-03-25 00:43:55 +00007128 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007129 case CK_BaseToDerived:
7130 case CK_DerivedToBase:
7131 case CK_UncheckedDerivedToBase:
7132 case CK_Dynamic:
7133 case CK_ToUnion:
7134 case CK_ArrayToPointerDecay:
7135 case CK_FunctionToPointerDecay:
7136 case CK_NullToPointer:
7137 case CK_NullToMemberPointer:
7138 case CK_BaseToDerivedMemberPointer:
7139 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007140 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007141 case CK_ConstructorConversion:
7142 case CK_IntegralToPointer:
7143 case CK_ToVoid:
7144 case CK_VectorSplat:
7145 case CK_IntegralToFloating:
7146 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007147 case CK_CPointerToObjCPointerCast:
7148 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007149 case CK_AnyPointerToBlockPointerCast:
7150 case CK_ObjCObjectLValueCast:
7151 case CK_FloatingRealToComplex:
7152 case CK_FloatingComplexToReal:
7153 case CK_FloatingComplexCast:
7154 case CK_FloatingComplexToIntegralComplex:
7155 case CK_IntegralRealToComplex:
7156 case CK_IntegralComplexCast:
7157 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007158 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007159 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007160 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007161 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007162 llvm_unreachable("invalid cast kind for integral value");
7163
Eli Friedman9faf2f92011-03-25 19:07:11 +00007164 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007165 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007166 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007167 case CK_ARCProduceObject:
7168 case CK_ARCConsumeObject:
7169 case CK_ARCReclaimReturnedObject:
7170 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007171 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007172 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007173
Richard Smith4ef685b2012-01-17 21:17:26 +00007174 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007175 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007176 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007177 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007178 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007179
7180 case CK_MemberPointerToBoolean:
7181 case CK_PointerToBoolean:
7182 case CK_IntegralToBoolean:
7183 case CK_FloatingToBoolean:
7184 case CK_FloatingComplexToBoolean:
7185 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007186 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007187 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007188 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007189 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007190 }
7191
Eli Friedmanc757de22011-03-25 00:43:55 +00007192 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007193 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007194 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007195
Eli Friedman742421e2009-02-20 01:15:07 +00007196 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007197 // Allow casts of address-of-label differences if they are no-ops
7198 // or narrowing. (The narrowing case isn't actually guaranteed to
7199 // be constant-evaluatable except in some narrow cases which are hard
7200 // to detect here. We let it through on the assumption the user knows
7201 // what they are doing.)
7202 if (Result.isAddrLabelDiff())
7203 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007204 // Only allow casts of lvalues if they are lossless.
7205 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7206 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007207
Richard Smith911e1422012-01-30 22:27:01 +00007208 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7209 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007210 }
Mike Stump11289f42009-09-09 15:08:12 +00007211
Eli Friedmanc757de22011-03-25 00:43:55 +00007212 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007213 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7214
John McCall45d55e42010-05-07 21:00:08 +00007215 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007216 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007217 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007218
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007219 if (LV.getLValueBase()) {
7220 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007221 // FIXME: Allow a larger integer size than the pointer size, and allow
7222 // narrowing back down to pointer width in subsequent integral casts.
7223 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007224 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007225 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007226
Richard Smithcf74da72011-11-16 07:18:12 +00007227 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007228 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007229 return true;
7230 }
7231
Ken Dyck02990832010-01-15 12:37:54 +00007232 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7233 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007234 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007235 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007236
Eli Friedmanc757de22011-03-25 00:43:55 +00007237 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007238 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007239 if (!EvaluateComplex(SubExpr, C, Info))
7240 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007241 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007242 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007243
Eli Friedmanc757de22011-03-25 00:43:55 +00007244 case CK_FloatingToIntegral: {
7245 APFloat F(0.0);
7246 if (!EvaluateFloat(SubExpr, F, Info))
7247 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007248
Richard Smith357362d2011-12-13 06:39:58 +00007249 APSInt Value;
7250 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7251 return false;
7252 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007253 }
7254 }
Mike Stump11289f42009-09-09 15:08:12 +00007255
Eli Friedmanc757de22011-03-25 00:43:55 +00007256 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007257}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007258
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007259bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7260 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007261 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007262 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7263 return false;
7264 if (!LV.isComplexInt())
7265 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007266 return Success(LV.getComplexIntReal(), E);
7267 }
7268
7269 return Visit(E->getSubExpr());
7270}
7271
Eli Friedman4e7a2412009-02-27 04:45:43 +00007272bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007273 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007274 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007275 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7276 return false;
7277 if (!LV.isComplexInt())
7278 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007279 return Success(LV.getComplexIntImag(), E);
7280 }
7281
Richard Smith4a678122011-10-24 18:44:57 +00007282 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007283 return Success(0, E);
7284}
7285
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007286bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7287 return Success(E->getPackLength(), E);
7288}
7289
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007290bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7291 return Success(E->getValue(), E);
7292}
7293
Chris Lattner05706e882008-07-11 18:11:29 +00007294//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007295// Float Evaluation
7296//===----------------------------------------------------------------------===//
7297
7298namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007299class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007300 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007301 APFloat &Result;
7302public:
7303 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007304 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007305
Richard Smith2e312c82012-03-03 22:46:17 +00007306 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007307 Result = V.getFloat();
7308 return true;
7309 }
Eli Friedman24c01542008-08-22 00:06:13 +00007310
Richard Smithfddd3842011-12-30 21:15:51 +00007311 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007312 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7313 return true;
7314 }
7315
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007316 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007317
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007318 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007319 bool VisitBinaryOperator(const BinaryOperator *E);
7320 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007321 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007322
John McCallb1fb0d32010-05-07 22:08:54 +00007323 bool VisitUnaryReal(const UnaryOperator *E);
7324 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007325
Richard Smithfddd3842011-12-30 21:15:51 +00007326 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007327};
7328} // end anonymous namespace
7329
7330static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007331 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007332 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007333}
7334
Jay Foad39c79802011-01-12 09:06:06 +00007335static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007336 QualType ResultTy,
7337 const Expr *Arg,
7338 bool SNaN,
7339 llvm::APFloat &Result) {
7340 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7341 if (!S) return false;
7342
7343 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7344
7345 llvm::APInt fill;
7346
7347 // Treat empty strings as if they were zero.
7348 if (S->getString().empty())
7349 fill = llvm::APInt(32, 0);
7350 else if (S->getString().getAsInteger(0, fill))
7351 return false;
7352
7353 if (SNaN)
7354 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7355 else
7356 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7357 return true;
7358}
7359
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007360bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007361 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007362 default:
7363 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7364
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007365 case Builtin::BI__builtin_huge_val:
7366 case Builtin::BI__builtin_huge_valf:
7367 case Builtin::BI__builtin_huge_vall:
7368 case Builtin::BI__builtin_inf:
7369 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007370 case Builtin::BI__builtin_infl: {
7371 const llvm::fltSemantics &Sem =
7372 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007373 Result = llvm::APFloat::getInf(Sem);
7374 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007375 }
Mike Stump11289f42009-09-09 15:08:12 +00007376
John McCall16291492010-02-28 13:00:19 +00007377 case Builtin::BI__builtin_nans:
7378 case Builtin::BI__builtin_nansf:
7379 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007380 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7381 true, Result))
7382 return Error(E);
7383 return true;
John McCall16291492010-02-28 13:00:19 +00007384
Chris Lattner0b7282e2008-10-06 06:31:58 +00007385 case Builtin::BI__builtin_nan:
7386 case Builtin::BI__builtin_nanf:
7387 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007388 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007389 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007390 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7391 false, Result))
7392 return Error(E);
7393 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007394
7395 case Builtin::BI__builtin_fabs:
7396 case Builtin::BI__builtin_fabsf:
7397 case Builtin::BI__builtin_fabsl:
7398 if (!EvaluateFloat(E->getArg(0), Result, Info))
7399 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007400
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007401 if (Result.isNegative())
7402 Result.changeSign();
7403 return true;
7404
Richard Smith8889a3d2013-06-13 06:26:32 +00007405 // FIXME: Builtin::BI__builtin_powi
7406 // FIXME: Builtin::BI__builtin_powif
7407 // FIXME: Builtin::BI__builtin_powil
7408
Mike Stump11289f42009-09-09 15:08:12 +00007409 case Builtin::BI__builtin_copysign:
7410 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007411 case Builtin::BI__builtin_copysignl: {
7412 APFloat RHS(0.);
7413 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7414 !EvaluateFloat(E->getArg(1), RHS, Info))
7415 return false;
7416 Result.copySign(RHS);
7417 return true;
7418 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007419 }
7420}
7421
John McCallb1fb0d32010-05-07 22:08:54 +00007422bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007423 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7424 ComplexValue CV;
7425 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7426 return false;
7427 Result = CV.FloatReal;
7428 return true;
7429 }
7430
7431 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007432}
7433
7434bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007435 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7436 ComplexValue CV;
7437 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7438 return false;
7439 Result = CV.FloatImag;
7440 return true;
7441 }
7442
Richard Smith4a678122011-10-24 18:44:57 +00007443 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007444 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7445 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007446 return true;
7447}
7448
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007449bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007450 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007451 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007452 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007453 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007454 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007455 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7456 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007457 Result.changeSign();
7458 return true;
7459 }
7460}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007461
Eli Friedman24c01542008-08-22 00:06:13 +00007462bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007463 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7464 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007465
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007466 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007467 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7468 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007469 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007470 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7471 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007472}
7473
7474bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7475 Result = E->getValue();
7476 return true;
7477}
7478
Peter Collingbournee9200682011-05-13 03:29:01 +00007479bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7480 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007481
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007482 switch (E->getCastKind()) {
7483 default:
Richard Smith11562c52011-10-28 17:51:58 +00007484 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007485
7486 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007487 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007488 return EvaluateInteger(SubExpr, IntResult, Info) &&
7489 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7490 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007491 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007492
7493 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007494 if (!Visit(SubExpr))
7495 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007496 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7497 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007498 }
John McCalld7646252010-11-14 08:17:51 +00007499
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007500 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007501 ComplexValue V;
7502 if (!EvaluateComplex(SubExpr, V, Info))
7503 return false;
7504 Result = V.getComplexFloatReal();
7505 return true;
7506 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007507 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007508}
7509
Eli Friedman24c01542008-08-22 00:06:13 +00007510//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007511// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007512//===----------------------------------------------------------------------===//
7513
7514namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007515class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007516 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007517 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007518
Anders Carlsson537969c2008-11-16 20:27:53 +00007519public:
John McCall93d91dc2010-05-07 17:22:02 +00007520 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007521 : ExprEvaluatorBaseTy(info), Result(Result) {}
7522
Richard Smith2e312c82012-03-03 22:46:17 +00007523 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007524 Result.setFrom(V);
7525 return true;
7526 }
Mike Stump11289f42009-09-09 15:08:12 +00007527
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007528 bool ZeroInitialization(const Expr *E);
7529
Anders Carlsson537969c2008-11-16 20:27:53 +00007530 //===--------------------------------------------------------------------===//
7531 // Visitor Methods
7532 //===--------------------------------------------------------------------===//
7533
Peter Collingbournee9200682011-05-13 03:29:01 +00007534 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007535 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007536 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007537 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007538 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007539};
7540} // end anonymous namespace
7541
John McCall93d91dc2010-05-07 17:22:02 +00007542static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7543 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007544 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007545 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007546}
7547
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007548bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007549 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007550 if (ElemTy->isRealFloatingType()) {
7551 Result.makeComplexFloat();
7552 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7553 Result.FloatReal = Zero;
7554 Result.FloatImag = Zero;
7555 } else {
7556 Result.makeComplexInt();
7557 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7558 Result.IntReal = Zero;
7559 Result.IntImag = Zero;
7560 }
7561 return true;
7562}
7563
Peter Collingbournee9200682011-05-13 03:29:01 +00007564bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7565 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007566
7567 if (SubExpr->getType()->isRealFloatingType()) {
7568 Result.makeComplexFloat();
7569 APFloat &Imag = Result.FloatImag;
7570 if (!EvaluateFloat(SubExpr, Imag, Info))
7571 return false;
7572
7573 Result.FloatReal = APFloat(Imag.getSemantics());
7574 return true;
7575 } else {
7576 assert(SubExpr->getType()->isIntegerType() &&
7577 "Unexpected imaginary literal.");
7578
7579 Result.makeComplexInt();
7580 APSInt &Imag = Result.IntImag;
7581 if (!EvaluateInteger(SubExpr, Imag, Info))
7582 return false;
7583
7584 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7585 return true;
7586 }
7587}
7588
Peter Collingbournee9200682011-05-13 03:29:01 +00007589bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007590
John McCallfcef3cf2010-12-14 17:51:41 +00007591 switch (E->getCastKind()) {
7592 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007593 case CK_BaseToDerived:
7594 case CK_DerivedToBase:
7595 case CK_UncheckedDerivedToBase:
7596 case CK_Dynamic:
7597 case CK_ToUnion:
7598 case CK_ArrayToPointerDecay:
7599 case CK_FunctionToPointerDecay:
7600 case CK_NullToPointer:
7601 case CK_NullToMemberPointer:
7602 case CK_BaseToDerivedMemberPointer:
7603 case CK_DerivedToBaseMemberPointer:
7604 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007605 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007606 case CK_ConstructorConversion:
7607 case CK_IntegralToPointer:
7608 case CK_PointerToIntegral:
7609 case CK_PointerToBoolean:
7610 case CK_ToVoid:
7611 case CK_VectorSplat:
7612 case CK_IntegralCast:
7613 case CK_IntegralToBoolean:
7614 case CK_IntegralToFloating:
7615 case CK_FloatingToIntegral:
7616 case CK_FloatingToBoolean:
7617 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007618 case CK_CPointerToObjCPointerCast:
7619 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007620 case CK_AnyPointerToBlockPointerCast:
7621 case CK_ObjCObjectLValueCast:
7622 case CK_FloatingComplexToReal:
7623 case CK_FloatingComplexToBoolean:
7624 case CK_IntegralComplexToReal:
7625 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007626 case CK_ARCProduceObject:
7627 case CK_ARCConsumeObject:
7628 case CK_ARCReclaimReturnedObject:
7629 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007630 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007631 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007632 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007633 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007634 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007635 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007636
John McCallfcef3cf2010-12-14 17:51:41 +00007637 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007638 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007639 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007640 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007641
7642 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007643 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007644 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007645 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007646
7647 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007648 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007649 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007650 return false;
7651
John McCallfcef3cf2010-12-14 17:51:41 +00007652 Result.makeComplexFloat();
7653 Result.FloatImag = APFloat(Real.getSemantics());
7654 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007655 }
7656
John McCallfcef3cf2010-12-14 17:51:41 +00007657 case CK_FloatingComplexCast: {
7658 if (!Visit(E->getSubExpr()))
7659 return false;
7660
7661 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7662 QualType From
7663 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7664
Richard Smith357362d2011-12-13 06:39:58 +00007665 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7666 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007667 }
7668
7669 case CK_FloatingComplexToIntegralComplex: {
7670 if (!Visit(E->getSubExpr()))
7671 return false;
7672
7673 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7674 QualType From
7675 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7676 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007677 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7678 To, Result.IntReal) &&
7679 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7680 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007681 }
7682
7683 case CK_IntegralRealToComplex: {
7684 APSInt &Real = Result.IntReal;
7685 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7686 return false;
7687
7688 Result.makeComplexInt();
7689 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7690 return true;
7691 }
7692
7693 case CK_IntegralComplexCast: {
7694 if (!Visit(E->getSubExpr()))
7695 return false;
7696
7697 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7698 QualType From
7699 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7700
Richard Smith911e1422012-01-30 22:27:01 +00007701 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7702 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007703 return true;
7704 }
7705
7706 case CK_IntegralComplexToFloatingComplex: {
7707 if (!Visit(E->getSubExpr()))
7708 return false;
7709
Ted Kremenek28831752012-08-23 20:46:57 +00007710 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007711 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007712 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007713 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007714 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7715 To, Result.FloatReal) &&
7716 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7717 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007718 }
7719 }
7720
7721 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007722}
7723
John McCall93d91dc2010-05-07 17:22:02 +00007724bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007725 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007726 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7727
Richard Smith253c2a32012-01-27 01:14:48 +00007728 bool LHSOK = Visit(E->getLHS());
7729 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007730 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007731
John McCall93d91dc2010-05-07 17:22:02 +00007732 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007733 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007734 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007735
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007736 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7737 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007738 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007739 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007740 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007741 if (Result.isComplexFloat()) {
7742 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7743 APFloat::rmNearestTiesToEven);
7744 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7745 APFloat::rmNearestTiesToEven);
7746 } else {
7747 Result.getComplexIntReal() += RHS.getComplexIntReal();
7748 Result.getComplexIntImag() += RHS.getComplexIntImag();
7749 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007750 break;
John McCalle3027922010-08-25 11:45:40 +00007751 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007752 if (Result.isComplexFloat()) {
7753 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7754 APFloat::rmNearestTiesToEven);
7755 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7756 APFloat::rmNearestTiesToEven);
7757 } else {
7758 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7759 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7760 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007761 break;
John McCalle3027922010-08-25 11:45:40 +00007762 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007763 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007764 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007765 APFloat &LHS_r = LHS.getComplexFloatReal();
7766 APFloat &LHS_i = LHS.getComplexFloatImag();
7767 APFloat &RHS_r = RHS.getComplexFloatReal();
7768 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007769
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007770 APFloat Tmp = LHS_r;
7771 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7772 Result.getComplexFloatReal() = Tmp;
7773 Tmp = LHS_i;
7774 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7775 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7776
7777 Tmp = LHS_r;
7778 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7779 Result.getComplexFloatImag() = Tmp;
7780 Tmp = LHS_i;
7781 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7782 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7783 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007784 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007785 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007786 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7787 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007788 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007789 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7790 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7791 }
7792 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007793 case BO_Div:
7794 if (Result.isComplexFloat()) {
7795 ComplexValue LHS = Result;
7796 APFloat &LHS_r = LHS.getComplexFloatReal();
7797 APFloat &LHS_i = LHS.getComplexFloatImag();
7798 APFloat &RHS_r = RHS.getComplexFloatReal();
7799 APFloat &RHS_i = RHS.getComplexFloatImag();
7800 APFloat &Res_r = Result.getComplexFloatReal();
7801 APFloat &Res_i = Result.getComplexFloatImag();
7802
7803 APFloat Den = RHS_r;
7804 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7805 APFloat Tmp = RHS_i;
7806 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7807 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7808
7809 Res_r = LHS_r;
7810 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7811 Tmp = LHS_i;
7812 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7813 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7814 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7815
7816 Res_i = LHS_i;
7817 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7818 Tmp = LHS_r;
7819 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7820 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7821 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7822 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007823 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7824 return Error(E, diag::note_expr_divide_by_zero);
7825
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007826 ComplexValue LHS = Result;
7827 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7828 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7829 Result.getComplexIntReal() =
7830 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7831 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7832 Result.getComplexIntImag() =
7833 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7834 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7835 }
7836 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007837 }
7838
John McCall93d91dc2010-05-07 17:22:02 +00007839 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007840}
7841
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007842bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7843 // Get the operand value into 'Result'.
7844 if (!Visit(E->getSubExpr()))
7845 return false;
7846
7847 switch (E->getOpcode()) {
7848 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007849 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007850 case UO_Extension:
7851 return true;
7852 case UO_Plus:
7853 // The result is always just the subexpr.
7854 return true;
7855 case UO_Minus:
7856 if (Result.isComplexFloat()) {
7857 Result.getComplexFloatReal().changeSign();
7858 Result.getComplexFloatImag().changeSign();
7859 }
7860 else {
7861 Result.getComplexIntReal() = -Result.getComplexIntReal();
7862 Result.getComplexIntImag() = -Result.getComplexIntImag();
7863 }
7864 return true;
7865 case UO_Not:
7866 if (Result.isComplexFloat())
7867 Result.getComplexFloatImag().changeSign();
7868 else
7869 Result.getComplexIntImag() = -Result.getComplexIntImag();
7870 return true;
7871 }
7872}
7873
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007874bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7875 if (E->getNumInits() == 2) {
7876 if (E->getType()->isComplexType()) {
7877 Result.makeComplexFloat();
7878 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7879 return false;
7880 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7881 return false;
7882 } else {
7883 Result.makeComplexInt();
7884 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7885 return false;
7886 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7887 return false;
7888 }
7889 return true;
7890 }
7891 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7892}
7893
Anders Carlsson537969c2008-11-16 20:27:53 +00007894//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007895// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7896// implicit conversion.
7897//===----------------------------------------------------------------------===//
7898
7899namespace {
7900class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007901 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007902 APValue &Result;
7903public:
7904 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7905 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7906
7907 bool Success(const APValue &V, const Expr *E) {
7908 Result = V;
7909 return true;
7910 }
7911
7912 bool ZeroInitialization(const Expr *E) {
7913 ImplicitValueInitExpr VIE(
7914 E->getType()->castAs<AtomicType>()->getValueType());
7915 return Evaluate(Result, Info, &VIE);
7916 }
7917
7918 bool VisitCastExpr(const CastExpr *E) {
7919 switch (E->getCastKind()) {
7920 default:
7921 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7922 case CK_NonAtomicToAtomic:
7923 return Evaluate(Result, Info, E->getSubExpr());
7924 }
7925 }
7926};
7927} // end anonymous namespace
7928
7929static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7930 assert(E->isRValue() && E->getType()->isAtomicType());
7931 return AtomicExprEvaluator(Info, Result).Visit(E);
7932}
7933
7934//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007935// Void expression evaluation, primarily for a cast to void on the LHS of a
7936// comma operator
7937//===----------------------------------------------------------------------===//
7938
7939namespace {
7940class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007941 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00007942public:
7943 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7944
Richard Smith2e312c82012-03-03 22:46:17 +00007945 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007946
7947 bool VisitCastExpr(const CastExpr *E) {
7948 switch (E->getCastKind()) {
7949 default:
7950 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7951 case CK_ToVoid:
7952 VisitIgnoredValue(E->getSubExpr());
7953 return true;
7954 }
7955 }
7956};
7957} // end anonymous namespace
7958
7959static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7960 assert(E->isRValue() && E->getType()->isVoidType());
7961 return VoidExprEvaluator(Info).Visit(E);
7962}
7963
7964//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007965// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007966//===----------------------------------------------------------------------===//
7967
Richard Smith2e312c82012-03-03 22:46:17 +00007968static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007969 // In C, function designators are not lvalues, but we evaluate them as if they
7970 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007971 QualType T = E->getType();
7972 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007973 LValue LV;
7974 if (!EvaluateLValue(E, LV, Info))
7975 return false;
7976 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007977 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007978 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007979 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007980 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007981 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007982 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007983 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007984 LValue LV;
7985 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007986 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007987 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007988 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007989 llvm::APFloat F(0.0);
7990 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007991 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007992 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007993 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007994 ComplexValue C;
7995 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007996 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007997 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007998 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007999 MemberPtr P;
8000 if (!EvaluateMemberPointer(E, P, Info))
8001 return false;
8002 P.moveInto(Result);
8003 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008004 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008005 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008006 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008007 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8008 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008009 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008010 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008011 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008012 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008013 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008014 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8015 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008016 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008017 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008018 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008019 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008020 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008021 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008022 if (!EvaluateVoid(E, Info))
8023 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008024 } else if (T->isAtomicType()) {
8025 if (!EvaluateAtomic(E, Result, Info))
8026 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008027 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008028 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008029 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008030 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008031 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008032 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008033 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008034
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008035 return true;
8036}
8037
Richard Smithb228a862012-02-15 02:18:13 +00008038/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8039/// cases, the in-place evaluation is essential, since later initializers for
8040/// an object can indirectly refer to subobjects which were initialized earlier.
8041static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008042 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008043 assert(!E->isValueDependent());
8044
Richard Smith7525ff62013-05-09 07:14:00 +00008045 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008046 return false;
8047
8048 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008049 // Evaluate arrays and record types in-place, so that later initializers can
8050 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008051 if (E->getType()->isArrayType())
8052 return EvaluateArray(E, This, Result, Info);
8053 else if (E->getType()->isRecordType())
8054 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008055 }
8056
8057 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008058 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008059}
8060
Richard Smithf57d8cb2011-12-09 22:58:01 +00008061/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8062/// lvalue-to-rvalue cast if it is an lvalue.
8063static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008064 if (E->getType().isNull())
8065 return false;
8066
Richard Smithfddd3842011-12-30 21:15:51 +00008067 if (!CheckLiteralType(Info, E))
8068 return false;
8069
Richard Smith2e312c82012-03-03 22:46:17 +00008070 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008071 return false;
8072
8073 if (E->isGLValue()) {
8074 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008075 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008076 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008077 return false;
8078 }
8079
Richard Smith2e312c82012-03-03 22:46:17 +00008080 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008081 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008082}
Richard Smith11562c52011-10-28 17:51:58 +00008083
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008084static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8085 const ASTContext &Ctx, bool &IsConst) {
8086 // Fast-path evaluations of integer literals, since we sometimes see files
8087 // containing vast quantities of these.
8088 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8089 Result.Val = APValue(APSInt(L->getValue(),
8090 L->getType()->isUnsignedIntegerType()));
8091 IsConst = true;
8092 return true;
8093 }
James Dennett0492ef02014-03-14 17:44:10 +00008094
8095 // This case should be rare, but we need to check it before we check on
8096 // the type below.
8097 if (Exp->getType().isNull()) {
8098 IsConst = false;
8099 return true;
8100 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008101
8102 // FIXME: Evaluating values of large array and record types can cause
8103 // performance problems. Only do so in C++11 for now.
8104 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8105 Exp->getType()->isRecordType()) &&
8106 !Ctx.getLangOpts().CPlusPlus11) {
8107 IsConst = false;
8108 return true;
8109 }
8110 return false;
8111}
8112
8113
Richard Smith7b553f12011-10-29 00:50:52 +00008114/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008115/// any crazy technique (that has nothing to do with language standards) that
8116/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008117/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8118/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008119bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008120 bool IsConst;
8121 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8122 return IsConst;
8123
Richard Smith6d4c6582013-11-05 22:18:15 +00008124 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008125 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008126}
8127
Jay Foad39c79802011-01-12 09:06:06 +00008128bool Expr::EvaluateAsBooleanCondition(bool &Result,
8129 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008130 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008131 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008132 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008133}
8134
Richard Smith5fab0c92011-12-28 19:48:30 +00008135bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8136 SideEffectsKind AllowSideEffects) const {
8137 if (!getType()->isIntegralOrEnumerationType())
8138 return false;
8139
Richard Smith11562c52011-10-28 17:51:58 +00008140 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008141 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8142 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008144
Richard Smith11562c52011-10-28 17:51:58 +00008145 Result = ExprResult.Val.getInt();
8146 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008147}
8148
Jay Foad39c79802011-01-12 09:06:06 +00008149bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008150 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008151
John McCall45d55e42010-05-07 21:00:08 +00008152 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008153 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8154 !CheckLValueConstantExpression(Info, getExprLoc(),
8155 Ctx.getLValueReferenceType(getType()), LV))
8156 return false;
8157
Richard Smith2e312c82012-03-03 22:46:17 +00008158 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008159 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008160}
8161
Richard Smithd0b4dd62011-12-19 06:19:21 +00008162bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8163 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008164 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008165 // FIXME: Evaluating initializers for large array and record types can cause
8166 // performance problems. Only do so in C++11 for now.
8167 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008168 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008169 return false;
8170
Richard Smithd0b4dd62011-12-19 06:19:21 +00008171 Expr::EvalStatus EStatus;
8172 EStatus.Diag = &Notes;
8173
Richard Smith6d4c6582013-11-05 22:18:15 +00008174 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008175 InitInfo.setEvaluatingDecl(VD, Value);
8176
8177 LValue LVal;
8178 LVal.set(VD);
8179
Richard Smithfddd3842011-12-30 21:15:51 +00008180 // C++11 [basic.start.init]p2:
8181 // Variables with static storage duration or thread storage duration shall be
8182 // zero-initialized before any other initialization takes place.
8183 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008184 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008185 !VD->getType()->isReferenceType()) {
8186 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008187 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008188 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008189 return false;
8190 }
8191
Richard Smith7525ff62013-05-09 07:14:00 +00008192 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8193 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008194 EStatus.HasSideEffects)
8195 return false;
8196
8197 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8198 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008199}
8200
Richard Smith7b553f12011-10-29 00:50:52 +00008201/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8202/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008203bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008204 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008205 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008206}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008207
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008208APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008209 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008210 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008211 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008212 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008213 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008214 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008215 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008216
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008217 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008218}
John McCall864e3962010-05-07 05:32:02 +00008219
Richard Smithe9ff7702013-11-05 22:23:30 +00008220void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008221 bool IsConst;
8222 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008223 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008224 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008225 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8226 }
8227}
8228
Richard Smithe6c01442013-06-05 00:46:14 +00008229bool Expr::EvalResult::isGlobalLValue() const {
8230 assert(Val.isLValue());
8231 return IsGlobalLValue(Val.getLValueBase());
8232}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008233
8234
John McCall864e3962010-05-07 05:32:02 +00008235/// isIntegerConstantExpr - this recursive routine will test if an expression is
8236/// an integer constant expression.
8237
8238/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8239/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008240
8241// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008242// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8243// and a (possibly null) SourceLocation indicating the location of the problem.
8244//
John McCall864e3962010-05-07 05:32:02 +00008245// Note that to reduce code duplication, this helper does no evaluation
8246// itself; the caller checks whether the expression is evaluatable, and
8247// in the rare cases where CheckICE actually cares about the evaluated
8248// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008249
Dan Gohman28ade552010-07-26 21:25:24 +00008250namespace {
8251
Richard Smith9e575da2012-12-28 13:25:52 +00008252enum ICEKind {
8253 /// This expression is an ICE.
8254 IK_ICE,
8255 /// This expression is not an ICE, but if it isn't evaluated, it's
8256 /// a legal subexpression for an ICE. This return value is used to handle
8257 /// the comma operator in C99 mode, and non-constant subexpressions.
8258 IK_ICEIfUnevaluated,
8259 /// This expression is not an ICE, and is not a legal subexpression for one.
8260 IK_NotICE
8261};
8262
John McCall864e3962010-05-07 05:32:02 +00008263struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008264 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008265 SourceLocation Loc;
8266
Richard Smith9e575da2012-12-28 13:25:52 +00008267 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008268};
8269
Dan Gohman28ade552010-07-26 21:25:24 +00008270}
8271
Richard Smith9e575da2012-12-28 13:25:52 +00008272static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8273
8274static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008275
Craig Toppera31a8822013-08-22 07:09:37 +00008276static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008277 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008278 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008279 !EVResult.Val.isInt())
8280 return ICEDiag(IK_NotICE, E->getLocStart());
8281
John McCall864e3962010-05-07 05:32:02 +00008282 return NoDiag();
8283}
8284
Craig Toppera31a8822013-08-22 07:09:37 +00008285static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008286 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008287 if (!E->getType()->isIntegralOrEnumerationType())
8288 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008289
8290 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008291#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008292#define STMT(Node, Base) case Expr::Node##Class:
8293#define EXPR(Node, Base)
8294#include "clang/AST/StmtNodes.inc"
8295 case Expr::PredefinedExprClass:
8296 case Expr::FloatingLiteralClass:
8297 case Expr::ImaginaryLiteralClass:
8298 case Expr::StringLiteralClass:
8299 case Expr::ArraySubscriptExprClass:
8300 case Expr::MemberExprClass:
8301 case Expr::CompoundAssignOperatorClass:
8302 case Expr::CompoundLiteralExprClass:
8303 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008304 case Expr::DesignatedInitExprClass:
8305 case Expr::ImplicitValueInitExprClass:
8306 case Expr::ParenListExprClass:
8307 case Expr::VAArgExprClass:
8308 case Expr::AddrLabelExprClass:
8309 case Expr::StmtExprClass:
8310 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008311 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008312 case Expr::CXXDynamicCastExprClass:
8313 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008314 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008315 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008316 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008317 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008318 case Expr::CXXThisExprClass:
8319 case Expr::CXXThrowExprClass:
8320 case Expr::CXXNewExprClass:
8321 case Expr::CXXDeleteExprClass:
8322 case Expr::CXXPseudoDestructorExprClass:
8323 case Expr::UnresolvedLookupExprClass:
8324 case Expr::DependentScopeDeclRefExprClass:
8325 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008326 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008327 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008328 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008329 case Expr::CXXTemporaryObjectExprClass:
8330 case Expr::CXXUnresolvedConstructExprClass:
8331 case Expr::CXXDependentScopeMemberExprClass:
8332 case Expr::UnresolvedMemberExprClass:
8333 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008334 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008335 case Expr::ObjCArrayLiteralClass:
8336 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008337 case Expr::ObjCEncodeExprClass:
8338 case Expr::ObjCMessageExprClass:
8339 case Expr::ObjCSelectorExprClass:
8340 case Expr::ObjCProtocolExprClass:
8341 case Expr::ObjCIvarRefExprClass:
8342 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008343 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008344 case Expr::ObjCIsaExprClass:
8345 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008346 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008347 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008348 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008349 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008350 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008351 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008352 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008353 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008354 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008355 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008356 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008357 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008358 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008359 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008360
Richard Smithf137f932014-01-25 20:50:08 +00008361 case Expr::InitListExprClass: {
8362 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8363 // form "T x = { a };" is equivalent to "T x = a;".
8364 // Unless we're initializing a reference, T is a scalar as it is known to be
8365 // of integral or enumeration type.
8366 if (E->isRValue())
8367 if (cast<InitListExpr>(E)->getNumInits() == 1)
8368 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8369 return ICEDiag(IK_NotICE, E->getLocStart());
8370 }
8371
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008372 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008373 case Expr::GNUNullExprClass:
8374 // GCC considers the GNU __null value to be an integral constant expression.
8375 return NoDiag();
8376
John McCall7c454bb2011-07-15 05:09:51 +00008377 case Expr::SubstNonTypeTemplateParmExprClass:
8378 return
8379 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8380
John McCall864e3962010-05-07 05:32:02 +00008381 case Expr::ParenExprClass:
8382 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008383 case Expr::GenericSelectionExprClass:
8384 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008385 case Expr::IntegerLiteralClass:
8386 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008387 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008388 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008389 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008390 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008391 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008392 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008393 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008394 return NoDiag();
8395 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008396 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008397 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8398 // constant expressions, but they can never be ICEs because an ICE cannot
8399 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008400 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008401 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008402 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008403 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008404 }
Richard Smith6365c912012-02-24 22:12:32 +00008405 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008406 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8407 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008408 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008409 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008410 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008411 // Parameter variables are never constants. Without this check,
8412 // getAnyInitializer() can find a default argument, which leads
8413 // to chaos.
8414 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008415 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008416
8417 // C++ 7.1.5.1p2
8418 // A variable of non-volatile const-qualified integral or enumeration
8419 // type initialized by an ICE can be used in ICEs.
8420 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008421 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008422 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008423
Richard Smithd0b4dd62011-12-19 06:19:21 +00008424 const VarDecl *VD;
8425 // Look for a declaration of this variable that has an initializer, and
8426 // check whether it is an ICE.
8427 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8428 return NoDiag();
8429 else
Richard Smith9e575da2012-12-28 13:25:52 +00008430 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008431 }
8432 }
Richard Smith9e575da2012-12-28 13:25:52 +00008433 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008434 }
John McCall864e3962010-05-07 05:32:02 +00008435 case Expr::UnaryOperatorClass: {
8436 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8437 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008438 case UO_PostInc:
8439 case UO_PostDec:
8440 case UO_PreInc:
8441 case UO_PreDec:
8442 case UO_AddrOf:
8443 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008444 // C99 6.6/3 allows increment and decrement within unevaluated
8445 // subexpressions of constant expressions, but they can never be ICEs
8446 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008447 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008448 case UO_Extension:
8449 case UO_LNot:
8450 case UO_Plus:
8451 case UO_Minus:
8452 case UO_Not:
8453 case UO_Real:
8454 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008455 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008456 }
Richard Smith9e575da2012-12-28 13:25:52 +00008457
John McCall864e3962010-05-07 05:32:02 +00008458 // OffsetOf falls through here.
8459 }
8460 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008461 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8462 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8463 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8464 // compliance: we should warn earlier for offsetof expressions with
8465 // array subscripts that aren't ICEs, and if the array subscripts
8466 // are ICEs, the value of the offsetof must be an integer constant.
8467 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008468 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008469 case Expr::UnaryExprOrTypeTraitExprClass: {
8470 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8471 if ((Exp->getKind() == UETT_SizeOf) &&
8472 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008473 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008474 return NoDiag();
8475 }
8476 case Expr::BinaryOperatorClass: {
8477 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8478 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008479 case BO_PtrMemD:
8480 case BO_PtrMemI:
8481 case BO_Assign:
8482 case BO_MulAssign:
8483 case BO_DivAssign:
8484 case BO_RemAssign:
8485 case BO_AddAssign:
8486 case BO_SubAssign:
8487 case BO_ShlAssign:
8488 case BO_ShrAssign:
8489 case BO_AndAssign:
8490 case BO_XorAssign:
8491 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008492 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8493 // constant expressions, but they can never be ICEs because an ICE cannot
8494 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008495 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008496
John McCalle3027922010-08-25 11:45:40 +00008497 case BO_Mul:
8498 case BO_Div:
8499 case BO_Rem:
8500 case BO_Add:
8501 case BO_Sub:
8502 case BO_Shl:
8503 case BO_Shr:
8504 case BO_LT:
8505 case BO_GT:
8506 case BO_LE:
8507 case BO_GE:
8508 case BO_EQ:
8509 case BO_NE:
8510 case BO_And:
8511 case BO_Xor:
8512 case BO_Or:
8513 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008514 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008516 if (Exp->getOpcode() == BO_Div ||
8517 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008518 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008519 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008520 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008521 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008522 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008523 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008524 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008525 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008526 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008527 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008528 }
8529 }
8530 }
John McCalle3027922010-08-25 11:45:40 +00008531 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008532 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008533 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8534 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008535 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8536 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008537 } else {
8538 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008539 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008540 }
8541 }
Richard Smith9e575da2012-12-28 13:25:52 +00008542 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008543 }
John McCalle3027922010-08-25 11:45:40 +00008544 case BO_LAnd:
8545 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008546 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8547 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008548 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008549 // Rare case where the RHS has a comma "side-effect"; we need
8550 // to actually check the condition to see whether the side
8551 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008552 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008553 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008554 return RHSResult;
8555 return NoDiag();
8556 }
8557
Richard Smith9e575da2012-12-28 13:25:52 +00008558 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008559 }
8560 }
8561 }
8562 case Expr::ImplicitCastExprClass:
8563 case Expr::CStyleCastExprClass:
8564 case Expr::CXXFunctionalCastExprClass:
8565 case Expr::CXXStaticCastExprClass:
8566 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008567 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008568 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008569 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008570 if (isa<ExplicitCastExpr>(E)) {
8571 if (const FloatingLiteral *FL
8572 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8573 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8574 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8575 APSInt IgnoredVal(DestWidth, !DestSigned);
8576 bool Ignored;
8577 // If the value does not fit in the destination type, the behavior is
8578 // undefined, so we are not required to treat it as a constant
8579 // expression.
8580 if (FL->getValue().convertToInteger(IgnoredVal,
8581 llvm::APFloat::rmTowardZero,
8582 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008583 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008584 return NoDiag();
8585 }
8586 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008587 switch (cast<CastExpr>(E)->getCastKind()) {
8588 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008589 case CK_AtomicToNonAtomic:
8590 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008591 case CK_NoOp:
8592 case CK_IntegralToBoolean:
8593 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008594 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008595 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008596 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008597 }
John McCall864e3962010-05-07 05:32:02 +00008598 }
John McCallc07a0c72011-02-17 10:25:35 +00008599 case Expr::BinaryConditionalOperatorClass: {
8600 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8601 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008602 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008603 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008604 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8605 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8606 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008607 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008608 return FalseResult;
8609 }
John McCall864e3962010-05-07 05:32:02 +00008610 case Expr::ConditionalOperatorClass: {
8611 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8612 // If the condition (ignoring parens) is a __builtin_constant_p call,
8613 // then only the true side is actually considered in an integer constant
8614 // expression, and it is fully evaluated. This is an important GNU
8615 // extension. See GCC PR38377 for discussion.
8616 if (const CallExpr *CallCE
8617 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008618 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008619 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008620 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008621 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008622 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008623
Richard Smithf57d8cb2011-12-09 22:58:01 +00008624 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8625 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008626
Richard Smith9e575da2012-12-28 13:25:52 +00008627 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008628 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008629 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008630 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008631 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008632 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008633 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008634 return NoDiag();
8635 // Rare case where the diagnostics depend on which side is evaluated
8636 // Note that if we get here, CondResult is 0, and at least one of
8637 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008638 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008639 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008640 return TrueResult;
8641 }
8642 case Expr::CXXDefaultArgExprClass:
8643 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008644 case Expr::CXXDefaultInitExprClass:
8645 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008646 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008647 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008648 }
8649 }
8650
David Blaikiee4d798f2012-01-20 21:50:17 +00008651 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008652}
8653
Richard Smithf57d8cb2011-12-09 22:58:01 +00008654/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008655static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008656 const Expr *E,
8657 llvm::APSInt *Value,
8658 SourceLocation *Loc) {
8659 if (!E->getType()->isIntegralOrEnumerationType()) {
8660 if (Loc) *Loc = E->getExprLoc();
8661 return false;
8662 }
8663
Richard Smith66e05fe2012-01-18 05:21:49 +00008664 APValue Result;
8665 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008666 return false;
8667
Richard Smith66e05fe2012-01-18 05:21:49 +00008668 assert(Result.isInt() && "pointer cast to int is not an ICE");
8669 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008670 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008671}
8672
Craig Toppera31a8822013-08-22 07:09:37 +00008673bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8674 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008675 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008676 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008677
Richard Smith9e575da2012-12-28 13:25:52 +00008678 ICEDiag D = CheckICE(this, Ctx);
8679 if (D.Kind != IK_ICE) {
8680 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008681 return false;
8682 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008683 return true;
8684}
8685
Craig Toppera31a8822013-08-22 07:09:37 +00008686bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008687 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008688 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008689 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8690
8691 if (!isIntegerConstantExpr(Ctx, Loc))
8692 return false;
8693 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008694 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008695 return true;
8696}
Richard Smith66e05fe2012-01-18 05:21:49 +00008697
Craig Toppera31a8822013-08-22 07:09:37 +00008698bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008699 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008700}
8701
Craig Toppera31a8822013-08-22 07:09:37 +00008702bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008703 SourceLocation *Loc) const {
8704 // We support this checking in C++98 mode in order to diagnose compatibility
8705 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008706 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008707
Richard Smith98a0a492012-02-14 21:38:30 +00008708 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008709 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008710 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008711 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008712 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008713
8714 APValue Scratch;
8715 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8716
8717 if (!Diags.empty()) {
8718 IsConstExpr = false;
8719 if (Loc) *Loc = Diags[0].first;
8720 } else if (!IsConstExpr) {
8721 // FIXME: This shouldn't happen.
8722 if (Loc) *Loc = getExprLoc();
8723 }
8724
8725 return IsConstExpr;
8726}
Richard Smith253c2a32012-01-27 01:14:48 +00008727
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008728bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8729 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00008730 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008731 Expr::EvalStatus Status;
8732 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8733
8734 ArgVector ArgValues(Args.size());
8735 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8736 I != E; ++I) {
8737 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8738 // If evaluation fails, throw away the argument entirely.
8739 ArgValues[I - Args.begin()] = APValue();
8740 if (Info.EvalStatus.HasSideEffects)
8741 return false;
8742 }
8743
8744 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00008745 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008746 ArgValues.data());
8747 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8748}
8749
Richard Smith253c2a32012-01-27 01:14:48 +00008750bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008751 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008752 PartialDiagnosticAt> &Diags) {
8753 // FIXME: It would be useful to check constexpr function templates, but at the
8754 // moment the constant expression evaluator cannot cope with the non-rigorous
8755 // ASTs which we build for dependent expressions.
8756 if (FD->isDependentContext())
8757 return true;
8758
8759 Expr::EvalStatus Status;
8760 Status.Diag = &Diags;
8761
Richard Smith6d4c6582013-11-05 22:18:15 +00008762 EvalInfo Info(FD->getASTContext(), Status,
8763 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008764
8765 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00008766 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00008767
Richard Smith7525ff62013-05-09 07:14:00 +00008768 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008769 // is a temporary being used as the 'this' pointer.
8770 LValue This;
8771 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008772 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008773
Richard Smith253c2a32012-01-27 01:14:48 +00008774 ArrayRef<const Expr*> Args;
8775
8776 SourceLocation Loc = FD->getLocation();
8777
Richard Smith2e312c82012-03-03 22:46:17 +00008778 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008779 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8780 // Evaluate the call as a constant initializer, to allow the construction
8781 // of objects of non-literal types.
8782 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008783 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008784 } else
Craig Topper36250ad2014-05-12 05:36:57 +00008785 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00008786 Args, FD->getBody(), Info, Scratch);
8787
8788 return Diags.empty();
8789}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008790
8791bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8792 const FunctionDecl *FD,
8793 SmallVectorImpl<
8794 PartialDiagnosticAt> &Diags) {
8795 Expr::EvalStatus Status;
8796 Status.Diag = &Diags;
8797
8798 EvalInfo Info(FD->getASTContext(), Status,
8799 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8800
8801 // Fabricate a call stack frame to give the arguments a plausible cover story.
8802 ArrayRef<const Expr*> Args;
8803 ArgVector ArgValues(0);
8804 bool Success = EvaluateArgs(Args, ArgValues, Info);
8805 (void)Success;
8806 assert(Success &&
8807 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00008808 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008809
8810 APValue ResultScratch;
8811 Evaluate(ResultScratch, Info, E);
8812 return Diags.empty();
8813}