blob: 390cfe9cd2354d8755279ab330448c0492adba0c [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);
323 return I == Temporaries.end() ? 0 : &I->second;
324 }
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:
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
351
352 template<typename T>
353 OptionalDiagnostic &operator<<(const T &v) {
354 if (Diag)
355 *Diag << v;
356 return *this;
357 }
Richard Smithfe800032012-01-31 04:08:20 +0000358
359 OptionalDiagnostic &operator<<(const APSInt &I) {
360 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000361 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000362 I.toString(Buffer);
363 *Diag << StringRef(Buffer.data(), Buffer.size());
364 }
365 return *this;
366 }
367
368 OptionalDiagnostic &operator<<(const APFloat &F) {
369 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
376 unsigned precision =
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000379 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000380 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000381 *Diag << StringRef(Buffer.data(), Buffer.size());
382 }
383 return *this;
384 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000385 };
386
Richard Smith08d6a2c2013-07-24 07:11:57 +0000387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
388 class Cleanup {
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
390
391 public:
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
394
395 bool isLifetimeExtended() const { return Value.getInt(); }
396 void endLifetime() {
397 *Value.getPointer() = APValue();
398 }
399 };
400
Richard Smithb228a862012-02-15 02:18:13 +0000401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
404 /// expression.
405 ///
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
409 ///
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000415 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000416 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000417
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
420
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
423
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
426
Richard Smithb228a862012-02-15 02:18:13 +0000427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
429
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
433 unsigned StepsLeft;
434
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000435 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000436 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 CallStackFrame BottomFrame;
438
Richard Smith08d6a2c2013-07-24 07:11:57 +0000439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
442
Richard Smithd62306a2011-11-10 06:34:14 +0000443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000445 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000446
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
450
Richard Smith357362d2011-12-13 06:39:58 +0000451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
454
Richard Smith6d4c6582013-11-05 22:18:15 +0000455 enum EvaluationMode {
456 /// Evaluate as a constant expression. Stop if we find that the expression
457 /// is not a constant expression.
458 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000459
Richard Smith6d4c6582013-11-05 22:18:15 +0000460 /// Evaluate as a potential constant expression. Keep going if we hit a
461 /// construct that we can't evaluate yet (because we don't yet know the
462 /// value of something) but stop if we hit something that could never be
463 /// a constant expression.
464 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000465
Richard Smith6d4c6582013-11-05 22:18:15 +0000466 /// Fold the expression to a constant. Stop if we hit a side-effect that
467 /// we can't model.
468 EM_ConstantFold,
469
470 /// Evaluate the expression looking for integer overflow and similar
471 /// issues. Don't worry about side-effects, and try to visit all
472 /// subexpressions.
473 EM_EvaluateForOverflow,
474
475 /// Evaluate in any way we know how. Don't worry about side-effects that
476 /// can't be modeled.
477 EM_IgnoreSideEffects
478 } EvalMode;
479
480 /// Are we checking whether the expression is a potential constant
481 /// expression?
482 bool checkingPotentialConstantExpression() const {
483 return EvalMode == EM_PotentialConstantExpression;
484 }
485
486 /// Are we checking an expression for overflow?
487 // FIXME: We should check for any kind of undefined or suspicious behavior
488 // in such constructs, not just overflow.
489 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
490
491 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000493 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000494 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000495 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000496 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
Richard Smith6d4c6582013-11-05 22:18:15 +0000497 HasActiveDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000498
Richard Smith7525ff62013-05-09 07:14:00 +0000499 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
500 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000501 EvaluatingDeclValue = &Value;
502 }
503
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000505
Richard Smith357362d2011-12-13 06:39:58 +0000506 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000507 // Don't perform any constexpr calls (other than the call we're checking)
508 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000509 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000510 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000511 if (NextCallIndex == 0) {
512 // NextCallIndex has wrapped around.
513 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
514 return false;
515 }
Richard Smith357362d2011-12-13 06:39:58 +0000516 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
517 return true;
518 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
519 << getLangOpts().ConstexprCallDepth;
520 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000521 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000522
Richard Smithb228a862012-02-15 02:18:13 +0000523 CallStackFrame *getCallFrame(unsigned CallIndex) {
524 assert(CallIndex && "no call index in getCallFrame");
525 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
526 // be null in this loop.
527 CallStackFrame *Frame = CurrentCall;
528 while (Frame->Index > CallIndex)
529 Frame = Frame->Caller;
530 return (Frame->Index == CallIndex) ? Frame : 0;
531 }
532
Richard Smitha3d3bd22013-05-08 02:12:03 +0000533 bool nextStep(const Stmt *S) {
534 if (!StepsLeft) {
535 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
536 return false;
537 }
538 --StepsLeft;
539 return true;
540 }
541
Richard Smith357362d2011-12-13 06:39:58 +0000542 private:
543 /// Add a diagnostic to the diagnostics list.
544 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
545 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
546 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
547 return EvalStatus.Diag->back().second;
548 }
549
Richard Smithf6f003a2011-12-16 19:06:07 +0000550 /// Add notes containing a call stack to the current point of evaluation.
551 void addCallStack(unsigned Limit);
552
Richard Smith357362d2011-12-13 06:39:58 +0000553 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000554 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000555 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
556 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000557 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000558 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000559 // If we have a prior diagnostic, it will be noting that the expression
560 // isn't a constant expression. This diagnostic is more important,
561 // unless we require this evaluation to produce a constant expression.
562 //
563 // FIXME: We might want to show both diagnostics to the user in
564 // EM_ConstantFold mode.
565 if (!EvalStatus.Diag->empty()) {
566 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000567 case EM_ConstantFold:
568 case EM_IgnoreSideEffects:
569 case EM_EvaluateForOverflow:
570 if (!EvalStatus.HasSideEffects)
571 break;
572 // We've had side-effects; we want the diagnostic from them, not
573 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000574 case EM_ConstantExpression:
575 case EM_PotentialConstantExpression:
Richard Smith6d4c6582013-11-05 22:18:15 +0000576 HasActiveDiagnostic = false;
577 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000578 }
579 }
580
Richard Smithf6f003a2011-12-16 19:06:07 +0000581 unsigned CallStackNotes = CallStackDepth - 1;
582 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
583 if (Limit)
584 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000585 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000586 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000587
Richard Smith357362d2011-12-13 06:39:58 +0000588 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000589 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000590 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
591 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000592 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000593 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000594 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000595 }
Richard Smith357362d2011-12-13 06:39:58 +0000596 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000597 return OptionalDiagnostic();
598 }
599
Richard Smithce1ec5e2012-03-15 04:53:45 +0000600 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
601 = diag::note_invalid_subexpr_in_const_expr,
602 unsigned ExtraNotes = 0) {
603 if (EvalStatus.Diag)
604 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
605 HasActiveDiagnostic = false;
606 return OptionalDiagnostic();
607 }
608
Richard Smith92b1ce02011-12-12 09:28:41 +0000609 /// Diagnose that the evaluation does not produce a C++11 core constant
610 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 ///
612 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
613 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000614 template<typename LocArg>
615 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000616 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000617 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000618 // Don't override a previous diagnostic. Don't bother collecting
619 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000620 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000621 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000622 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000623 }
Richard Smith357362d2011-12-13 06:39:58 +0000624 return Diag(Loc, DiagId, ExtraNotes);
625 }
626
627 /// Add a note to a prior diagnostic.
628 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
629 if (!HasActiveDiagnostic)
630 return OptionalDiagnostic();
631 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000632 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000633
634 /// Add a stack of notes to a prior diagnostic.
635 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
636 if (HasActiveDiagnostic) {
637 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
638 Diags.begin(), Diags.end());
639 }
640 }
Richard Smith253c2a32012-01-27 01:14:48 +0000641
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 /// Should we continue evaluation after encountering a side-effect that we
643 /// couldn't model?
644 bool keepEvaluatingAfterSideEffect() {
645 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000646 case EM_PotentialConstantExpression:
Richard Smith6d4c6582013-11-05 22:18:15 +0000647 case EM_EvaluateForOverflow:
648 case EM_IgnoreSideEffects:
649 return true;
650
Richard Smith6d4c6582013-11-05 22:18:15 +0000651 case EM_ConstantExpression:
652 case EM_ConstantFold:
653 return false;
654 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000655 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000656 }
657
658 /// Note that we have had a side-effect, and determine whether we should
659 /// keep evaluating.
660 bool noteSideEffect() {
661 EvalStatus.HasSideEffects = true;
662 return keepEvaluatingAfterSideEffect();
663 }
664
Richard Smith253c2a32012-01-27 01:14:48 +0000665 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000667 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000668 if (!StepsLeft)
669 return false;
670
671 switch (EvalMode) {
672 case EM_PotentialConstantExpression:
673 case EM_EvaluateForOverflow:
674 return true;
675
676 case EM_ConstantExpression:
677 case EM_ConstantFold:
678 case EM_IgnoreSideEffects:
679 return false;
680 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000681 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000682 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000683 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000684
685 /// Object used to treat all foldable expressions as constant expressions.
686 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000687 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000688 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000689 bool HadNoPriorDiags;
690 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000691
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 explicit FoldConstant(EvalInfo &Info, bool Enabled)
693 : Info(Info),
694 Enabled(Enabled),
695 HadNoPriorDiags(Info.EvalStatus.Diag &&
696 Info.EvalStatus.Diag->empty() &&
697 !Info.EvalStatus.HasSideEffects),
698 OldMode(Info.EvalMode) {
699 if (Enabled && Info.EvalMode == EvalInfo::EM_ConstantExpression)
700 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000701 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 void keepDiagnostics() { Enabled = false; }
703 ~FoldConstant() {
704 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000705 !Info.EvalStatus.HasSideEffects)
706 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000708 }
709 };
Richard Smith17100ba2012-02-16 02:46:34 +0000710
711 /// RAII object used to suppress diagnostics and side-effects from a
712 /// speculative evaluation.
713 class SpeculativeEvaluationRAII {
714 EvalInfo &Info;
715 Expr::EvalStatus Old;
716
717 public:
718 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000719 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000720 : Info(Info), Old(Info.EvalStatus) {
721 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000722 // If we're speculatively evaluating, we may have skipped over some
723 // evaluations and missed out a side effect.
724 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000725 }
726 ~SpeculativeEvaluationRAII() {
727 Info.EvalStatus = Old;
728 }
729 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000730
731 /// RAII object wrapping a full-expression or block scope, and handling
732 /// the ending of the lifetime of temporaries created within it.
733 template<bool IsFullExpression>
734 class ScopeRAII {
735 EvalInfo &Info;
736 unsigned OldStackSize;
737 public:
738 ScopeRAII(EvalInfo &Info)
739 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
740 ~ScopeRAII() {
741 // Body moved to a static method to encourage the compiler to inline away
742 // instances of this class.
743 cleanup(Info, OldStackSize);
744 }
745 private:
746 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
747 unsigned NewEnd = OldStackSize;
748 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
749 I != N; ++I) {
750 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
751 // Full-expression cleanup of a lifetime-extended temporary: nothing
752 // to do, just move this cleanup to the right place in the stack.
753 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
754 ++NewEnd;
755 } else {
756 // End the lifetime of the object.
757 Info.CleanupStack[I].endLifetime();
758 }
759 }
760 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
761 Info.CleanupStack.end());
762 }
763 };
764 typedef ScopeRAII<false> BlockScopeRAII;
765 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000766}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000767
Richard Smitha8105bc2012-01-06 16:39:00 +0000768bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
769 CheckSubobjectKind CSK) {
770 if (Invalid)
771 return false;
772 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000774 << CSK;
775 setInvalid();
776 return false;
777 }
778 return true;
779}
780
781void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
782 const Expr *E, uint64_t N) {
783 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000784 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000785 << static_cast<int>(N) << /*array*/ 0
786 << static_cast<unsigned>(MostDerivedArraySize);
787 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000788 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000789 << static_cast<int>(N) << /*non-array*/ 1;
790 setInvalid();
791}
792
Richard Smithf6f003a2011-12-16 19:06:07 +0000793CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
794 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000795 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000796 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000797 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000798 Info.CurrentCall = this;
799 ++Info.CallStackDepth;
800}
801
802CallStackFrame::~CallStackFrame() {
803 assert(Info.CurrentCall == this && "calls retired out of order");
804 --Info.CallStackDepth;
805 Info.CurrentCall = Caller;
806}
807
Richard Smith08d6a2c2013-07-24 07:11:57 +0000808APValue &CallStackFrame::createTemporary(const void *Key,
809 bool IsLifetimeExtended) {
810 APValue &Result = Temporaries[Key];
811 assert(Result.isUninit() && "temporary created multiple times");
812 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
813 return Result;
814}
815
Richard Smith84401042013-06-03 05:03:02 +0000816static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000817
818void EvalInfo::addCallStack(unsigned Limit) {
819 // Determine which calls to skip, if any.
820 unsigned ActiveCalls = CallStackDepth - 1;
821 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
822 if (Limit && Limit < ActiveCalls) {
823 SkipStart = Limit / 2 + Limit % 2;
824 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000825 }
826
Richard Smithf6f003a2011-12-16 19:06:07 +0000827 // Walk the call stack and add the diagnostics.
828 unsigned CallIdx = 0;
829 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
830 Frame = Frame->Caller, ++CallIdx) {
831 // Skip this call?
832 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
833 if (CallIdx == SkipStart) {
834 // Note that we're skipping calls.
835 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
836 << unsigned(ActiveCalls - Limit);
837 }
838 continue;
839 }
840
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000841 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000842 llvm::raw_svector_ostream Out(Buffer);
843 describeCall(Frame, Out);
844 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
845 }
846}
847
848namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000849 struct ComplexValue {
850 private:
851 bool IsInt;
852
853 public:
854 APSInt IntReal, IntImag;
855 APFloat FloatReal, FloatImag;
856
857 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
858
859 void makeComplexFloat() { IsInt = false; }
860 bool isComplexFloat() const { return !IsInt; }
861 APFloat &getComplexFloatReal() { return FloatReal; }
862 APFloat &getComplexFloatImag() { return FloatImag; }
863
864 void makeComplexInt() { IsInt = true; }
865 bool isComplexInt() const { return IsInt; }
866 APSInt &getComplexIntReal() { return IntReal; }
867 APSInt &getComplexIntImag() { return IntImag; }
868
Richard Smith2e312c82012-03-03 22:46:17 +0000869 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000870 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000871 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000872 else
Richard Smith2e312c82012-03-03 22:46:17 +0000873 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000874 }
Richard Smith2e312c82012-03-03 22:46:17 +0000875 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000876 assert(v.isComplexFloat() || v.isComplexInt());
877 if (v.isComplexFloat()) {
878 makeComplexFloat();
879 FloatReal = v.getComplexFloatReal();
880 FloatImag = v.getComplexFloatImag();
881 } else {
882 makeComplexInt();
883 IntReal = v.getComplexIntReal();
884 IntImag = v.getComplexIntImag();
885 }
886 }
John McCall93d91dc2010-05-07 17:22:02 +0000887 };
John McCall45d55e42010-05-07 21:00:08 +0000888
889 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000890 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000891 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000892 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000893 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000894
Richard Smithce40ad62011-11-12 22:28:03 +0000895 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000896 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000897 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000898 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000899 SubobjectDesignator &getLValueDesignator() { return Designator; }
900 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000901
Richard Smith2e312c82012-03-03 22:46:17 +0000902 void moveInto(APValue &V) const {
903 if (Designator.Invalid)
904 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
905 else
906 V = APValue(Base, Offset, Designator.Entries,
907 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000908 }
Richard Smith2e312c82012-03-03 22:46:17 +0000909 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000910 assert(V.isLValue());
911 Base = V.getLValueBase();
912 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000913 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000914 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000915 }
916
Richard Smithb228a862012-02-15 02:18:13 +0000917 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000918 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000919 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000920 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000921 Designator = SubobjectDesignator(getType(B));
922 }
923
924 // Check that this LValue is not based on a null pointer. If it is, produce
925 // a diagnostic and mark the designator as invalid.
926 bool checkNullPointer(EvalInfo &Info, const Expr *E,
927 CheckSubobjectKind CSK) {
928 if (Designator.Invalid)
929 return false;
930 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000931 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000932 << CSK;
933 Designator.setInvalid();
934 return false;
935 }
936 return true;
937 }
938
939 // Check this LValue refers to an object. If not, set the designator to be
940 // invalid and emit a diagnostic.
941 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000942 // Outside C++11, do not build a designator referring to a subobject of
943 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000944 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000945 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000946 return checkNullPointer(Info, E, CSK) &&
947 Designator.checkSubobject(Info, E, CSK);
948 }
949
950 void addDecl(EvalInfo &Info, const Expr *E,
951 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000952 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
953 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000954 }
955 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000956 if (checkSubobject(Info, E, CSK_ArrayToPointer))
957 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000958 }
Richard Smith66c96992012-02-18 22:04:06 +0000959 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000960 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
961 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000962 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000963 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000964 if (checkNullPointer(Info, E, CSK_ArrayIndex))
965 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000966 }
John McCall45d55e42010-05-07 21:00:08 +0000967 };
Richard Smith027bf112011-11-17 22:56:20 +0000968
969 struct MemberPtr {
970 MemberPtr() {}
971 explicit MemberPtr(const ValueDecl *Decl) :
972 DeclAndIsDerivedMember(Decl, false), Path() {}
973
974 /// The member or (direct or indirect) field referred to by this member
975 /// pointer, or 0 if this is a null member pointer.
976 const ValueDecl *getDecl() const {
977 return DeclAndIsDerivedMember.getPointer();
978 }
979 /// Is this actually a member of some type derived from the relevant class?
980 bool isDerivedMember() const {
981 return DeclAndIsDerivedMember.getInt();
982 }
983 /// Get the class which the declaration actually lives in.
984 const CXXRecordDecl *getContainingRecord() const {
985 return cast<CXXRecordDecl>(
986 DeclAndIsDerivedMember.getPointer()->getDeclContext());
987 }
988
Richard Smith2e312c82012-03-03 22:46:17 +0000989 void moveInto(APValue &V) const {
990 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000991 }
Richard Smith2e312c82012-03-03 22:46:17 +0000992 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000993 assert(V.isMemberPointer());
994 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
995 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
996 Path.clear();
997 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
998 Path.insert(Path.end(), P.begin(), P.end());
999 }
1000
1001 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1002 /// whether the member is a member of some class derived from the class type
1003 /// of the member pointer.
1004 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1005 /// Path - The path of base/derived classes from the member declaration's
1006 /// class (exclusive) to the class type of the member pointer (inclusive).
1007 SmallVector<const CXXRecordDecl*, 4> Path;
1008
1009 /// Perform a cast towards the class of the Decl (either up or down the
1010 /// hierarchy).
1011 bool castBack(const CXXRecordDecl *Class) {
1012 assert(!Path.empty());
1013 const CXXRecordDecl *Expected;
1014 if (Path.size() >= 2)
1015 Expected = Path[Path.size() - 2];
1016 else
1017 Expected = getContainingRecord();
1018 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1019 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1020 // if B does not contain the original member and is not a base or
1021 // derived class of the class containing the original member, the result
1022 // of the cast is undefined.
1023 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1024 // (D::*). We consider that to be a language defect.
1025 return false;
1026 }
1027 Path.pop_back();
1028 return true;
1029 }
1030 /// Perform a base-to-derived member pointer cast.
1031 bool castToDerived(const CXXRecordDecl *Derived) {
1032 if (!getDecl())
1033 return true;
1034 if (!isDerivedMember()) {
1035 Path.push_back(Derived);
1036 return true;
1037 }
1038 if (!castBack(Derived))
1039 return false;
1040 if (Path.empty())
1041 DeclAndIsDerivedMember.setInt(false);
1042 return true;
1043 }
1044 /// Perform a derived-to-base member pointer cast.
1045 bool castToBase(const CXXRecordDecl *Base) {
1046 if (!getDecl())
1047 return true;
1048 if (Path.empty())
1049 DeclAndIsDerivedMember.setInt(true);
1050 if (isDerivedMember()) {
1051 Path.push_back(Base);
1052 return true;
1053 }
1054 return castBack(Base);
1055 }
1056 };
Richard Smith357362d2011-12-13 06:39:58 +00001057
Richard Smith7bb00672012-02-01 01:42:44 +00001058 /// Compare two member pointers, which are assumed to be of the same type.
1059 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1060 if (!LHS.getDecl() || !RHS.getDecl())
1061 return !LHS.getDecl() && !RHS.getDecl();
1062 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1063 return false;
1064 return LHS.Path == RHS.Path;
1065 }
John McCall93d91dc2010-05-07 17:22:02 +00001066}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001067
Richard Smith2e312c82012-03-03 22:46:17 +00001068static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001069static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1070 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001071 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001072static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1073static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001074static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1075 EvalInfo &Info);
1076static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001077static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001078static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001079 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001080static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001081static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001082static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001083
1084//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001085// Misc utilities
1086//===----------------------------------------------------------------------===//
1087
Richard Smith84401042013-06-03 05:03:02 +00001088/// Produce a string describing the given constexpr call.
1089static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1090 unsigned ArgIndex = 0;
1091 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1092 !isa<CXXConstructorDecl>(Frame->Callee) &&
1093 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1094
1095 if (!IsMemberCall)
1096 Out << *Frame->Callee << '(';
1097
1098 if (Frame->This && IsMemberCall) {
1099 APValue Val;
1100 Frame->This->moveInto(Val);
1101 Val.printPretty(Out, Frame->Info.Ctx,
1102 Frame->This->Designator.MostDerivedType);
1103 // FIXME: Add parens around Val if needed.
1104 Out << "->" << *Frame->Callee << '(';
1105 IsMemberCall = false;
1106 }
1107
1108 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1109 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1110 if (ArgIndex > (unsigned)IsMemberCall)
1111 Out << ", ";
1112
1113 const ParmVarDecl *Param = *I;
1114 const APValue &Arg = Frame->Arguments[ArgIndex];
1115 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1116
1117 if (ArgIndex == 0 && IsMemberCall)
1118 Out << "->" << *Frame->Callee << '(';
1119 }
1120
1121 Out << ')';
1122}
1123
Richard Smithd9f663b2013-04-22 15:31:51 +00001124/// Evaluate an expression to see if it had side-effects, and discard its
1125/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001126/// \return \c true if the caller should keep evaluating.
1127static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001128 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001129 if (!Evaluate(Scratch, Info, E))
1130 // We don't need the value, but we might have skipped a side effect here.
1131 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001132 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001133}
1134
Richard Smith861b5b52013-05-07 23:34:45 +00001135/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1136/// return its existing value.
1137static int64_t getExtValue(const APSInt &Value) {
1138 return Value.isSigned() ? Value.getSExtValue()
1139 : static_cast<int64_t>(Value.getZExtValue());
1140}
1141
Richard Smithd62306a2011-11-10 06:34:14 +00001142/// Should this call expression be treated as a string literal?
1143static bool IsStringLiteralCall(const CallExpr *E) {
1144 unsigned Builtin = E->isBuiltinCall();
1145 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1146 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1147}
1148
Richard Smithce40ad62011-11-12 22:28:03 +00001149static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001150 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1151 // constant expression of pointer type that evaluates to...
1152
1153 // ... a null pointer value, or a prvalue core constant expression of type
1154 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001155 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001156
Richard Smithce40ad62011-11-12 22:28:03 +00001157 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1158 // ... the address of an object with static storage duration,
1159 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1160 return VD->hasGlobalStorage();
1161 // ... the address of a function,
1162 return isa<FunctionDecl>(D);
1163 }
1164
1165 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001166 switch (E->getStmtClass()) {
1167 default:
1168 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001169 case Expr::CompoundLiteralExprClass: {
1170 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1171 return CLE->isFileScope() && CLE->isLValue();
1172 }
Richard Smithe6c01442013-06-05 00:46:14 +00001173 case Expr::MaterializeTemporaryExprClass:
1174 // A materialized temporary might have been lifetime-extended to static
1175 // storage duration.
1176 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001177 // A string literal has static storage duration.
1178 case Expr::StringLiteralClass:
1179 case Expr::PredefinedExprClass:
1180 case Expr::ObjCStringLiteralClass:
1181 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001182 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001183 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001184 return true;
1185 case Expr::CallExprClass:
1186 return IsStringLiteralCall(cast<CallExpr>(E));
1187 // For GCC compatibility, &&label has static storage duration.
1188 case Expr::AddrLabelExprClass:
1189 return true;
1190 // A Block literal expression may be used as the initialization value for
1191 // Block variables at global or local static scope.
1192 case Expr::BlockExprClass:
1193 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001194 case Expr::ImplicitValueInitExprClass:
1195 // FIXME:
1196 // We can never form an lvalue with an implicit value initialization as its
1197 // base through expression evaluation, so these only appear in one case: the
1198 // implicit variable declaration we invent when checking whether a constexpr
1199 // constructor can produce a constant expression. We must assume that such
1200 // an expression might be a global lvalue.
1201 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001202 }
John McCall95007602010-05-10 23:27:23 +00001203}
1204
Richard Smithb228a862012-02-15 02:18:13 +00001205static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1206 assert(Base && "no location for a null lvalue");
1207 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1208 if (VD)
1209 Info.Note(VD->getLocation(), diag::note_declared_at);
1210 else
Ted Kremenek28831752012-08-23 20:46:57 +00001211 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001212 diag::note_constexpr_temporary_here);
1213}
1214
Richard Smith80815602011-11-07 05:07:52 +00001215/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001216/// value for an address or reference constant expression. Return true if we
1217/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001218static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1219 QualType Type, const LValue &LVal) {
1220 bool IsReferenceType = Type->isReferenceType();
1221
Richard Smith357362d2011-12-13 06:39:58 +00001222 APValue::LValueBase Base = LVal.getLValueBase();
1223 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1224
Richard Smith0dea49e2012-02-18 04:58:18 +00001225 // Check that the object is a global. Note that the fake 'this' object we
1226 // manufacture when checking potential constant expressions is conservatively
1227 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001228 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001229 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001230 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001231 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1232 << IsReferenceType << !Designator.Entries.empty()
1233 << !!VD << VD;
1234 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001235 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001236 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001237 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001238 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001241 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001242 LVal.getLValueCallIndex() == 0) &&
1243 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001244
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001245 // Check if this is a thread-local variable.
1246 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1247 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001248 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001249 return false;
1250 }
1251 }
1252
Richard Smitha8105bc2012-01-06 16:39:00 +00001253 // Allow address constant expressions to be past-the-end pointers. This is
1254 // an extension: the standard requires them to point to an object.
1255 if (!IsReferenceType)
1256 return true;
1257
1258 // A reference constant expression must refer to an object.
1259 if (!Base) {
1260 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001261 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001262 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001263 }
1264
Richard Smith357362d2011-12-13 06:39:58 +00001265 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001266 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001267 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001268 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001269 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001270 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001271 }
1272
Richard Smith80815602011-11-07 05:07:52 +00001273 return true;
1274}
1275
Richard Smithfddd3842011-12-30 21:15:51 +00001276/// Check that this core constant expression is of literal type, and if not,
1277/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001278static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1279 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001280 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001281 return true;
1282
Richard Smith7525ff62013-05-09 07:14:00 +00001283 // C++1y: A constant initializer for an object o [...] may also invoke
1284 // constexpr constructors for o and its subobjects even if those objects
1285 // are of non-literal class types.
1286 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001287 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001288 return true;
1289
Richard Smithfddd3842011-12-30 21:15:51 +00001290 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001291 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001292 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001293 << E->getType();
1294 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001295 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001296 return false;
1297}
1298
Richard Smith0b0a0b62011-10-29 20:57:55 +00001299/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001300/// constant expression. If not, report an appropriate diagnostic. Does not
1301/// check that the expression is of literal type.
1302static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1303 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001304 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001305 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1306 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001307 return false;
1308 }
1309
Richard Smithb228a862012-02-15 02:18:13 +00001310 // Core issue 1454: For a literal constant expression of array or class type,
1311 // each subobject of its value shall have been initialized by a constant
1312 // expression.
1313 if (Value.isArray()) {
1314 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1315 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1316 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1317 Value.getArrayInitializedElt(I)))
1318 return false;
1319 }
1320 if (!Value.hasArrayFiller())
1321 return true;
1322 return CheckConstantExpression(Info, DiagLoc, EltTy,
1323 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001324 }
Richard Smithb228a862012-02-15 02:18:13 +00001325 if (Value.isUnion() && Value.getUnionField()) {
1326 return CheckConstantExpression(Info, DiagLoc,
1327 Value.getUnionField()->getType(),
1328 Value.getUnionValue());
1329 }
1330 if (Value.isStruct()) {
1331 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1332 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1333 unsigned BaseIndex = 0;
1334 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1335 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1336 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1337 Value.getStructBase(BaseIndex)))
1338 return false;
1339 }
1340 }
1341 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1342 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001343 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1344 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001345 return false;
1346 }
1347 }
1348
1349 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001350 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001351 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001352 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1353 }
1354
1355 // Everything else is fine.
1356 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001357}
1358
Richard Smith83c68212011-10-31 05:11:32 +00001359const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001360 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001361}
1362
1363static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001364 if (Value.CallIndex)
1365 return false;
1366 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1367 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001368}
1369
Richard Smithcecf1842011-11-01 21:06:14 +00001370static bool IsWeakLValue(const LValue &Value) {
1371 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001372 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001373}
1374
Richard Smith2e312c82012-03-03 22:46:17 +00001375static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001376 // A null base expression indicates a null pointer. These are always
1377 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001378 if (!Value.getLValueBase()) {
1379 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001380 return true;
1381 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001382
Richard Smith027bf112011-11-17 22:56:20 +00001383 // We have a non-null base. These are generally known to be true, but if it's
1384 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001385 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001386 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001387 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001388}
1389
Richard Smith2e312c82012-03-03 22:46:17 +00001390static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001391 switch (Val.getKind()) {
1392 case APValue::Uninitialized:
1393 return false;
1394 case APValue::Int:
1395 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001396 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001397 case APValue::Float:
1398 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001399 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001400 case APValue::ComplexInt:
1401 Result = Val.getComplexIntReal().getBoolValue() ||
1402 Val.getComplexIntImag().getBoolValue();
1403 return true;
1404 case APValue::ComplexFloat:
1405 Result = !Val.getComplexFloatReal().isZero() ||
1406 !Val.getComplexFloatImag().isZero();
1407 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001408 case APValue::LValue:
1409 return EvalPointerValueAsBool(Val, Result);
1410 case APValue::MemberPointer:
1411 Result = Val.getMemberPointerDecl();
1412 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001413 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001414 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001415 case APValue::Struct:
1416 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001417 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001418 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001419 }
1420
Richard Smith11562c52011-10-28 17:51:58 +00001421 llvm_unreachable("unknown APValue kind");
1422}
1423
1424static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1425 EvalInfo &Info) {
1426 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001427 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001428 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001429 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001430 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001431}
1432
Richard Smith357362d2011-12-13 06:39:58 +00001433template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001434static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001435 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001436 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001437 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001438}
1439
1440static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1441 QualType SrcType, const APFloat &Value,
1442 QualType DestType, APSInt &Result) {
1443 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001444 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001445 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001446
Richard Smith357362d2011-12-13 06:39:58 +00001447 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001448 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001449 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1450 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001451 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001452 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001453}
1454
Richard Smith357362d2011-12-13 06:39:58 +00001455static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1456 QualType SrcType, QualType DestType,
1457 APFloat &Result) {
1458 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001459 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001460 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1461 APFloat::rmNearestTiesToEven, &ignored)
1462 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001463 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001464 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001465}
1466
Richard Smith911e1422012-01-30 22:27:01 +00001467static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1468 QualType DestType, QualType SrcType,
1469 APSInt &Value) {
1470 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001471 APSInt Result = Value;
1472 // Figure out if this is a truncate, extend or noop cast.
1473 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001474 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001475 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001476 return Result;
1477}
1478
Richard Smith357362d2011-12-13 06:39:58 +00001479static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1480 QualType SrcType, const APSInt &Value,
1481 QualType DestType, APFloat &Result) {
1482 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1483 if (Result.convertFromAPInt(Value, Value.isSigned(),
1484 APFloat::rmNearestTiesToEven)
1485 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001486 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001487 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001488}
1489
Richard Smith49ca8aa2013-08-06 07:09:20 +00001490static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1491 APValue &Value, const FieldDecl *FD) {
1492 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1493
1494 if (!Value.isInt()) {
1495 // Trying to store a pointer-cast-to-integer into a bitfield.
1496 // FIXME: In this case, we should provide the diagnostic for casting
1497 // a pointer to an integer.
1498 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1499 Info.Diag(E);
1500 return false;
1501 }
1502
1503 APSInt &Int = Value.getInt();
1504 unsigned OldBitWidth = Int.getBitWidth();
1505 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1506 if (NewBitWidth < OldBitWidth)
1507 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1508 return true;
1509}
1510
Eli Friedman803acb32011-12-22 03:51:45 +00001511static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1512 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001513 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001514 if (!Evaluate(SVal, Info, E))
1515 return false;
1516 if (SVal.isInt()) {
1517 Res = SVal.getInt();
1518 return true;
1519 }
1520 if (SVal.isFloat()) {
1521 Res = SVal.getFloat().bitcastToAPInt();
1522 return true;
1523 }
1524 if (SVal.isVector()) {
1525 QualType VecTy = E->getType();
1526 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1527 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1528 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1529 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1530 Res = llvm::APInt::getNullValue(VecSize);
1531 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1532 APValue &Elt = SVal.getVectorElt(i);
1533 llvm::APInt EltAsInt;
1534 if (Elt.isInt()) {
1535 EltAsInt = Elt.getInt();
1536 } else if (Elt.isFloat()) {
1537 EltAsInt = Elt.getFloat().bitcastToAPInt();
1538 } else {
1539 // Don't try to handle vectors of anything other than int or float
1540 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001541 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001542 return false;
1543 }
1544 unsigned BaseEltSize = EltAsInt.getBitWidth();
1545 if (BigEndian)
1546 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1547 else
1548 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1549 }
1550 return true;
1551 }
1552 // Give up if the input isn't an int, float, or vector. For example, we
1553 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001554 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001555 return false;
1556}
1557
Richard Smith43e77732013-05-07 04:50:00 +00001558/// Perform the given integer operation, which is known to need at most BitWidth
1559/// bits, and check for overflow in the original type (if that type was not an
1560/// unsigned type).
1561template<typename Operation>
1562static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1563 const APSInt &LHS, const APSInt &RHS,
1564 unsigned BitWidth, Operation Op) {
1565 if (LHS.isUnsigned())
1566 return Op(LHS, RHS);
1567
1568 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1569 APSInt Result = Value.trunc(LHS.getBitWidth());
1570 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001571 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001572 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1573 diag::warn_integer_constant_overflow)
1574 << Result.toString(10) << E->getType();
1575 else
1576 HandleOverflow(Info, E, Value, E->getType());
1577 }
1578 return Result;
1579}
1580
1581/// Perform the given binary integer operation.
1582static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1583 BinaryOperatorKind Opcode, APSInt RHS,
1584 APSInt &Result) {
1585 switch (Opcode) {
1586 default:
1587 Info.Diag(E);
1588 return false;
1589 case BO_Mul:
1590 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1591 std::multiplies<APSInt>());
1592 return true;
1593 case BO_Add:
1594 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1595 std::plus<APSInt>());
1596 return true;
1597 case BO_Sub:
1598 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1599 std::minus<APSInt>());
1600 return true;
1601 case BO_And: Result = LHS & RHS; return true;
1602 case BO_Xor: Result = LHS ^ RHS; return true;
1603 case BO_Or: Result = LHS | RHS; return true;
1604 case BO_Div:
1605 case BO_Rem:
1606 if (RHS == 0) {
1607 Info.Diag(E, diag::note_expr_divide_by_zero);
1608 return false;
1609 }
1610 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1611 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1612 LHS.isSigned() && LHS.isMinSignedValue())
1613 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1614 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1615 return true;
1616 case BO_Shl: {
1617 if (Info.getLangOpts().OpenCL)
1618 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1619 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1620 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1621 RHS.isUnsigned());
1622 else if (RHS.isSigned() && RHS.isNegative()) {
1623 // During constant-folding, a negative shift is an opposite shift. Such
1624 // a shift is not a constant expression.
1625 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1626 RHS = -RHS;
1627 goto shift_right;
1628 }
1629 shift_left:
1630 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1631 // the shifted type.
1632 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1633 if (SA != RHS) {
1634 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1635 << RHS << E->getType() << LHS.getBitWidth();
1636 } else if (LHS.isSigned()) {
1637 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1638 // operand, and must not overflow the corresponding unsigned type.
1639 if (LHS.isNegative())
1640 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1641 else if (LHS.countLeadingZeros() < SA)
1642 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1643 }
1644 Result = LHS << SA;
1645 return true;
1646 }
1647 case BO_Shr: {
1648 if (Info.getLangOpts().OpenCL)
1649 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1650 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1651 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1652 RHS.isUnsigned());
1653 else if (RHS.isSigned() && RHS.isNegative()) {
1654 // During constant-folding, a negative shift is an opposite shift. Such a
1655 // shift is not a constant expression.
1656 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1657 RHS = -RHS;
1658 goto shift_left;
1659 }
1660 shift_right:
1661 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1662 // shifted type.
1663 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1664 if (SA != RHS)
1665 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1666 << RHS << E->getType() << LHS.getBitWidth();
1667 Result = LHS >> SA;
1668 return true;
1669 }
1670
1671 case BO_LT: Result = LHS < RHS; return true;
1672 case BO_GT: Result = LHS > RHS; return true;
1673 case BO_LE: Result = LHS <= RHS; return true;
1674 case BO_GE: Result = LHS >= RHS; return true;
1675 case BO_EQ: Result = LHS == RHS; return true;
1676 case BO_NE: Result = LHS != RHS; return true;
1677 }
1678}
1679
Richard Smith861b5b52013-05-07 23:34:45 +00001680/// Perform the given binary floating-point operation, in-place, on LHS.
1681static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1682 APFloat &LHS, BinaryOperatorKind Opcode,
1683 const APFloat &RHS) {
1684 switch (Opcode) {
1685 default:
1686 Info.Diag(E);
1687 return false;
1688 case BO_Mul:
1689 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1690 break;
1691 case BO_Add:
1692 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1693 break;
1694 case BO_Sub:
1695 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1696 break;
1697 case BO_Div:
1698 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1699 break;
1700 }
1701
1702 if (LHS.isInfinity() || LHS.isNaN())
1703 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1704 return true;
1705}
1706
Richard Smitha8105bc2012-01-06 16:39:00 +00001707/// Cast an lvalue referring to a base subobject to a derived class, by
1708/// truncating the lvalue's path to the given length.
1709static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1710 const RecordDecl *TruncatedType,
1711 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001712 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001713
1714 // Check we actually point to a derived class object.
1715 if (TruncatedElements == D.Entries.size())
1716 return true;
1717 assert(TruncatedElements >= D.MostDerivedPathLength &&
1718 "not casting to a derived class");
1719 if (!Result.checkSubobject(Info, E, CSK_Derived))
1720 return false;
1721
1722 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001723 const RecordDecl *RD = TruncatedType;
1724 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001725 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001726 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1727 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001728 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001729 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001730 else
Richard Smithd62306a2011-11-10 06:34:14 +00001731 Result.Offset -= Layout.getBaseClassOffset(Base);
1732 RD = Base;
1733 }
Richard Smith027bf112011-11-17 22:56:20 +00001734 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001735 return true;
1736}
1737
John McCalld7bca762012-05-01 00:38:49 +00001738static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001739 const CXXRecordDecl *Derived,
1740 const CXXRecordDecl *Base,
1741 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001742 if (!RL) {
1743 if (Derived->isInvalidDecl()) return false;
1744 RL = &Info.Ctx.getASTRecordLayout(Derived);
1745 }
1746
Richard Smithd62306a2011-11-10 06:34:14 +00001747 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001748 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001749 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001750}
1751
Richard Smitha8105bc2012-01-06 16:39:00 +00001752static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001753 const CXXRecordDecl *DerivedDecl,
1754 const CXXBaseSpecifier *Base) {
1755 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1756
John McCalld7bca762012-05-01 00:38:49 +00001757 if (!Base->isVirtual())
1758 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001759
Richard Smitha8105bc2012-01-06 16:39:00 +00001760 SubobjectDesignator &D = Obj.Designator;
1761 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001762 return false;
1763
Richard Smitha8105bc2012-01-06 16:39:00 +00001764 // Extract most-derived object and corresponding type.
1765 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1766 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1767 return false;
1768
1769 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001770 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1772 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001773 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001774 return true;
1775}
1776
Richard Smith84401042013-06-03 05:03:02 +00001777static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1778 QualType Type, LValue &Result) {
1779 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1780 PathE = E->path_end();
1781 PathI != PathE; ++PathI) {
1782 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1783 *PathI))
1784 return false;
1785 Type = (*PathI)->getType();
1786 }
1787 return true;
1788}
1789
Richard Smithd62306a2011-11-10 06:34:14 +00001790/// Update LVal to refer to the given field, which must be a member of the type
1791/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001792static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001793 const FieldDecl *FD,
1794 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001795 if (!RL) {
1796 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001797 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001798 }
Richard Smithd62306a2011-11-10 06:34:14 +00001799
1800 unsigned I = FD->getFieldIndex();
1801 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001802 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001803 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001804}
1805
Richard Smith1b78b3d2012-01-25 22:15:11 +00001806/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001807static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001808 LValue &LVal,
1809 const IndirectFieldDecl *IFD) {
1810 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1811 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001812 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1813 return false;
1814 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001815}
1816
Richard Smithd62306a2011-11-10 06:34:14 +00001817/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001818static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1819 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001820 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1821 // extension.
1822 if (Type->isVoidType() || Type->isFunctionType()) {
1823 Size = CharUnits::One();
1824 return true;
1825 }
1826
1827 if (!Type->isConstantSizeType()) {
1828 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001829 // FIXME: Better diagnostic.
1830 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001831 return false;
1832 }
1833
1834 Size = Info.Ctx.getTypeSizeInChars(Type);
1835 return true;
1836}
1837
1838/// Update a pointer value to model pointer arithmetic.
1839/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001840/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001841/// \param LVal - The pointer value to be updated.
1842/// \param EltTy - The pointee type represented by LVal.
1843/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001844static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1845 LValue &LVal, QualType EltTy,
1846 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001847 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001848 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001849 return false;
1850
1851 // Compute the new offset in the appropriate width.
1852 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001853 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001854 return true;
1855}
1856
Richard Smith66c96992012-02-18 22:04:06 +00001857/// Update an lvalue to refer to a component of a complex number.
1858/// \param Info - Information about the ongoing evaluation.
1859/// \param LVal - The lvalue to be updated.
1860/// \param EltTy - The complex number's component type.
1861/// \param Imag - False for the real component, true for the imaginary.
1862static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1863 LValue &LVal, QualType EltTy,
1864 bool Imag) {
1865 if (Imag) {
1866 CharUnits SizeOfComponent;
1867 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1868 return false;
1869 LVal.Offset += SizeOfComponent;
1870 }
1871 LVal.addComplex(Info, E, EltTy, Imag);
1872 return true;
1873}
1874
Richard Smith27908702011-10-24 17:54:18 +00001875/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001876///
1877/// \param Info Information about the ongoing evaluation.
1878/// \param E An expression to be used when printing diagnostics.
1879/// \param VD The variable whose initializer should be obtained.
1880/// \param Frame The frame in which the variable was created. Must be null
1881/// if this variable is not local to the evaluation.
1882/// \param Result Filled in with a pointer to the value of the variable.
1883static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1884 const VarDecl *VD, CallStackFrame *Frame,
1885 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001886 // If this is a parameter to an active constexpr function call, perform
1887 // argument substitution.
1888 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001889 // Assume arguments of a potential constant expression are unknown
1890 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001891 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001892 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001893 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001894 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001895 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001896 }
Richard Smith3229b742013-05-05 21:17:10 +00001897 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001898 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001899 }
Richard Smith27908702011-10-24 17:54:18 +00001900
Richard Smithd9f663b2013-04-22 15:31:51 +00001901 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001902 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001903 Result = Frame->getTemporary(VD);
1904 assert(Result && "missing value for local variable");
1905 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001906 }
1907
Richard Smithd0b4dd62011-12-19 06:19:21 +00001908 // Dig out the initializer, and use the declaration which it's attached to.
1909 const Expr *Init = VD->getAnyInitializer(VD);
1910 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001911 // If we're checking a potential constant expression, the variable could be
1912 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001913 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001914 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001915 return false;
1916 }
1917
Richard Smithd62306a2011-11-10 06:34:14 +00001918 // If we're currently evaluating the initializer of this declaration, use that
1919 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001920 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001921 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001922 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001923 }
1924
Richard Smithcecf1842011-11-01 21:06:14 +00001925 // Never evaluate the initializer of a weak variable. We can't be sure that
1926 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001927 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001928 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001929 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001930 }
Richard Smithcecf1842011-11-01 21:06:14 +00001931
Richard Smithd0b4dd62011-12-19 06:19:21 +00001932 // Check that we can fold the initializer. In C++, we will have already done
1933 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001934 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001935 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001936 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001937 Notes.size() + 1) << VD;
1938 Info.Note(VD->getLocation(), diag::note_declared_at);
1939 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001940 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001941 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001942 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001943 Notes.size() + 1) << VD;
1944 Info.Note(VD->getLocation(), diag::note_declared_at);
1945 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001946 }
Richard Smith27908702011-10-24 17:54:18 +00001947
Richard Smith3229b742013-05-05 21:17:10 +00001948 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001949 return true;
Richard Smith27908702011-10-24 17:54:18 +00001950}
1951
Richard Smith11562c52011-10-28 17:51:58 +00001952static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001953 Qualifiers Quals = T.getQualifiers();
1954 return Quals.hasConst() && !Quals.hasVolatile();
1955}
1956
Richard Smithe97cbd72011-11-11 04:05:33 +00001957/// Get the base index of the given base class within an APValue representing
1958/// the given derived class.
1959static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1960 const CXXRecordDecl *Base) {
1961 Base = Base->getCanonicalDecl();
1962 unsigned Index = 0;
1963 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1964 E = Derived->bases_end(); I != E; ++I, ++Index) {
1965 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1966 return Index;
1967 }
1968
1969 llvm_unreachable("base class missing from derived class's bases list");
1970}
1971
Richard Smith3da88fa2013-04-26 14:36:30 +00001972/// Extract the value of a character from a string literal.
1973static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1974 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001975 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001976 const StringLiteral *S = cast<StringLiteral>(Lit);
1977 const ConstantArrayType *CAT =
1978 Info.Ctx.getAsConstantArrayType(S->getType());
1979 assert(CAT && "string literal isn't an array");
1980 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001981 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001982
1983 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001984 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001985 if (Index < S->getLength())
1986 Value = S->getCodeUnit(Index);
1987 return Value;
1988}
1989
Richard Smith3da88fa2013-04-26 14:36:30 +00001990// Expand a string literal into an array of characters.
1991static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1992 APValue &Result) {
1993 const StringLiteral *S = cast<StringLiteral>(Lit);
1994 const ConstantArrayType *CAT =
1995 Info.Ctx.getAsConstantArrayType(S->getType());
1996 assert(CAT && "string literal isn't an array");
1997 QualType CharType = CAT->getElementType();
1998 assert(CharType->isIntegerType() && "unexpected character type");
1999
2000 unsigned Elts = CAT->getSize().getZExtValue();
2001 Result = APValue(APValue::UninitArray(),
2002 std::min(S->getLength(), Elts), Elts);
2003 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2004 CharType->isUnsignedIntegerType());
2005 if (Result.hasArrayFiller())
2006 Result.getArrayFiller() = APValue(Value);
2007 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2008 Value = S->getCodeUnit(I);
2009 Result.getArrayInitializedElt(I) = APValue(Value);
2010 }
2011}
2012
2013// Expand an array so that it has more than Index filled elements.
2014static void expandArray(APValue &Array, unsigned Index) {
2015 unsigned Size = Array.getArraySize();
2016 assert(Index < Size);
2017
2018 // Always at least double the number of elements for which we store a value.
2019 unsigned OldElts = Array.getArrayInitializedElts();
2020 unsigned NewElts = std::max(Index+1, OldElts * 2);
2021 NewElts = std::min(Size, std::max(NewElts, 8u));
2022
2023 // Copy the data across.
2024 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2025 for (unsigned I = 0; I != OldElts; ++I)
2026 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2027 for (unsigned I = OldElts; I != NewElts; ++I)
2028 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2029 if (NewValue.hasArrayFiller())
2030 NewValue.getArrayFiller() = Array.getArrayFiller();
2031 Array.swap(NewValue);
2032}
2033
Richard Smith861b5b52013-05-07 23:34:45 +00002034/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002035enum AccessKinds {
2036 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002037 AK_Assign,
2038 AK_Increment,
2039 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002040};
2041
Richard Smith3229b742013-05-05 21:17:10 +00002042/// A handle to a complete object (an object that is not a subobject of
2043/// another object).
2044struct CompleteObject {
2045 /// The value of the complete object.
2046 APValue *Value;
2047 /// The type of the complete object.
2048 QualType Type;
2049
2050 CompleteObject() : Value(0) {}
2051 CompleteObject(APValue *Value, QualType Type)
2052 : Value(Value), Type(Type) {
2053 assert(Value && "missing value for complete object");
2054 }
2055
David Blaikie7d170102013-05-15 07:37:26 +00002056 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002057};
2058
Richard Smith3da88fa2013-04-26 14:36:30 +00002059/// Find the designated sub-object of an rvalue.
2060template<typename SubobjectHandler>
2061typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002062findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002063 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002064 if (Sub.Invalid)
2065 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002066 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002067 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002068 if (Info.getLangOpts().CPlusPlus11)
2069 Info.Diag(E, diag::note_constexpr_access_past_end)
2070 << handler.AccessKind;
2071 else
2072 Info.Diag(E);
2073 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002074 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002075
Richard Smith3229b742013-05-05 21:17:10 +00002076 APValue *O = Obj.Value;
2077 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002078 const FieldDecl *LastField = 0;
2079
Richard Smithd62306a2011-11-10 06:34:14 +00002080 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002081 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2082 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002083 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002084 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2085 return handler.failed();
2086 }
2087
Richard Smith49ca8aa2013-08-06 07:09:20 +00002088 if (I == N) {
2089 if (!handler.found(*O, ObjType))
2090 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002091
Richard Smith49ca8aa2013-08-06 07:09:20 +00002092 // If we modified a bit-field, truncate it to the right width.
2093 if (handler.AccessKind != AK_Read &&
2094 LastField && LastField->isBitField() &&
2095 !truncateBitfieldValue(Info, E, *O, LastField))
2096 return false;
2097
2098 return true;
2099 }
2100
2101 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002102 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002103 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002104 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002105 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002106 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002107 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002108 // Note, it should not be possible to form a pointer with a valid
2109 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002110 if (Info.getLangOpts().CPlusPlus11)
2111 Info.Diag(E, diag::note_constexpr_access_past_end)
2112 << handler.AccessKind;
2113 else
2114 Info.Diag(E);
2115 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002116 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002117
2118 ObjType = CAT->getElementType();
2119
Richard Smith14a94132012-02-17 03:35:37 +00002120 // An array object is represented as either an Array APValue or as an
2121 // LValue which refers to a string literal.
2122 if (O->isLValue()) {
2123 assert(I == N - 1 && "extracting subobject of character?");
2124 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002125 if (handler.AccessKind != AK_Read)
2126 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2127 *O);
2128 else
2129 return handler.foundString(*O, ObjType, Index);
2130 }
2131
2132 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002133 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002134 else if (handler.AccessKind != AK_Read) {
2135 expandArray(*O, Index);
2136 O = &O->getArrayInitializedElt(Index);
2137 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002138 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002139 } else if (ObjType->isAnyComplexType()) {
2140 // Next subobject is a complex number.
2141 uint64_t Index = Sub.Entries[I].ArrayIndex;
2142 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002143 if (Info.getLangOpts().CPlusPlus11)
2144 Info.Diag(E, diag::note_constexpr_access_past_end)
2145 << handler.AccessKind;
2146 else
2147 Info.Diag(E);
2148 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002149 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002150
2151 bool WasConstQualified = ObjType.isConstQualified();
2152 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2153 if (WasConstQualified)
2154 ObjType.addConst();
2155
Richard Smith66c96992012-02-18 22:04:06 +00002156 assert(I == N - 1 && "extracting subobject of scalar?");
2157 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002158 return handler.found(Index ? O->getComplexIntImag()
2159 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002160 } else {
2161 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002162 return handler.found(Index ? O->getComplexFloatImag()
2163 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002164 }
Richard Smithd62306a2011-11-10 06:34:14 +00002165 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002166 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002167 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002168 << Field;
2169 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002170 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002171 }
2172
Richard Smithd62306a2011-11-10 06:34:14 +00002173 // Next subobject is a class, struct or union field.
2174 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2175 if (RD->isUnion()) {
2176 const FieldDecl *UnionField = O->getUnionField();
2177 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002178 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002179 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2180 << handler.AccessKind << Field << !UnionField << UnionField;
2181 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002182 }
Richard Smithd62306a2011-11-10 06:34:14 +00002183 O = &O->getUnionValue();
2184 } else
2185 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002186
2187 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002188 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002189 if (WasConstQualified && !Field->isMutable())
2190 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002191
2192 if (ObjType.isVolatileQualified()) {
2193 if (Info.getLangOpts().CPlusPlus) {
2194 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002195 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2196 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002197 Info.Note(Field->getLocation(), diag::note_declared_at);
2198 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002199 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002200 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002201 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002202 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002203
2204 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002205 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002206 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002207 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2208 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2209 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002210
2211 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002212 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002213 if (WasConstQualified)
2214 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002215 }
2216 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002217}
2218
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002219namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002220struct ExtractSubobjectHandler {
2221 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002222 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002223
2224 static const AccessKinds AccessKind = AK_Read;
2225
2226 typedef bool result_type;
2227 bool failed() { return false; }
2228 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002229 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002230 return true;
2231 }
2232 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002233 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002234 return true;
2235 }
2236 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002237 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002238 return true;
2239 }
2240 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002241 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002242 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2243 return true;
2244 }
2245};
Richard Smith3229b742013-05-05 21:17:10 +00002246} // end anonymous namespace
2247
Richard Smith3da88fa2013-04-26 14:36:30 +00002248const AccessKinds ExtractSubobjectHandler::AccessKind;
2249
2250/// Extract the designated sub-object of an rvalue.
2251static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002252 const CompleteObject &Obj,
2253 const SubobjectDesignator &Sub,
2254 APValue &Result) {
2255 ExtractSubobjectHandler Handler = { Info, Result };
2256 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002257}
2258
Richard Smith3229b742013-05-05 21:17:10 +00002259namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002260struct ModifySubobjectHandler {
2261 EvalInfo &Info;
2262 APValue &NewVal;
2263 const Expr *E;
2264
2265 typedef bool result_type;
2266 static const AccessKinds AccessKind = AK_Assign;
2267
2268 bool checkConst(QualType QT) {
2269 // Assigning to a const object has undefined behavior.
2270 if (QT.isConstQualified()) {
2271 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2272 return false;
2273 }
2274 return true;
2275 }
2276
2277 bool failed() { return false; }
2278 bool found(APValue &Subobj, QualType SubobjType) {
2279 if (!checkConst(SubobjType))
2280 return false;
2281 // We've been given ownership of NewVal, so just swap it in.
2282 Subobj.swap(NewVal);
2283 return true;
2284 }
2285 bool found(APSInt &Value, QualType SubobjType) {
2286 if (!checkConst(SubobjType))
2287 return false;
2288 if (!NewVal.isInt()) {
2289 // Maybe trying to write a cast pointer value into a complex?
2290 Info.Diag(E);
2291 return false;
2292 }
2293 Value = NewVal.getInt();
2294 return true;
2295 }
2296 bool found(APFloat &Value, QualType SubobjType) {
2297 if (!checkConst(SubobjType))
2298 return false;
2299 Value = NewVal.getFloat();
2300 return true;
2301 }
2302 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2303 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2304 }
2305};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002306} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002307
Richard Smith3229b742013-05-05 21:17:10 +00002308const AccessKinds ModifySubobjectHandler::AccessKind;
2309
Richard Smith3da88fa2013-04-26 14:36:30 +00002310/// Update the designated sub-object of an rvalue to the given value.
2311static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002312 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002313 const SubobjectDesignator &Sub,
2314 APValue &NewVal) {
2315 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002316 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002317}
2318
Richard Smith84f6dcf2012-02-02 01:16:57 +00002319/// Find the position where two subobject designators diverge, or equivalently
2320/// the length of the common initial subsequence.
2321static unsigned FindDesignatorMismatch(QualType ObjType,
2322 const SubobjectDesignator &A,
2323 const SubobjectDesignator &B,
2324 bool &WasArrayIndex) {
2325 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2326 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002327 if (!ObjType.isNull() &&
2328 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002329 // Next subobject is an array element.
2330 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2331 WasArrayIndex = true;
2332 return I;
2333 }
Richard Smith66c96992012-02-18 22:04:06 +00002334 if (ObjType->isAnyComplexType())
2335 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2336 else
2337 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002338 } else {
2339 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2340 WasArrayIndex = false;
2341 return I;
2342 }
2343 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2344 // Next subobject is a field.
2345 ObjType = FD->getType();
2346 else
2347 // Next subobject is a base class.
2348 ObjType = QualType();
2349 }
2350 }
2351 WasArrayIndex = false;
2352 return I;
2353}
2354
2355/// Determine whether the given subobject designators refer to elements of the
2356/// same array object.
2357static bool AreElementsOfSameArray(QualType ObjType,
2358 const SubobjectDesignator &A,
2359 const SubobjectDesignator &B) {
2360 if (A.Entries.size() != B.Entries.size())
2361 return false;
2362
2363 bool IsArray = A.MostDerivedArraySize != 0;
2364 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2365 // A is a subobject of the array element.
2366 return false;
2367
2368 // If A (and B) designates an array element, the last entry will be the array
2369 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2370 // of length 1' case, and the entire path must match.
2371 bool WasArrayIndex;
2372 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2373 return CommonLength >= A.Entries.size() - IsArray;
2374}
2375
Richard Smith3229b742013-05-05 21:17:10 +00002376/// Find the complete object to which an LValue refers.
2377CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2378 const LValue &LVal, QualType LValType) {
2379 if (!LVal.Base) {
2380 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2381 return CompleteObject();
2382 }
2383
2384 CallStackFrame *Frame = 0;
2385 if (LVal.CallIndex) {
2386 Frame = Info.getCallFrame(LVal.CallIndex);
2387 if (!Frame) {
2388 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2389 << AK << LVal.Base.is<const ValueDecl*>();
2390 NoteLValueLocation(Info, LVal.Base);
2391 return CompleteObject();
2392 }
Richard Smith3229b742013-05-05 21:17:10 +00002393 }
2394
2395 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2396 // is not a constant expression (even if the object is non-volatile). We also
2397 // apply this rule to C++98, in order to conform to the expected 'volatile'
2398 // semantics.
2399 if (LValType.isVolatileQualified()) {
2400 if (Info.getLangOpts().CPlusPlus)
2401 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2402 << AK << LValType;
2403 else
2404 Info.Diag(E);
2405 return CompleteObject();
2406 }
2407
2408 // Compute value storage location and type of base object.
2409 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002410 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002411
2412 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2413 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2414 // In C++11, constexpr, non-volatile variables initialized with constant
2415 // expressions are constant expressions too. Inside constexpr functions,
2416 // parameters are constant expressions even if they're non-const.
2417 // In C++1y, objects local to a constant expression (those with a Frame) are
2418 // both readable and writable inside constant expressions.
2419 // In C, such things can also be folded, although they are not ICEs.
2420 const VarDecl *VD = dyn_cast<VarDecl>(D);
2421 if (VD) {
2422 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2423 VD = VDef;
2424 }
2425 if (!VD || VD->isInvalidDecl()) {
2426 Info.Diag(E);
2427 return CompleteObject();
2428 }
2429
2430 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002431 if (BaseType.isVolatileQualified()) {
2432 if (Info.getLangOpts().CPlusPlus) {
2433 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2434 << AK << 1 << VD;
2435 Info.Note(VD->getLocation(), diag::note_declared_at);
2436 } else {
2437 Info.Diag(E);
2438 }
2439 return CompleteObject();
2440 }
2441
2442 // Unless we're looking at a local variable or argument in a constexpr call,
2443 // the variable we're reading must be const.
2444 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002445 if (Info.getLangOpts().CPlusPlus1y &&
2446 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2447 // OK, we can read and modify an object if we're in the process of
2448 // evaluating its initializer, because its lifetime began in this
2449 // evaluation.
2450 } else if (AK != AK_Read) {
2451 // All the remaining cases only permit reading.
2452 Info.Diag(E, diag::note_constexpr_modify_global);
2453 return CompleteObject();
2454 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002455 // OK, we can read this variable.
2456 } else if (BaseType->isIntegralOrEnumerationType()) {
2457 if (!BaseType.isConstQualified()) {
2458 if (Info.getLangOpts().CPlusPlus) {
2459 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2460 Info.Note(VD->getLocation(), diag::note_declared_at);
2461 } else {
2462 Info.Diag(E);
2463 }
2464 return CompleteObject();
2465 }
2466 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2467 // We support folding of const floating-point types, in order to make
2468 // static const data members of such types (supported as an extension)
2469 // more useful.
2470 if (Info.getLangOpts().CPlusPlus11) {
2471 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2472 Info.Note(VD->getLocation(), diag::note_declared_at);
2473 } else {
2474 Info.CCEDiag(E);
2475 }
2476 } else {
2477 // FIXME: Allow folding of values of any literal type in all languages.
2478 if (Info.getLangOpts().CPlusPlus11) {
2479 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2480 Info.Note(VD->getLocation(), diag::note_declared_at);
2481 } else {
2482 Info.Diag(E);
2483 }
2484 return CompleteObject();
2485 }
2486 }
2487
2488 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2489 return CompleteObject();
2490 } else {
2491 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2492
2493 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002494 if (const MaterializeTemporaryExpr *MTE =
2495 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2496 assert(MTE->getStorageDuration() == SD_Static &&
2497 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002498
Richard Smithe6c01442013-06-05 00:46:14 +00002499 // Per C++1y [expr.const]p2:
2500 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2501 // - a [...] glvalue of integral or enumeration type that refers to
2502 // a non-volatile const object [...]
2503 // [...]
2504 // - a [...] glvalue of literal type that refers to a non-volatile
2505 // object whose lifetime began within the evaluation of e.
2506 //
2507 // C++11 misses the 'began within the evaluation of e' check and
2508 // instead allows all temporaries, including things like:
2509 // int &&r = 1;
2510 // int x = ++r;
2511 // constexpr int k = r;
2512 // Therefore we use the C++1y rules in C++11 too.
2513 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2514 const ValueDecl *ED = MTE->getExtendingDecl();
2515 if (!(BaseType.isConstQualified() &&
2516 BaseType->isIntegralOrEnumerationType()) &&
2517 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2518 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2519 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2520 return CompleteObject();
2521 }
2522
2523 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2524 assert(BaseVal && "got reference to unevaluated temporary");
2525 } else {
2526 Info.Diag(E);
2527 return CompleteObject();
2528 }
2529 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002530 BaseVal = Frame->getTemporary(Base);
2531 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002532 }
Richard Smith3229b742013-05-05 21:17:10 +00002533
2534 // Volatile temporary objects cannot be accessed in constant expressions.
2535 if (BaseType.isVolatileQualified()) {
2536 if (Info.getLangOpts().CPlusPlus) {
2537 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2538 << AK << 0;
2539 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2540 } else {
2541 Info.Diag(E);
2542 }
2543 return CompleteObject();
2544 }
2545 }
2546
Richard Smith7525ff62013-05-09 07:14:00 +00002547 // During the construction of an object, it is not yet 'const'.
2548 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2549 // and this doesn't do quite the right thing for const subobjects of the
2550 // object under construction.
2551 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2552 BaseType = Info.Ctx.getCanonicalType(BaseType);
2553 BaseType.removeLocalConst();
2554 }
2555
Richard Smith6d4c6582013-11-05 22:18:15 +00002556 // In C++1y, we can't safely access any mutable state when we might be
2557 // evaluating after an unmodeled side effect or an evaluation failure.
2558 //
2559 // FIXME: Not all local state is mutable. Allow local constant subobjects
2560 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002561 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002562 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002563 return CompleteObject();
2564
2565 return CompleteObject(BaseVal, BaseType);
2566}
2567
Richard Smith243ef902013-05-05 23:31:59 +00002568/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2569/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2570/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002571///
2572/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002573/// \param Conv - The expression for which we are performing the conversion.
2574/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002575/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2576/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002577/// \param LVal - The glvalue on which we are attempting to perform this action.
2578/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002579static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002580 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002581 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002582 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002583 return false;
2584
Richard Smith3229b742013-05-05 21:17:10 +00002585 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002586 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002587 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2588 !Type.isVolatileQualified()) {
2589 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2590 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2591 // initializer until now for such expressions. Such an expression can't be
2592 // an ICE in C, so this only matters for fold.
2593 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2594 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002595 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002596 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002597 }
Richard Smith3229b742013-05-05 21:17:10 +00002598 APValue Lit;
2599 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2600 return false;
2601 CompleteObject LitObj(&Lit, Base->getType());
2602 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2603 } else if (isa<StringLiteral>(Base)) {
2604 // We represent a string literal array as an lvalue pointing at the
2605 // corresponding expression, rather than building an array of chars.
2606 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2607 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2608 CompleteObject StrObj(&Str, Base->getType());
2609 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002610 }
Richard Smith11562c52011-10-28 17:51:58 +00002611 }
2612
Richard Smith3229b742013-05-05 21:17:10 +00002613 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2614 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002615}
2616
2617/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002618static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002619 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002620 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002621 return false;
2622
Richard Smith3229b742013-05-05 21:17:10 +00002623 if (!Info.getLangOpts().CPlusPlus1y) {
2624 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002625 return false;
2626 }
2627
Richard Smith3229b742013-05-05 21:17:10 +00002628 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2629 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002630}
2631
Richard Smith243ef902013-05-05 23:31:59 +00002632static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2633 return T->isSignedIntegerType() &&
2634 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2635}
2636
2637namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002638struct CompoundAssignSubobjectHandler {
2639 EvalInfo &Info;
2640 const Expr *E;
2641 QualType PromotedLHSType;
2642 BinaryOperatorKind Opcode;
2643 const APValue &RHS;
2644
2645 static const AccessKinds AccessKind = AK_Assign;
2646
2647 typedef bool result_type;
2648
2649 bool checkConst(QualType QT) {
2650 // Assigning to a const object has undefined behavior.
2651 if (QT.isConstQualified()) {
2652 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2653 return false;
2654 }
2655 return true;
2656 }
2657
2658 bool failed() { return false; }
2659 bool found(APValue &Subobj, QualType SubobjType) {
2660 switch (Subobj.getKind()) {
2661 case APValue::Int:
2662 return found(Subobj.getInt(), SubobjType);
2663 case APValue::Float:
2664 return found(Subobj.getFloat(), SubobjType);
2665 case APValue::ComplexInt:
2666 case APValue::ComplexFloat:
2667 // FIXME: Implement complex compound assignment.
2668 Info.Diag(E);
2669 return false;
2670 case APValue::LValue:
2671 return foundPointer(Subobj, SubobjType);
2672 default:
2673 // FIXME: can this happen?
2674 Info.Diag(E);
2675 return false;
2676 }
2677 }
2678 bool found(APSInt &Value, QualType SubobjType) {
2679 if (!checkConst(SubobjType))
2680 return false;
2681
2682 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2683 // We don't support compound assignment on integer-cast-to-pointer
2684 // values.
2685 Info.Diag(E);
2686 return false;
2687 }
2688
2689 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2690 SubobjType, Value);
2691 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2692 return false;
2693 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2694 return true;
2695 }
2696 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002697 return checkConst(SubobjType) &&
2698 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2699 Value) &&
2700 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2701 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002702 }
2703 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2704 if (!checkConst(SubobjType))
2705 return false;
2706
2707 QualType PointeeType;
2708 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2709 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002710
2711 if (PointeeType.isNull() || !RHS.isInt() ||
2712 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002713 Info.Diag(E);
2714 return false;
2715 }
2716
Richard Smith861b5b52013-05-07 23:34:45 +00002717 int64_t Offset = getExtValue(RHS.getInt());
2718 if (Opcode == BO_Sub)
2719 Offset = -Offset;
2720
2721 LValue LVal;
2722 LVal.setFrom(Info.Ctx, Subobj);
2723 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2724 return false;
2725 LVal.moveInto(Subobj);
2726 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002727 }
2728 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2729 llvm_unreachable("shouldn't encounter string elements here");
2730 }
2731};
2732} // end anonymous namespace
2733
2734const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2735
2736/// Perform a compound assignment of LVal <op>= RVal.
2737static bool handleCompoundAssignment(
2738 EvalInfo &Info, const Expr *E,
2739 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2740 BinaryOperatorKind Opcode, const APValue &RVal) {
2741 if (LVal.Designator.Invalid)
2742 return false;
2743
2744 if (!Info.getLangOpts().CPlusPlus1y) {
2745 Info.Diag(E);
2746 return false;
2747 }
2748
2749 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2750 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2751 RVal };
2752 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2753}
2754
2755namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002756struct IncDecSubobjectHandler {
2757 EvalInfo &Info;
2758 const Expr *E;
2759 AccessKinds AccessKind;
2760 APValue *Old;
2761
2762 typedef bool result_type;
2763
2764 bool checkConst(QualType QT) {
2765 // Assigning to a const object has undefined behavior.
2766 if (QT.isConstQualified()) {
2767 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2768 return false;
2769 }
2770 return true;
2771 }
2772
2773 bool failed() { return false; }
2774 bool found(APValue &Subobj, QualType SubobjType) {
2775 // Stash the old value. Also clear Old, so we don't clobber it later
2776 // if we're post-incrementing a complex.
2777 if (Old) {
2778 *Old = Subobj;
2779 Old = 0;
2780 }
2781
2782 switch (Subobj.getKind()) {
2783 case APValue::Int:
2784 return found(Subobj.getInt(), SubobjType);
2785 case APValue::Float:
2786 return found(Subobj.getFloat(), SubobjType);
2787 case APValue::ComplexInt:
2788 return found(Subobj.getComplexIntReal(),
2789 SubobjType->castAs<ComplexType>()->getElementType()
2790 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2791 case APValue::ComplexFloat:
2792 return found(Subobj.getComplexFloatReal(),
2793 SubobjType->castAs<ComplexType>()->getElementType()
2794 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2795 case APValue::LValue:
2796 return foundPointer(Subobj, SubobjType);
2797 default:
2798 // FIXME: can this happen?
2799 Info.Diag(E);
2800 return false;
2801 }
2802 }
2803 bool found(APSInt &Value, QualType SubobjType) {
2804 if (!checkConst(SubobjType))
2805 return false;
2806
2807 if (!SubobjType->isIntegerType()) {
2808 // We don't support increment / decrement on integer-cast-to-pointer
2809 // values.
2810 Info.Diag(E);
2811 return false;
2812 }
2813
2814 if (Old) *Old = APValue(Value);
2815
2816 // bool arithmetic promotes to int, and the conversion back to bool
2817 // doesn't reduce mod 2^n, so special-case it.
2818 if (SubobjType->isBooleanType()) {
2819 if (AccessKind == AK_Increment)
2820 Value = 1;
2821 else
2822 Value = !Value;
2823 return true;
2824 }
2825
2826 bool WasNegative = Value.isNegative();
2827 if (AccessKind == AK_Increment) {
2828 ++Value;
2829
2830 if (!WasNegative && Value.isNegative() &&
2831 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2832 APSInt ActualValue(Value, /*IsUnsigned*/true);
2833 HandleOverflow(Info, E, ActualValue, SubobjType);
2834 }
2835 } else {
2836 --Value;
2837
2838 if (WasNegative && !Value.isNegative() &&
2839 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2840 unsigned BitWidth = Value.getBitWidth();
2841 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2842 ActualValue.setBit(BitWidth);
2843 HandleOverflow(Info, E, ActualValue, SubobjType);
2844 }
2845 }
2846 return true;
2847 }
2848 bool found(APFloat &Value, QualType SubobjType) {
2849 if (!checkConst(SubobjType))
2850 return false;
2851
2852 if (Old) *Old = APValue(Value);
2853
2854 APFloat One(Value.getSemantics(), 1);
2855 if (AccessKind == AK_Increment)
2856 Value.add(One, APFloat::rmNearestTiesToEven);
2857 else
2858 Value.subtract(One, APFloat::rmNearestTiesToEven);
2859 return true;
2860 }
2861 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2862 if (!checkConst(SubobjType))
2863 return false;
2864
2865 QualType PointeeType;
2866 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2867 PointeeType = PT->getPointeeType();
2868 else {
2869 Info.Diag(E);
2870 return false;
2871 }
2872
2873 LValue LVal;
2874 LVal.setFrom(Info.Ctx, Subobj);
2875 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2876 AccessKind == AK_Increment ? 1 : -1))
2877 return false;
2878 LVal.moveInto(Subobj);
2879 return true;
2880 }
2881 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2882 llvm_unreachable("shouldn't encounter string elements here");
2883 }
2884};
2885} // end anonymous namespace
2886
2887/// Perform an increment or decrement on LVal.
2888static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2889 QualType LValType, bool IsIncrement, APValue *Old) {
2890 if (LVal.Designator.Invalid)
2891 return false;
2892
2893 if (!Info.getLangOpts().CPlusPlus1y) {
2894 Info.Diag(E);
2895 return false;
2896 }
2897
2898 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2899 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2900 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2901 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2902}
2903
Richard Smithe97cbd72011-11-11 04:05:33 +00002904/// Build an lvalue for the object argument of a member function call.
2905static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2906 LValue &This) {
2907 if (Object->getType()->isPointerType())
2908 return EvaluatePointer(Object, This, Info);
2909
2910 if (Object->isGLValue())
2911 return EvaluateLValue(Object, This, Info);
2912
Richard Smithd9f663b2013-04-22 15:31:51 +00002913 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002914 return EvaluateTemporary(Object, This, Info);
2915
2916 return false;
2917}
2918
2919/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2920/// lvalue referring to the result.
2921///
2922/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002923/// \param LV - An lvalue referring to the base of the member pointer.
2924/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002925/// \param IncludeMember - Specifies whether the member itself is included in
2926/// the resulting LValue subobject designator. This is not possible when
2927/// creating a bound member function.
2928/// \return The field or method declaration to which the member pointer refers,
2929/// or 0 if evaluation fails.
2930static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002931 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002932 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002933 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002934 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002935 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002936 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002937 return 0;
2938
2939 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2940 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002941 if (!MemPtr.getDecl()) {
2942 // FIXME: Specific diagnostic.
2943 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002944 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002945 }
Richard Smith253c2a32012-01-27 01:14:48 +00002946
Richard Smith027bf112011-11-17 22:56:20 +00002947 if (MemPtr.isDerivedMember()) {
2948 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002949 // The end of the derived-to-base path for the base object must match the
2950 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002951 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002952 LV.Designator.Entries.size()) {
2953 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002954 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002955 }
Richard Smith027bf112011-11-17 22:56:20 +00002956 unsigned PathLengthToMember =
2957 LV.Designator.Entries.size() - MemPtr.Path.size();
2958 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2959 const CXXRecordDecl *LVDecl = getAsBaseClass(
2960 LV.Designator.Entries[PathLengthToMember + I]);
2961 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002962 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2963 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002964 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002965 }
Richard Smith027bf112011-11-17 22:56:20 +00002966 }
2967
2968 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002969 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002970 PathLengthToMember))
2971 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002972 } else if (!MemPtr.Path.empty()) {
2973 // Extend the LValue path with the member pointer's path.
2974 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2975 MemPtr.Path.size() + IncludeMember);
2976
2977 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002978 if (const PointerType *PT = LVType->getAs<PointerType>())
2979 LVType = PT->getPointeeType();
2980 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2981 assert(RD && "member pointer access on non-class-type expression");
2982 // The first class in the path is that of the lvalue.
2983 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2984 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002985 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002986 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002987 RD = Base;
2988 }
2989 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002990 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2991 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002992 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002993 }
2994
2995 // Add the member. Note that we cannot build bound member functions here.
2996 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002997 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002998 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002999 return 0;
3000 } else if (const IndirectFieldDecl *IFD =
3001 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003002 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00003003 return 0;
3004 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003005 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003006 }
Richard Smith027bf112011-11-17 22:56:20 +00003007 }
3008
3009 return MemPtr.getDecl();
3010}
3011
Richard Smith84401042013-06-03 05:03:02 +00003012static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3013 const BinaryOperator *BO,
3014 LValue &LV,
3015 bool IncludeMember = true) {
3016 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3017
3018 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3019 if (Info.keepEvaluatingAfterFailure()) {
3020 MemberPtr MemPtr;
3021 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3022 }
3023 return 0;
3024 }
3025
3026 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3027 BO->getRHS(), IncludeMember);
3028}
3029
Richard Smith027bf112011-11-17 22:56:20 +00003030/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3031/// the provided lvalue, which currently refers to the base object.
3032static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3033 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003034 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003035 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003036 return false;
3037
Richard Smitha8105bc2012-01-06 16:39:00 +00003038 QualType TargetQT = E->getType();
3039 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3040 TargetQT = PT->getPointeeType();
3041
3042 // Check this cast lands within the final derived-to-base subobject path.
3043 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003044 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003045 << D.MostDerivedType << TargetQT;
3046 return false;
3047 }
3048
Richard Smith027bf112011-11-17 22:56:20 +00003049 // Check the type of the final cast. We don't need to check the path,
3050 // since a cast can only be formed if the path is unique.
3051 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003052 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3053 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003054 if (NewEntriesSize == D.MostDerivedPathLength)
3055 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3056 else
Richard Smith027bf112011-11-17 22:56:20 +00003057 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003058 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003059 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003060 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003061 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003062 }
Richard Smith027bf112011-11-17 22:56:20 +00003063
3064 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003065 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003066}
3067
Mike Stump876387b2009-10-27 22:09:17 +00003068namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003069enum EvalStmtResult {
3070 /// Evaluation failed.
3071 ESR_Failed,
3072 /// Hit a 'return' statement.
3073 ESR_Returned,
3074 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003075 ESR_Succeeded,
3076 /// Hit a 'continue' statement.
3077 ESR_Continue,
3078 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003079 ESR_Break,
3080 /// Still scanning for 'case' or 'default' statement.
3081 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003082};
3083}
3084
Richard Smithd9f663b2013-04-22 15:31:51 +00003085static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3086 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3087 // We don't need to evaluate the initializer for a static local.
3088 if (!VD->hasLocalStorage())
3089 return true;
3090
3091 LValue Result;
3092 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003093 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003094
Richard Smith51f03172013-06-20 03:00:05 +00003095 if (!VD->getInit()) {
3096 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3097 << false << VD->getType();
3098 Val = APValue();
3099 return false;
3100 }
3101
Richard Smithd9f663b2013-04-22 15:31:51 +00003102 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3103 // Wipe out any partially-computed value, to allow tracking that this
3104 // evaluation failed.
3105 Val = APValue();
3106 return false;
3107 }
3108 }
3109
3110 return true;
3111}
3112
Richard Smith4e18ca52013-05-06 05:56:11 +00003113/// Evaluate a condition (either a variable declaration or an expression).
3114static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3115 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003116 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003117 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3118 return false;
3119 return EvaluateAsBooleanCondition(Cond, Result, Info);
3120}
3121
3122static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003123 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003124
3125/// Evaluate the body of a loop, and translate the result as appropriate.
3126static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003127 const Stmt *Body,
3128 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003129 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003130 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003131 case ESR_Break:
3132 return ESR_Succeeded;
3133 case ESR_Succeeded:
3134 case ESR_Continue:
3135 return ESR_Continue;
3136 case ESR_Failed:
3137 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003138 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003139 return ESR;
3140 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003141 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003142}
3143
Richard Smith496ddcf2013-05-12 17:32:42 +00003144/// Evaluate a switch statement.
3145static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3146 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003147 BlockScopeRAII Scope(Info);
3148
Richard Smith496ddcf2013-05-12 17:32:42 +00003149 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003150 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003151 {
3152 FullExpressionRAII Scope(Info);
3153 if (SS->getConditionVariable() &&
3154 !EvaluateDecl(Info, SS->getConditionVariable()))
3155 return ESR_Failed;
3156 if (!EvaluateInteger(SS->getCond(), Value, Info))
3157 return ESR_Failed;
3158 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003159
3160 // Find the switch case corresponding to the value of the condition.
3161 // FIXME: Cache this lookup.
3162 const SwitchCase *Found = 0;
3163 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3164 SC = SC->getNextSwitchCase()) {
3165 if (isa<DefaultStmt>(SC)) {
3166 Found = SC;
3167 continue;
3168 }
3169
3170 const CaseStmt *CS = cast<CaseStmt>(SC);
3171 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3172 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3173 : LHS;
3174 if (LHS <= Value && Value <= RHS) {
3175 Found = SC;
3176 break;
3177 }
3178 }
3179
3180 if (!Found)
3181 return ESR_Succeeded;
3182
3183 // Search the switch body for the switch case and evaluate it from there.
3184 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3185 case ESR_Break:
3186 return ESR_Succeeded;
3187 case ESR_Succeeded:
3188 case ESR_Continue:
3189 case ESR_Failed:
3190 case ESR_Returned:
3191 return ESR;
3192 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003193 // This can only happen if the switch case is nested within a statement
3194 // expression. We have no intention of supporting that.
3195 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3196 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003197 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003198 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003199}
3200
Richard Smith254a73d2011-10-28 22:34:42 +00003201// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003202static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003203 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003204 if (!Info.nextStep(S))
3205 return ESR_Failed;
3206
Richard Smith496ddcf2013-05-12 17:32:42 +00003207 // If we're hunting down a 'case' or 'default' label, recurse through
3208 // substatements until we hit the label.
3209 if (Case) {
3210 // FIXME: We don't start the lifetime of objects whose initialization we
3211 // jump over. However, such objects must be of class type with a trivial
3212 // default constructor that initialize all subobjects, so must be empty,
3213 // so this almost never matters.
3214 switch (S->getStmtClass()) {
3215 case Stmt::CompoundStmtClass:
3216 // FIXME: Precompute which substatement of a compound statement we
3217 // would jump to, and go straight there rather than performing a
3218 // linear scan each time.
3219 case Stmt::LabelStmtClass:
3220 case Stmt::AttributedStmtClass:
3221 case Stmt::DoStmtClass:
3222 break;
3223
3224 case Stmt::CaseStmtClass:
3225 case Stmt::DefaultStmtClass:
3226 if (Case == S)
3227 Case = 0;
3228 break;
3229
3230 case Stmt::IfStmtClass: {
3231 // FIXME: Precompute which side of an 'if' we would jump to, and go
3232 // straight there rather than scanning both sides.
3233 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003234
3235 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3236 // preceded by our switch label.
3237 BlockScopeRAII Scope(Info);
3238
Richard Smith496ddcf2013-05-12 17:32:42 +00003239 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3240 if (ESR != ESR_CaseNotFound || !IS->getElse())
3241 return ESR;
3242 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3243 }
3244
3245 case Stmt::WhileStmtClass: {
3246 EvalStmtResult ESR =
3247 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3248 if (ESR != ESR_Continue)
3249 return ESR;
3250 break;
3251 }
3252
3253 case Stmt::ForStmtClass: {
3254 const ForStmt *FS = cast<ForStmt>(S);
3255 EvalStmtResult ESR =
3256 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3257 if (ESR != ESR_Continue)
3258 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003259 if (FS->getInc()) {
3260 FullExpressionRAII IncScope(Info);
3261 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3262 return ESR_Failed;
3263 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003264 break;
3265 }
3266
3267 case Stmt::DeclStmtClass:
3268 // FIXME: If the variable has initialization that can't be jumped over,
3269 // bail out of any immediately-surrounding compound-statement too.
3270 default:
3271 return ESR_CaseNotFound;
3272 }
3273 }
3274
Richard Smith254a73d2011-10-28 22:34:42 +00003275 switch (S->getStmtClass()) {
3276 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003277 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003278 // Don't bother evaluating beyond an expression-statement which couldn't
3279 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003280 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003281 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003282 return ESR_Failed;
3283 return ESR_Succeeded;
3284 }
3285
3286 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003287 return ESR_Failed;
3288
3289 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003290 return ESR_Succeeded;
3291
Richard Smithd9f663b2013-04-22 15:31:51 +00003292 case Stmt::DeclStmtClass: {
3293 const DeclStmt *DS = cast<DeclStmt>(S);
3294 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003295 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3296 // Each declaration initialization is its own full-expression.
3297 // FIXME: This isn't quite right; if we're performing aggregate
3298 // initialization, each braced subexpression is its own full-expression.
3299 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003300 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3301 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003302 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003303 return ESR_Succeeded;
3304 }
3305
Richard Smith357362d2011-12-13 06:39:58 +00003306 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003307 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003309 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003310 return ESR_Failed;
3311 return ESR_Returned;
3312 }
Richard Smith254a73d2011-10-28 22:34:42 +00003313
3314 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003315 BlockScopeRAII Scope(Info);
3316
Richard Smith254a73d2011-10-28 22:34:42 +00003317 const CompoundStmt *CS = cast<CompoundStmt>(S);
3318 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3319 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003320 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3321 if (ESR == ESR_Succeeded)
3322 Case = 0;
3323 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003324 return ESR;
3325 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003326 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003327 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003328
3329 case Stmt::IfStmtClass: {
3330 const IfStmt *IS = cast<IfStmt>(S);
3331
3332 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003333 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003334 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003335 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003336 return ESR_Failed;
3337
3338 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3339 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3340 if (ESR != ESR_Succeeded)
3341 return ESR;
3342 }
3343 return ESR_Succeeded;
3344 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003345
3346 case Stmt::WhileStmtClass: {
3347 const WhileStmt *WS = cast<WhileStmt>(S);
3348 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003349 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003350 bool Continue;
3351 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3352 Continue))
3353 return ESR_Failed;
3354 if (!Continue)
3355 break;
3356
3357 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3358 if (ESR != ESR_Continue)
3359 return ESR;
3360 }
3361 return ESR_Succeeded;
3362 }
3363
3364 case Stmt::DoStmtClass: {
3365 const DoStmt *DS = cast<DoStmt>(S);
3366 bool Continue;
3367 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003368 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003369 if (ESR != ESR_Continue)
3370 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003371 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003372
Richard Smith08d6a2c2013-07-24 07:11:57 +00003373 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003374 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3375 return ESR_Failed;
3376 } while (Continue);
3377 return ESR_Succeeded;
3378 }
3379
3380 case Stmt::ForStmtClass: {
3381 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003382 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003383 if (FS->getInit()) {
3384 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3385 if (ESR != ESR_Succeeded)
3386 return ESR;
3387 }
3388 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003389 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003390 bool Continue = true;
3391 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3392 FS->getCond(), Continue))
3393 return ESR_Failed;
3394 if (!Continue)
3395 break;
3396
3397 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3398 if (ESR != ESR_Continue)
3399 return ESR;
3400
Richard Smith08d6a2c2013-07-24 07:11:57 +00003401 if (FS->getInc()) {
3402 FullExpressionRAII IncScope(Info);
3403 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3404 return ESR_Failed;
3405 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003406 }
3407 return ESR_Succeeded;
3408 }
3409
Richard Smith896e0d72013-05-06 06:51:17 +00003410 case Stmt::CXXForRangeStmtClass: {
3411 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003412 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003413
3414 // Initialize the __range variable.
3415 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3416 if (ESR != ESR_Succeeded)
3417 return ESR;
3418
3419 // Create the __begin and __end iterators.
3420 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3421 if (ESR != ESR_Succeeded)
3422 return ESR;
3423
3424 while (true) {
3425 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003426 {
3427 bool Continue = true;
3428 FullExpressionRAII CondExpr(Info);
3429 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3430 return ESR_Failed;
3431 if (!Continue)
3432 break;
3433 }
Richard Smith896e0d72013-05-06 06:51:17 +00003434
3435 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003436 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003437 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3438 if (ESR != ESR_Succeeded)
3439 return ESR;
3440
3441 // Loop body.
3442 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3443 if (ESR != ESR_Continue)
3444 return ESR;
3445
3446 // Increment: ++__begin
3447 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3448 return ESR_Failed;
3449 }
3450
3451 return ESR_Succeeded;
3452 }
3453
Richard Smith496ddcf2013-05-12 17:32:42 +00003454 case Stmt::SwitchStmtClass:
3455 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3456
Richard Smith4e18ca52013-05-06 05:56:11 +00003457 case Stmt::ContinueStmtClass:
3458 return ESR_Continue;
3459
3460 case Stmt::BreakStmtClass:
3461 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003462
3463 case Stmt::LabelStmtClass:
3464 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3465
3466 case Stmt::AttributedStmtClass:
3467 // As a general principle, C++11 attributes can be ignored without
3468 // any semantic impact.
3469 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3470 Case);
3471
3472 case Stmt::CaseStmtClass:
3473 case Stmt::DefaultStmtClass:
3474 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003475 }
3476}
3477
Richard Smithcc36f692011-12-22 02:22:31 +00003478/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3479/// default constructor. If so, we'll fold it whether or not it's marked as
3480/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3481/// so we need special handling.
3482static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003483 const CXXConstructorDecl *CD,
3484 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003485 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3486 return false;
3487
Richard Smith66e05fe2012-01-18 05:21:49 +00003488 // Value-initialization does not call a trivial default constructor, so such a
3489 // call is a core constant expression whether or not the constructor is
3490 // constexpr.
3491 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003492 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003493 // FIXME: If DiagDecl is an implicitly-declared special member function,
3494 // we should be much more explicit about why it's not constexpr.
3495 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3496 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3497 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003498 } else {
3499 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3500 }
3501 }
3502 return true;
3503}
3504
Richard Smith357362d2011-12-13 06:39:58 +00003505/// CheckConstexprFunction - Check that a function can be called in a constant
3506/// expression.
3507static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3508 const FunctionDecl *Declaration,
3509 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003510 // Potential constant expressions can contain calls to declared, but not yet
3511 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003512 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003513 Declaration->isConstexpr())
3514 return false;
3515
Richard Smith0838f3a2013-05-14 05:18:44 +00003516 // Bail out with no diagnostic if the function declaration itself is invalid.
3517 // We will have produced a relevant diagnostic while parsing it.
3518 if (Declaration->isInvalidDecl())
3519 return false;
3520
Richard Smith357362d2011-12-13 06:39:58 +00003521 // Can we evaluate this function call?
3522 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3523 return true;
3524
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003525 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003526 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003527 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3528 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003529 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3530 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3531 << DiagDecl;
3532 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3533 } else {
3534 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3535 }
3536 return false;
3537}
3538
Richard Smithd62306a2011-11-10 06:34:14 +00003539namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003540typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003541}
3542
3543/// EvaluateArgs - Evaluate the arguments to a function call.
3544static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3545 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003546 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003547 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003548 I != E; ++I) {
3549 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3550 // If we're checking for a potential constant expression, evaluate all
3551 // initializers even if some of them fail.
3552 if (!Info.keepEvaluatingAfterFailure())
3553 return false;
3554 Success = false;
3555 }
3556 }
3557 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003558}
3559
Richard Smith254a73d2011-10-28 22:34:42 +00003560/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003561static bool HandleFunctionCall(SourceLocation CallLoc,
3562 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003563 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003564 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003565 ArgVector ArgValues(Args.size());
3566 if (!EvaluateArgs(Args, ArgValues, Info))
3567 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003568
Richard Smith253c2a32012-01-27 01:14:48 +00003569 if (!Info.CheckCallLimit(CallLoc))
3570 return false;
3571
3572 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003573
3574 // For a trivial copy or move assignment, perform an APValue copy. This is
3575 // essential for unions, where the operations performed by the assignment
3576 // operator cannot be represented as statements.
3577 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3578 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3579 assert(This &&
3580 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3581 LValue RHS;
3582 RHS.setFrom(Info.Ctx, ArgValues[0]);
3583 APValue RHSValue;
3584 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3585 RHS, RHSValue))
3586 return false;
3587 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3588 RHSValue))
3589 return false;
3590 This->moveInto(Result);
3591 return true;
3592 }
3593
Richard Smithd9f663b2013-04-22 15:31:51 +00003594 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003595 if (ESR == ESR_Succeeded) {
3596 if (Callee->getResultType()->isVoidType())
3597 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003598 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003599 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003600 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003601}
3602
Richard Smithd62306a2011-11-10 06:34:14 +00003603/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003604static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003605 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003606 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003607 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003608 ArgVector ArgValues(Args.size());
3609 if (!EvaluateArgs(Args, ArgValues, Info))
3610 return false;
3611
Richard Smith253c2a32012-01-27 01:14:48 +00003612 if (!Info.CheckCallLimit(CallLoc))
3613 return false;
3614
Richard Smith3607ffe2012-02-13 03:54:03 +00003615 const CXXRecordDecl *RD = Definition->getParent();
3616 if (RD->getNumVBases()) {
3617 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3618 return false;
3619 }
3620
Richard Smith253c2a32012-01-27 01:14:48 +00003621 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003622
3623 // If it's a delegating constructor, just delegate.
3624 if (Definition->isDelegatingConstructor()) {
3625 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003626 {
3627 FullExpressionRAII InitScope(Info);
3628 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3629 return false;
3630 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003631 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003632 }
3633
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003634 // For a trivial copy or move constructor, perform an APValue copy. This is
3635 // essential for unions, where the operations performed by the constructor
3636 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003637 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003638 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3639 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003640 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003641 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003642 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003643 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003644 }
3645
3646 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003647 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003648 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3649 std::distance(RD->field_begin(), RD->field_end()));
3650
John McCalld7bca762012-05-01 00:38:49 +00003651 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003652 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3653
Richard Smith08d6a2c2013-07-24 07:11:57 +00003654 // A scope for temporaries lifetime-extended by reference members.
3655 BlockScopeRAII LifetimeExtendedScope(Info);
3656
Richard Smith253c2a32012-01-27 01:14:48 +00003657 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003658 unsigned BasesSeen = 0;
3659#ifndef NDEBUG
3660 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3661#endif
3662 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3663 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003664 LValue Subobject = This;
3665 APValue *Value = &Result;
3666
3667 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003668 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003669 if ((*I)->isBaseInitializer()) {
3670 QualType BaseType((*I)->getBaseClass(), 0);
3671#ifndef NDEBUG
3672 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003673 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003674 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3675 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3676 "base class initializers not in expected order");
3677 ++BaseIt;
3678#endif
John McCalld7bca762012-05-01 00:38:49 +00003679 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3680 BaseType->getAsCXXRecordDecl(), &Layout))
3681 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003682 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003683 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003684 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3685 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003686 if (RD->isUnion()) {
3687 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003688 Value = &Result.getUnionValue();
3689 } else {
3690 Value = &Result.getStructField(FD->getFieldIndex());
3691 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003692 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003693 // Walk the indirect field decl's chain to find the object to initialize,
3694 // and make sure we've initialized every step along it.
3695 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3696 CE = IFD->chain_end();
3697 C != CE; ++C) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003698 FD = cast<FieldDecl>(*C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003699 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3700 // Switch the union field if it differs. This happens if we had
3701 // preceding zero-initialization, and we're now initializing a union
3702 // subobject other than the first.
3703 // FIXME: In this case, the values of the other subobjects are
3704 // specified, since zero-initialization sets all padding bits to zero.
3705 if (Value->isUninit() ||
3706 (Value->isUnion() && Value->getUnionField() != FD)) {
3707 if (CD->isUnion())
3708 *Value = APValue(FD);
3709 else
3710 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3711 std::distance(CD->field_begin(), CD->field_end()));
3712 }
John McCalld7bca762012-05-01 00:38:49 +00003713 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3714 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003715 if (CD->isUnion())
3716 Value = &Value->getUnionValue();
3717 else
3718 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003719 }
Richard Smithd62306a2011-11-10 06:34:14 +00003720 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003721 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003722 }
Richard Smith253c2a32012-01-27 01:14:48 +00003723
Richard Smith08d6a2c2013-07-24 07:11:57 +00003724 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003725 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3726 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3727 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003728 // If we're checking for a potential constant expression, evaluate all
3729 // initializers even if some of them fail.
3730 if (!Info.keepEvaluatingAfterFailure())
3731 return false;
3732 Success = false;
3733 }
Richard Smithd62306a2011-11-10 06:34:14 +00003734 }
3735
Richard Smithd9f663b2013-04-22 15:31:51 +00003736 return Success &&
3737 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003738}
3739
Eli Friedman9a156e52008-11-12 09:44:48 +00003740//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003741// Generic Evaluation
3742//===----------------------------------------------------------------------===//
3743namespace {
3744
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745// FIXME: RetTy is always bool. Remove it.
3746template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003747class ExprEvaluatorBase
3748 : public ConstStmtVisitor<Derived, RetTy> {
3749private:
Richard Smith2e312c82012-03-03 22:46:17 +00003750 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003751 return static_cast<Derived*>(this)->Success(V, E);
3752 }
Richard Smithfddd3842011-12-30 21:15:51 +00003753 RetTy DerivedZeroInitialization(const Expr *E) {
3754 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003755 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003756
Richard Smith17100ba2012-02-16 02:46:34 +00003757 // Check whether a conditional operator with a non-constant condition is a
3758 // potential constant expression. If neither arm is a potential constant
3759 // expression, then the conditional operator is not either.
3760 template<typename ConditionalOperator>
3761 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003762 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003763
3764 // Speculatively evaluate both arms.
3765 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003766 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003767 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3768
3769 StmtVisitorTy::Visit(E->getFalseExpr());
3770 if (Diag.empty())
3771 return;
3772
3773 Diag.clear();
3774 StmtVisitorTy::Visit(E->getTrueExpr());
3775 if (Diag.empty())
3776 return;
3777 }
3778
3779 Error(E, diag::note_constexpr_conditional_never_const);
3780 }
3781
3782
3783 template<typename ConditionalOperator>
3784 bool HandleConditionalOperator(const ConditionalOperator *E) {
3785 bool BoolResult;
3786 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003787 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003788 CheckPotentialConstantConditional(E);
3789 return false;
3790 }
3791
3792 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3793 return StmtVisitorTy::Visit(EvalExpr);
3794 }
3795
Peter Collingbournee9200682011-05-13 03:29:01 +00003796protected:
3797 EvalInfo &Info;
3798 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3799 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3800
Richard Smith92b1ce02011-12-12 09:28:41 +00003801 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003802 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003803 }
3804
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003805 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3806
3807public:
3808 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3809
3810 EvalInfo &getEvalInfo() { return Info; }
3811
Richard Smithf57d8cb2011-12-09 22:58:01 +00003812 /// Report an evaluation error. This should only be called when an error is
3813 /// first discovered. When propagating an error, just return false.
3814 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003815 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003816 return false;
3817 }
3818 bool Error(const Expr *E) {
3819 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3820 }
3821
Peter Collingbournee9200682011-05-13 03:29:01 +00003822 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003823 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003824 }
3825 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003826 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003827 }
3828
3829 RetTy VisitParenExpr(const ParenExpr *E)
3830 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3831 RetTy VisitUnaryExtension(const UnaryOperator *E)
3832 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3833 RetTy VisitUnaryPlus(const UnaryOperator *E)
3834 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3835 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003836 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003837 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3838 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003839 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3840 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003841 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3842 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith17e32462013-09-13 20:51:45 +00003843 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3844 // The initializer may not have been parsed yet, or might be erroneous.
3845 if (!E->getExpr())
3846 return Error(E);
3847 return StmtVisitorTy::Visit(E->getExpr());
3848 }
Richard Smith5894a912011-12-19 22:12:41 +00003849 // We cannot create any objects for which cleanups are required, so there is
3850 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3851 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3852 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003853
Richard Smith6d6ecc32011-12-12 12:46:16 +00003854 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3855 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3856 return static_cast<Derived*>(this)->VisitCastExpr(E);
3857 }
3858 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3859 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3860 return static_cast<Derived*>(this)->VisitCastExpr(E);
3861 }
3862
Richard Smith027bf112011-11-17 22:56:20 +00003863 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3864 switch (E->getOpcode()) {
3865 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003866 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003867
3868 case BO_Comma:
3869 VisitIgnoredValue(E->getLHS());
3870 return StmtVisitorTy::Visit(E->getRHS());
3871
3872 case BO_PtrMemD:
3873 case BO_PtrMemI: {
3874 LValue Obj;
3875 if (!HandleMemberPointerAccess(Info, E, Obj))
3876 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003877 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003878 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003879 return false;
3880 return DerivedSuccess(Result, E);
3881 }
3882 }
3883 }
3884
Peter Collingbournee9200682011-05-13 03:29:01 +00003885 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003886 // Evaluate and cache the common expression. We treat it as a temporary,
3887 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003888 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003889 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003890 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003891
Richard Smith17100ba2012-02-16 02:46:34 +00003892 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003893 }
3894
3895 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003896 bool IsBcpCall = false;
3897 // If the condition (ignoring parens) is a __builtin_constant_p call,
3898 // the result is a constant expression if it can be folded without
3899 // side-effects. This is an important GNU extension. See GCC PR38377
3900 // for discussion.
3901 if (const CallExpr *CallCE =
3902 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3903 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3904 IsBcpCall = true;
3905
3906 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3907 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003908 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003909 return false;
3910
Richard Smith6d4c6582013-11-05 22:18:15 +00003911 FoldConstant Fold(Info, IsBcpCall);
3912 if (!HandleConditionalOperator(E)) {
3913 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003914 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003915 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003916
3917 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003918 }
3919
3920 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003921 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3922 return DerivedSuccess(*Value, E);
3923
3924 const Expr *Source = E->getSourceExpr();
3925 if (!Source)
3926 return Error(E);
3927 if (Source == E) { // sanity checking.
3928 assert(0 && "OpaqueValueExpr recursively refers to itself");
3929 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003930 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003931 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003932 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003933
Richard Smith254a73d2011-10-28 22:34:42 +00003934 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003935 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003936 QualType CalleeType = Callee->getType();
3937
Richard Smith254a73d2011-10-28 22:34:42 +00003938 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003939 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003940 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003941 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003942
Richard Smithe97cbd72011-11-11 04:05:33 +00003943 // Extract function decl and 'this' pointer from the callee.
3944 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003945 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003946 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3947 // Explicit bound member calls, such as x.f() or p->g();
3948 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003949 return false;
3950 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003951 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003952 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003953 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3954 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003955 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3956 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003957 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003958 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003959 return Error(Callee);
3960
3961 FD = dyn_cast<FunctionDecl>(Member);
3962 if (!FD)
3963 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003964 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003965 LValue Call;
3966 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003967 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003968
Richard Smitha8105bc2012-01-06 16:39:00 +00003969 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003970 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003971 FD = dyn_cast_or_null<FunctionDecl>(
3972 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003973 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003974 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003975
3976 // Overloaded operator calls to member functions are represented as normal
3977 // calls with '*this' as the first argument.
3978 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3979 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003980 // FIXME: When selecting an implicit conversion for an overloaded
3981 // operator delete, we sometimes try to evaluate calls to conversion
3982 // operators without a 'this' parameter!
3983 if (Args.empty())
3984 return Error(E);
3985
Richard Smithe97cbd72011-11-11 04:05:33 +00003986 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3987 return false;
3988 This = &ThisVal;
3989 Args = Args.slice(1);
3990 }
3991
3992 // Don't call function pointers which have been cast to some other type.
3993 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003994 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003995 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003996 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003997
Richard Smith47b34932012-02-01 02:39:43 +00003998 if (This && !This->checkSubobject(Info, E, CSK_This))
3999 return false;
4000
Richard Smith3607ffe2012-02-13 03:54:03 +00004001 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4002 // calls to such functions in constant expressions.
4003 if (This && !HasQualifier &&
4004 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4005 return Error(E, diag::note_constexpr_virtual_call);
4006
Richard Smith357362d2011-12-13 06:39:58 +00004007 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004008 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004009 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004010
Richard Smith357362d2011-12-13 06:39:58 +00004011 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004012 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4013 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004014 return false;
4015
Richard Smithb228a862012-02-15 02:18:13 +00004016 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004017 }
4018
Richard Smith11562c52011-10-28 17:51:58 +00004019 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4020 return StmtVisitorTy::Visit(E->getInitializer());
4021 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004022 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004023 if (E->getNumInits() == 0)
4024 return DerivedZeroInitialization(E);
4025 if (E->getNumInits() == 1)
4026 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004027 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004028 }
4029 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004030 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004031 }
4032 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004033 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004034 }
Richard Smith027bf112011-11-17 22:56:20 +00004035 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004036 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004037 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004038
Richard Smithd62306a2011-11-10 06:34:14 +00004039 /// A member expression where the object is a prvalue is itself a prvalue.
4040 RetTy VisitMemberExpr(const MemberExpr *E) {
4041 assert(!E->isArrow() && "missing call to bound member function?");
4042
Richard Smith2e312c82012-03-03 22:46:17 +00004043 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004044 if (!Evaluate(Val, Info, E->getBase()))
4045 return false;
4046
4047 QualType BaseTy = E->getBase()->getType();
4048
4049 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004050 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004051 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004052 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004053 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4054
Richard Smith3229b742013-05-05 21:17:10 +00004055 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004056 SubobjectDesignator Designator(BaseTy);
4057 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004058
Richard Smith3229b742013-05-05 21:17:10 +00004059 APValue Result;
4060 return extractSubobject(Info, E, Obj, Designator, Result) &&
4061 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004062 }
4063
Richard Smith11562c52011-10-28 17:51:58 +00004064 RetTy VisitCastExpr(const CastExpr *E) {
4065 switch (E->getCastKind()) {
4066 default:
4067 break;
4068
Richard Smitha23ab512013-05-23 00:30:41 +00004069 case CK_AtomicToNonAtomic: {
4070 APValue AtomicVal;
4071 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4072 return false;
4073 return DerivedSuccess(AtomicVal, E);
4074 }
4075
Richard Smith11562c52011-10-28 17:51:58 +00004076 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004077 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004078 return StmtVisitorTy::Visit(E->getSubExpr());
4079
4080 case CK_LValueToRValue: {
4081 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004082 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4083 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004084 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004085 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004086 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004087 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004088 return false;
4089 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004090 }
4091 }
4092
Richard Smithf57d8cb2011-12-09 22:58:01 +00004093 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004094 }
4095
Richard Smith243ef902013-05-05 23:31:59 +00004096 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4097 return VisitUnaryPostIncDec(UO);
4098 }
4099 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4100 return VisitUnaryPostIncDec(UO);
4101 }
4102 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4103 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4104 return Error(UO);
4105
4106 LValue LVal;
4107 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4108 return false;
4109 APValue RVal;
4110 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4111 UO->isIncrementOp(), &RVal))
4112 return false;
4113 return DerivedSuccess(RVal, UO);
4114 }
4115
Richard Smith51f03172013-06-20 03:00:05 +00004116 RetTy VisitStmtExpr(const StmtExpr *E) {
4117 // We will have checked the full-expressions inside the statement expression
4118 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004119 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004120 return Error(E);
4121
Richard Smith08d6a2c2013-07-24 07:11:57 +00004122 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004123 const CompoundStmt *CS = E->getSubStmt();
4124 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4125 BE = CS->body_end();
4126 /**/; ++BI) {
4127 if (BI + 1 == BE) {
4128 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4129 if (!FinalExpr) {
4130 Info.Diag((*BI)->getLocStart(),
4131 diag::note_constexpr_stmt_expr_unsupported);
4132 return false;
4133 }
4134 return this->Visit(FinalExpr);
4135 }
4136
4137 APValue ReturnValue;
4138 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4139 if (ESR != ESR_Succeeded) {
4140 // FIXME: If the statement-expression terminated due to 'return',
4141 // 'break', or 'continue', it would be nice to propagate that to
4142 // the outer statement evaluation rather than bailing out.
4143 if (ESR != ESR_Failed)
4144 Info.Diag((*BI)->getLocStart(),
4145 diag::note_constexpr_stmt_expr_unsupported);
4146 return false;
4147 }
4148 }
4149 }
4150
Richard Smith4a678122011-10-24 18:44:57 +00004151 /// Visit a value which is evaluated, but whose value is ignored.
4152 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004153 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004154 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004155};
4156
4157}
4158
4159//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004160// Common base class for lvalue and temporary evaluation.
4161//===----------------------------------------------------------------------===//
4162namespace {
4163template<class Derived>
4164class LValueExprEvaluatorBase
4165 : public ExprEvaluatorBase<Derived, bool> {
4166protected:
4167 LValue &Result;
4168 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4169 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4170
4171 bool Success(APValue::LValueBase B) {
4172 Result.set(B);
4173 return true;
4174 }
4175
4176public:
4177 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4178 ExprEvaluatorBaseTy(Info), Result(Result) {}
4179
Richard Smith2e312c82012-03-03 22:46:17 +00004180 bool Success(const APValue &V, const Expr *E) {
4181 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004182 return true;
4183 }
Richard Smith027bf112011-11-17 22:56:20 +00004184
Richard Smith027bf112011-11-17 22:56:20 +00004185 bool VisitMemberExpr(const MemberExpr *E) {
4186 // Handle non-static data members.
4187 QualType BaseTy;
4188 if (E->isArrow()) {
4189 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4190 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004191 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004192 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004193 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004194 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4195 return false;
4196 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004197 } else {
4198 if (!this->Visit(E->getBase()))
4199 return false;
4200 BaseTy = E->getBase()->getType();
4201 }
Richard Smith027bf112011-11-17 22:56:20 +00004202
Richard Smith1b78b3d2012-01-25 22:15:11 +00004203 const ValueDecl *MD = E->getMemberDecl();
4204 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4205 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4206 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4207 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004208 if (!HandleLValueMember(this->Info, E, Result, FD))
4209 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004210 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004211 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4212 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004213 } else
4214 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004215
Richard Smith1b78b3d2012-01-25 22:15:11 +00004216 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004217 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004218 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004219 RefValue))
4220 return false;
4221 return Success(RefValue, E);
4222 }
4223 return true;
4224 }
4225
4226 bool VisitBinaryOperator(const BinaryOperator *E) {
4227 switch (E->getOpcode()) {
4228 default:
4229 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4230
4231 case BO_PtrMemD:
4232 case BO_PtrMemI:
4233 return HandleMemberPointerAccess(this->Info, E, Result);
4234 }
4235 }
4236
4237 bool VisitCastExpr(const CastExpr *E) {
4238 switch (E->getCastKind()) {
4239 default:
4240 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4241
4242 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004243 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004244 if (!this->Visit(E->getSubExpr()))
4245 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004246
4247 // Now figure out the necessary offset to add to the base LV to get from
4248 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004249 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4250 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004251 }
4252 }
4253};
4254}
4255
4256//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004257// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004258//
4259// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4260// function designators (in C), decl references to void objects (in C), and
4261// temporaries (if building with -Wno-address-of-temporary).
4262//
4263// LValue evaluation produces values comprising a base expression of one of the
4264// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004265// - Declarations
4266// * VarDecl
4267// * FunctionDecl
4268// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004269// * CompoundLiteralExpr in C
4270// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004271// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004272// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004273// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004274// * ObjCEncodeExpr
4275// * AddrLabelExpr
4276// * BlockExpr
4277// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004278// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004279// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004280// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004281// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4282// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004283// * A MaterializeTemporaryExpr that has static storage duration, with no
4284// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004285// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004286//===----------------------------------------------------------------------===//
4287namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004288class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004289 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004290public:
Richard Smith027bf112011-11-17 22:56:20 +00004291 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4292 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004293
Richard Smith11562c52011-10-28 17:51:58 +00004294 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004295 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004296
Peter Collingbournee9200682011-05-13 03:29:01 +00004297 bool VisitDeclRefExpr(const DeclRefExpr *E);
4298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004299 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4301 bool VisitMemberExpr(const MemberExpr *E);
4302 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4303 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004304 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004305 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004306 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4307 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004308 bool VisitUnaryReal(const UnaryOperator *E);
4309 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004310 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4311 return VisitUnaryPreIncDec(UO);
4312 }
4313 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4314 return VisitUnaryPreIncDec(UO);
4315 }
Richard Smith3229b742013-05-05 21:17:10 +00004316 bool VisitBinAssign(const BinaryOperator *BO);
4317 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004318
Peter Collingbournee9200682011-05-13 03:29:01 +00004319 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004320 switch (E->getCastKind()) {
4321 default:
Richard Smith027bf112011-11-17 22:56:20 +00004322 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004323
Eli Friedmance3e02a2011-10-11 00:13:24 +00004324 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004325 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004326 if (!Visit(E->getSubExpr()))
4327 return false;
4328 Result.Designator.setInvalid();
4329 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004330
Richard Smith027bf112011-11-17 22:56:20 +00004331 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004332 if (!Visit(E->getSubExpr()))
4333 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004334 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004335 }
4336 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004337};
4338} // end anonymous namespace
4339
Richard Smith11562c52011-10-28 17:51:58 +00004340/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004341/// expressions which are not glvalues, in two cases:
4342/// * function designators in C, and
4343/// * "extern void" objects
4344static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4345 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4346 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004347 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004348}
4349
Peter Collingbournee9200682011-05-13 03:29:01 +00004350bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004351 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4352 return Success(FD);
4353 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004354 return VisitVarDecl(E, VD);
4355 return Error(E);
4356}
Richard Smith733237d2011-10-24 23:14:33 +00004357
Richard Smith11562c52011-10-28 17:51:58 +00004358bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004359 CallStackFrame *Frame = 0;
4360 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4361 Frame = Info.CurrentCall;
4362
Richard Smithfec09922011-11-01 16:57:24 +00004363 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004364 if (Frame) {
4365 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004366 return true;
4367 }
Richard Smithce40ad62011-11-12 22:28:03 +00004368 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004369 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004370
Richard Smith3229b742013-05-05 21:17:10 +00004371 APValue *V;
4372 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004373 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004374 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004375 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004376 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4377 return false;
4378 }
Richard Smith3229b742013-05-05 21:17:10 +00004379 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004380}
4381
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004382bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4383 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004384 // Walk through the expression to find the materialized temporary itself.
4385 SmallVector<const Expr *, 2> CommaLHSs;
4386 SmallVector<SubobjectAdjustment, 2> Adjustments;
4387 const Expr *Inner = E->GetTemporaryExpr()->
4388 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004389
Richard Smith84401042013-06-03 05:03:02 +00004390 // If we passed any comma operators, evaluate their LHSs.
4391 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4392 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4393 return false;
4394
Richard Smithe6c01442013-06-05 00:46:14 +00004395 // A materialized temporary with static storage duration can appear within the
4396 // result of a constant expression evaluation, so we need to preserve its
4397 // value for use outside this evaluation.
4398 APValue *Value;
4399 if (E->getStorageDuration() == SD_Static) {
4400 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004401 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004402 Result.set(E);
4403 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004404 Value = &Info.CurrentCall->
4405 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004406 Result.set(E, Info.CurrentCall->Index);
4407 }
4408
Richard Smithea4ad5d2013-06-06 08:19:16 +00004409 QualType Type = Inner->getType();
4410
Richard Smith84401042013-06-03 05:03:02 +00004411 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004412 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4413 (E->getStorageDuration() == SD_Static &&
4414 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4415 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004416 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004417 }
Richard Smith84401042013-06-03 05:03:02 +00004418
4419 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004420 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4421 --I;
4422 switch (Adjustments[I].Kind) {
4423 case SubobjectAdjustment::DerivedToBaseAdjustment:
4424 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4425 Type, Result))
4426 return false;
4427 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4428 break;
4429
4430 case SubobjectAdjustment::FieldAdjustment:
4431 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4432 return false;
4433 Type = Adjustments[I].Field->getType();
4434 break;
4435
4436 case SubobjectAdjustment::MemberPointerAdjustment:
4437 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4438 Adjustments[I].Ptr.RHS))
4439 return false;
4440 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4441 break;
4442 }
4443 }
4444
4445 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004446}
4447
Peter Collingbournee9200682011-05-13 03:29:01 +00004448bool
4449LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004450 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4451 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4452 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004453 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004454}
4455
Richard Smith6e525142011-12-27 12:18:28 +00004456bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004457 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004458 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004459
4460 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4461 << E->getExprOperand()->getType()
4462 << E->getExprOperand()->getSourceRange();
4463 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004464}
4465
Francois Pichet0066db92012-04-16 04:08:35 +00004466bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4467 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004468}
Francois Pichet0066db92012-04-16 04:08:35 +00004469
Peter Collingbournee9200682011-05-13 03:29:01 +00004470bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004471 // Handle static data members.
4472 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4473 VisitIgnoredValue(E->getBase());
4474 return VisitVarDecl(E, VD);
4475 }
4476
Richard Smith254a73d2011-10-28 22:34:42 +00004477 // Handle static member functions.
4478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4479 if (MD->isStatic()) {
4480 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004481 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004482 }
4483 }
4484
Richard Smithd62306a2011-11-10 06:34:14 +00004485 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004486 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004487}
4488
Peter Collingbournee9200682011-05-13 03:29:01 +00004489bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004490 // FIXME: Deal with vectors as array subscript bases.
4491 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004492 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004493
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004494 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004495 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004496
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004497 APSInt Index;
4498 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004499 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004500
Richard Smith861b5b52013-05-07 23:34:45 +00004501 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4502 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004503}
Eli Friedman9a156e52008-11-12 09:44:48 +00004504
Peter Collingbournee9200682011-05-13 03:29:01 +00004505bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004506 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004507}
4508
Richard Smith66c96992012-02-18 22:04:06 +00004509bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4510 if (!Visit(E->getSubExpr()))
4511 return false;
4512 // __real is a no-op on scalar lvalues.
4513 if (E->getSubExpr()->getType()->isAnyComplexType())
4514 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4515 return true;
4516}
4517
4518bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4519 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4520 "lvalue __imag__ on scalar?");
4521 if (!Visit(E->getSubExpr()))
4522 return false;
4523 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4524 return true;
4525}
4526
Richard Smith243ef902013-05-05 23:31:59 +00004527bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4528 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004529 return Error(UO);
4530
4531 if (!this->Visit(UO->getSubExpr()))
4532 return false;
4533
Richard Smith243ef902013-05-05 23:31:59 +00004534 return handleIncDec(
4535 this->Info, UO, Result, UO->getSubExpr()->getType(),
4536 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004537}
4538
4539bool LValueExprEvaluator::VisitCompoundAssignOperator(
4540 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004541 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004542 return Error(CAO);
4543
Richard Smith3229b742013-05-05 21:17:10 +00004544 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004545
4546 // The overall lvalue result is the result of evaluating the LHS.
4547 if (!this->Visit(CAO->getLHS())) {
4548 if (Info.keepEvaluatingAfterFailure())
4549 Evaluate(RHS, this->Info, CAO->getRHS());
4550 return false;
4551 }
4552
Richard Smith3229b742013-05-05 21:17:10 +00004553 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4554 return false;
4555
Richard Smith43e77732013-05-07 04:50:00 +00004556 return handleCompoundAssignment(
4557 this->Info, CAO,
4558 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4559 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004560}
4561
4562bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004563 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4564 return Error(E);
4565
Richard Smith3229b742013-05-05 21:17:10 +00004566 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004567
4568 if (!this->Visit(E->getLHS())) {
4569 if (Info.keepEvaluatingAfterFailure())
4570 Evaluate(NewVal, this->Info, E->getRHS());
4571 return false;
4572 }
4573
Richard Smith3229b742013-05-05 21:17:10 +00004574 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4575 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004576
4577 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004578 NewVal);
4579}
4580
Eli Friedman9a156e52008-11-12 09:44:48 +00004581//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004582// Pointer Evaluation
4583//===----------------------------------------------------------------------===//
4584
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004585namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004586class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004587 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004588 LValue &Result;
4589
Peter Collingbournee9200682011-05-13 03:29:01 +00004590 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004591 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004592 return true;
4593 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004594public:
Mike Stump11289f42009-09-09 15:08:12 +00004595
John McCall45d55e42010-05-07 21:00:08 +00004596 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004597 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004598
Richard Smith2e312c82012-03-03 22:46:17 +00004599 bool Success(const APValue &V, const Expr *E) {
4600 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004601 return true;
4602 }
Richard Smithfddd3842011-12-30 21:15:51 +00004603 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004604 return Success((Expr*)0);
4605 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004606
John McCall45d55e42010-05-07 21:00:08 +00004607 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004608 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004609 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004610 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004611 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004612 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004613 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004614 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004615 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004616 bool VisitCallExpr(const CallExpr *E);
4617 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004618 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004619 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004620 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004621 }
Richard Smithd62306a2011-11-10 06:34:14 +00004622 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004623 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004624 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004625 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004626 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004627 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004628 Result = *Info.CurrentCall->This;
4629 return true;
4630 }
John McCallc07a0c72011-02-17 10:25:35 +00004631
Eli Friedman449fe542009-03-23 04:56:01 +00004632 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004633};
Chris Lattner05706e882008-07-11 18:11:29 +00004634} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004635
John McCall45d55e42010-05-07 21:00:08 +00004636static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004637 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004638 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004639}
4640
John McCall45d55e42010-05-07 21:00:08 +00004641bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004642 if (E->getOpcode() != BO_Add &&
4643 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004644 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004645
Chris Lattner05706e882008-07-11 18:11:29 +00004646 const Expr *PExp = E->getLHS();
4647 const Expr *IExp = E->getRHS();
4648 if (IExp->getType()->isPointerType())
4649 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004650
Richard Smith253c2a32012-01-27 01:14:48 +00004651 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4652 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004653 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004654
John McCall45d55e42010-05-07 21:00:08 +00004655 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004656 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004657 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004658
4659 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004660 if (E->getOpcode() == BO_Sub)
4661 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004662
Ted Kremenek28831752012-08-23 20:46:57 +00004663 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004664 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4665 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004666}
Eli Friedman9a156e52008-11-12 09:44:48 +00004667
John McCall45d55e42010-05-07 21:00:08 +00004668bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4669 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004670}
Mike Stump11289f42009-09-09 15:08:12 +00004671
Peter Collingbournee9200682011-05-13 03:29:01 +00004672bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4673 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004674
Eli Friedman847a2bc2009-12-27 05:43:15 +00004675 switch (E->getCastKind()) {
4676 default:
4677 break;
4678
John McCalle3027922010-08-25 11:45:40 +00004679 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004680 case CK_CPointerToObjCPointerCast:
4681 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004682 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004683 if (!Visit(SubExpr))
4684 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004685 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4686 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4687 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004688 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004689 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004690 if (SubExpr->getType()->isVoidPointerType())
4691 CCEDiag(E, diag::note_constexpr_invalid_cast)
4692 << 3 << SubExpr->getType();
4693 else
4694 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4695 }
Richard Smith96e0c102011-11-04 02:25:55 +00004696 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004697
Anders Carlsson18275092010-10-31 20:41:46 +00004698 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004699 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004700 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004701 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004702 if (!Result.Base && Result.Offset.isZero())
4703 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004704
Richard Smithd62306a2011-11-10 06:34:14 +00004705 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004706 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004707 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4708 castAs<PointerType>()->getPointeeType(),
4709 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004710
Richard Smith027bf112011-11-17 22:56:20 +00004711 case CK_BaseToDerived:
4712 if (!Visit(E->getSubExpr()))
4713 return false;
4714 if (!Result.Base && Result.Offset.isZero())
4715 return true;
4716 return HandleBaseToDerivedCast(Info, E, Result);
4717
Richard Smith0b0a0b62011-10-29 20:57:55 +00004718 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004719 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004720 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004721
John McCalle3027922010-08-25 11:45:40 +00004722 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004723 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4724
Richard Smith2e312c82012-03-03 22:46:17 +00004725 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004726 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004727 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004728
John McCall45d55e42010-05-07 21:00:08 +00004729 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004730 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4731 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004732 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004733 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004734 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004735 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004736 return true;
4737 } else {
4738 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004739 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004740 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004741 }
4742 }
John McCalle3027922010-08-25 11:45:40 +00004743 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004744 if (SubExpr->isGLValue()) {
4745 if (!EvaluateLValue(SubExpr, Result, Info))
4746 return false;
4747 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004748 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004749 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004750 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004751 return false;
4752 }
Richard Smith96e0c102011-11-04 02:25:55 +00004753 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004754 if (const ConstantArrayType *CAT
4755 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4756 Result.addArray(Info, E, CAT);
4757 else
4758 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004759 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004760
John McCalle3027922010-08-25 11:45:40 +00004761 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004762 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004763 }
4764
Richard Smith11562c52011-10-28 17:51:58 +00004765 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004766}
Chris Lattner05706e882008-07-11 18:11:29 +00004767
Peter Collingbournee9200682011-05-13 03:29:01 +00004768bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004769 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004770 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004771
Richard Smith6cbd65d2013-07-11 02:27:57 +00004772 switch (E->isBuiltinCall()) {
4773 case Builtin::BI__builtin_addressof:
4774 return EvaluateLValue(E->getArg(0), Result, Info);
4775
4776 default:
4777 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4778 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004779}
Chris Lattner05706e882008-07-11 18:11:29 +00004780
4781//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004782// Member Pointer Evaluation
4783//===----------------------------------------------------------------------===//
4784
4785namespace {
4786class MemberPointerExprEvaluator
4787 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4788 MemberPtr &Result;
4789
4790 bool Success(const ValueDecl *D) {
4791 Result = MemberPtr(D);
4792 return true;
4793 }
4794public:
4795
4796 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4797 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4798
Richard Smith2e312c82012-03-03 22:46:17 +00004799 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004800 Result.setFrom(V);
4801 return true;
4802 }
Richard Smithfddd3842011-12-30 21:15:51 +00004803 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004804 return Success((const ValueDecl*)0);
4805 }
4806
4807 bool VisitCastExpr(const CastExpr *E);
4808 bool VisitUnaryAddrOf(const UnaryOperator *E);
4809};
4810} // end anonymous namespace
4811
4812static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4813 EvalInfo &Info) {
4814 assert(E->isRValue() && E->getType()->isMemberPointerType());
4815 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4816}
4817
4818bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4819 switch (E->getCastKind()) {
4820 default:
4821 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4822
4823 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004824 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004825 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004826
4827 case CK_BaseToDerivedMemberPointer: {
4828 if (!Visit(E->getSubExpr()))
4829 return false;
4830 if (E->path_empty())
4831 return true;
4832 // Base-to-derived member pointer casts store the path in derived-to-base
4833 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4834 // the wrong end of the derived->base arc, so stagger the path by one class.
4835 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4836 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4837 PathI != PathE; ++PathI) {
4838 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4839 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4840 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004841 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004842 }
4843 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4844 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004845 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004846 return true;
4847 }
4848
4849 case CK_DerivedToBaseMemberPointer:
4850 if (!Visit(E->getSubExpr()))
4851 return false;
4852 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4853 PathE = E->path_end(); PathI != PathE; ++PathI) {
4854 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4855 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4856 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004857 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004858 }
4859 return true;
4860 }
4861}
4862
4863bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4864 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4865 // member can be formed.
4866 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4867}
4868
4869//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004870// Record Evaluation
4871//===----------------------------------------------------------------------===//
4872
4873namespace {
4874 class RecordExprEvaluator
4875 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4876 const LValue &This;
4877 APValue &Result;
4878 public:
4879
4880 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4881 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4882
Richard Smith2e312c82012-03-03 22:46:17 +00004883 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004884 Result = V;
4885 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004886 }
Richard Smithfddd3842011-12-30 21:15:51 +00004887 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004888
Richard Smithe97cbd72011-11-11 04:05:33 +00004889 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004890 bool VisitInitListExpr(const InitListExpr *E);
4891 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004892 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004893 };
4894}
4895
Richard Smithfddd3842011-12-30 21:15:51 +00004896/// Perform zero-initialization on an object of non-union class type.
4897/// C++11 [dcl.init]p5:
4898/// To zero-initialize an object or reference of type T means:
4899/// [...]
4900/// -- if T is a (possibly cv-qualified) non-union class type,
4901/// each non-static data member and each base-class subobject is
4902/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004903static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4904 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004905 const LValue &This, APValue &Result) {
4906 assert(!RD->isUnion() && "Expected non-union class type");
4907 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4908 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4909 std::distance(RD->field_begin(), RD->field_end()));
4910
John McCalld7bca762012-05-01 00:38:49 +00004911 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004912 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4913
4914 if (CD) {
4915 unsigned Index = 0;
4916 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004917 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004918 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4919 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004920 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4921 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004922 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004923 Result.getStructBase(Index)))
4924 return false;
4925 }
4926 }
4927
Richard Smitha8105bc2012-01-06 16:39:00 +00004928 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4929 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004930 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004931 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004932 continue;
4933
4934 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004935 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004936 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004937
David Blaikie2d7c57e2012-04-30 02:36:29 +00004938 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004939 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004940 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004941 return false;
4942 }
4943
4944 return true;
4945}
4946
4947bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4948 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004949 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004950 if (RD->isUnion()) {
4951 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4952 // object's first non-static named data member is zero-initialized
4953 RecordDecl::field_iterator I = RD->field_begin();
4954 if (I == RD->field_end()) {
4955 Result = APValue((const FieldDecl*)0);
4956 return true;
4957 }
4958
4959 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004960 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004961 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004962 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004963 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004964 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004965 }
4966
Richard Smith5d108602012-02-17 00:44:16 +00004967 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004968 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004969 return false;
4970 }
4971
Richard Smitha8105bc2012-01-06 16:39:00 +00004972 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004973}
4974
Richard Smithe97cbd72011-11-11 04:05:33 +00004975bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4976 switch (E->getCastKind()) {
4977 default:
4978 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4979
4980 case CK_ConstructorConversion:
4981 return Visit(E->getSubExpr());
4982
4983 case CK_DerivedToBase:
4984 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004985 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004986 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004987 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004988 if (!DerivedObject.isStruct())
4989 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004990
4991 // Derived-to-base rvalue conversion: just slice off the derived part.
4992 APValue *Value = &DerivedObject;
4993 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4994 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4995 PathE = E->path_end(); PathI != PathE; ++PathI) {
4996 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4997 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4998 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4999 RD = Base;
5000 }
5001 Result = *Value;
5002 return true;
5003 }
5004 }
5005}
5006
Richard Smithd62306a2011-11-10 06:34:14 +00005007bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5008 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005009 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005010 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5011
5012 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005013 const FieldDecl *Field = E->getInitializedFieldInUnion();
5014 Result = APValue(Field);
5015 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005016 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005017
5018 // If the initializer list for a union does not contain any elements, the
5019 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005020 // FIXME: The element should be initialized from an initializer list.
5021 // Is this difference ever observable for initializer lists which
5022 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005023 ImplicitValueInitExpr VIE(Field->getType());
5024 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5025
Richard Smithd62306a2011-11-10 06:34:14 +00005026 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005027 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5028 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005029
5030 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5031 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5032 isa<CXXDefaultInitExpr>(InitExpr));
5033
Richard Smithb228a862012-02-15 02:18:13 +00005034 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005035 }
5036
5037 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5038 "initializer list for class with base classes");
5039 Result = APValue(APValue::UninitStruct(), 0,
5040 std::distance(RD->field_begin(), RD->field_end()));
5041 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005042 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005043 for (RecordDecl::field_iterator Field = RD->field_begin(),
5044 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5045 // Anonymous bit-fields are not considered members of the class for
5046 // purposes of aggregate initialization.
5047 if (Field->isUnnamedBitfield())
5048 continue;
5049
5050 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005051
Richard Smith253c2a32012-01-27 01:14:48 +00005052 bool HaveInit = ElementNo < E->getNumInits();
5053
5054 // FIXME: Diagnostics here should point to the end of the initializer
5055 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005056 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00005057 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005058 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005059
5060 // Perform an implicit value-initialization for members beyond the end of
5061 // the initializer list.
5062 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005063 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005064
Richard Smith852c9db2013-04-20 22:23:05 +00005065 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5066 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5067 isa<CXXDefaultInitExpr>(Init));
5068
Richard Smith49ca8aa2013-08-06 07:09:20 +00005069 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5070 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5071 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5072 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005073 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005074 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005075 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005076 }
5077 }
5078
Richard Smith253c2a32012-01-27 01:14:48 +00005079 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005080}
5081
5082bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5083 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005084 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5085
Richard Smithfddd3842011-12-30 21:15:51 +00005086 bool ZeroInit = E->requiresZeroInitialization();
5087 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005088 // If we've already performed zero-initialization, we're already done.
5089 if (!Result.isUninit())
5090 return true;
5091
Richard Smithfddd3842011-12-30 21:15:51 +00005092 if (ZeroInit)
5093 return ZeroInitialization(E);
5094
Richard Smithcc36f692011-12-22 02:22:31 +00005095 const CXXRecordDecl *RD = FD->getParent();
5096 if (RD->isUnion())
5097 Result = APValue((FieldDecl*)0);
5098 else
5099 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5100 std::distance(RD->field_begin(), RD->field_end()));
5101 return true;
5102 }
5103
Richard Smithd62306a2011-11-10 06:34:14 +00005104 const FunctionDecl *Definition = 0;
5105 FD->getBody(Definition);
5106
Richard Smith357362d2011-12-13 06:39:58 +00005107 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5108 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005109
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005110 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005111 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005112 if (const MaterializeTemporaryExpr *ME
5113 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5114 return Visit(ME->GetTemporaryExpr());
5115
Richard Smithfddd3842011-12-30 21:15:51 +00005116 if (ZeroInit && !ZeroInitialization(E))
5117 return false;
5118
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005119 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005120 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005121 cast<CXXConstructorDecl>(Definition), Info,
5122 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005123}
5124
Richard Smithcc1b96d2013-06-12 22:31:48 +00005125bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5126 const CXXStdInitializerListExpr *E) {
5127 const ConstantArrayType *ArrayType =
5128 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5129
5130 LValue Array;
5131 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5132 return false;
5133
5134 // Get a pointer to the first element of the array.
5135 Array.addArray(Info, E, ArrayType);
5136
5137 // FIXME: Perform the checks on the field types in SemaInit.
5138 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5139 RecordDecl::field_iterator Field = Record->field_begin();
5140 if (Field == Record->field_end())
5141 return Error(E);
5142
5143 // Start pointer.
5144 if (!Field->getType()->isPointerType() ||
5145 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5146 ArrayType->getElementType()))
5147 return Error(E);
5148
5149 // FIXME: What if the initializer_list type has base classes, etc?
5150 Result = APValue(APValue::UninitStruct(), 0, 2);
5151 Array.moveInto(Result.getStructField(0));
5152
5153 if (++Field == Record->field_end())
5154 return Error(E);
5155
5156 if (Field->getType()->isPointerType() &&
5157 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5158 ArrayType->getElementType())) {
5159 // End pointer.
5160 if (!HandleLValueArrayAdjustment(Info, E, Array,
5161 ArrayType->getElementType(),
5162 ArrayType->getSize().getZExtValue()))
5163 return false;
5164 Array.moveInto(Result.getStructField(1));
5165 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5166 // Length.
5167 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5168 else
5169 return Error(E);
5170
5171 if (++Field != Record->field_end())
5172 return Error(E);
5173
5174 return true;
5175}
5176
Richard Smithd62306a2011-11-10 06:34:14 +00005177static bool EvaluateRecord(const Expr *E, const LValue &This,
5178 APValue &Result, EvalInfo &Info) {
5179 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005180 "can't evaluate expression as a record rvalue");
5181 return RecordExprEvaluator(Info, This, Result).Visit(E);
5182}
5183
5184//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005185// Temporary Evaluation
5186//
5187// Temporaries are represented in the AST as rvalues, but generally behave like
5188// lvalues. The full-object of which the temporary is a subobject is implicitly
5189// materialized so that a reference can bind to it.
5190//===----------------------------------------------------------------------===//
5191namespace {
5192class TemporaryExprEvaluator
5193 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5194public:
5195 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5196 LValueExprEvaluatorBaseTy(Info, Result) {}
5197
5198 /// Visit an expression which constructs the value of this temporary.
5199 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005200 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005201 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5202 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005203 }
5204
5205 bool VisitCastExpr(const CastExpr *E) {
5206 switch (E->getCastKind()) {
5207 default:
5208 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5209
5210 case CK_ConstructorConversion:
5211 return VisitConstructExpr(E->getSubExpr());
5212 }
5213 }
5214 bool VisitInitListExpr(const InitListExpr *E) {
5215 return VisitConstructExpr(E);
5216 }
5217 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5218 return VisitConstructExpr(E);
5219 }
5220 bool VisitCallExpr(const CallExpr *E) {
5221 return VisitConstructExpr(E);
5222 }
5223};
5224} // end anonymous namespace
5225
5226/// Evaluate an expression of record type as a temporary.
5227static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005228 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005229 return TemporaryExprEvaluator(Info, Result).Visit(E);
5230}
5231
5232//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005233// Vector Evaluation
5234//===----------------------------------------------------------------------===//
5235
5236namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005237 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005238 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5239 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005240 public:
Mike Stump11289f42009-09-09 15:08:12 +00005241
Richard Smith2d406342011-10-22 21:10:00 +00005242 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5243 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005244
Richard Smith2d406342011-10-22 21:10:00 +00005245 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5246 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5247 // FIXME: remove this APValue copy.
5248 Result = APValue(V.data(), V.size());
5249 return true;
5250 }
Richard Smith2e312c82012-03-03 22:46:17 +00005251 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005252 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005253 Result = V;
5254 return true;
5255 }
Richard Smithfddd3842011-12-30 21:15:51 +00005256 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005257
Richard Smith2d406342011-10-22 21:10:00 +00005258 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005259 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005260 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005261 bool VisitInitListExpr(const InitListExpr *E);
5262 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005263 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005264 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005265 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005266 };
5267} // end anonymous namespace
5268
5269static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005270 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005271 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005272}
5273
Richard Smith2d406342011-10-22 21:10:00 +00005274bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5275 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005276 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005277
Richard Smith161f09a2011-12-06 22:44:34 +00005278 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005279 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005280
Eli Friedmanc757de22011-03-25 00:43:55 +00005281 switch (E->getCastKind()) {
5282 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005283 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005284 if (SETy->isIntegerType()) {
5285 APSInt IntResult;
5286 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005287 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005288 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005289 } else if (SETy->isRealFloatingType()) {
5290 APFloat F(0.0);
5291 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005292 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005293 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005294 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005295 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005296 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005297
5298 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005299 SmallVector<APValue, 4> Elts(NElts, Val);
5300 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005301 }
Eli Friedman803acb32011-12-22 03:51:45 +00005302 case CK_BitCast: {
5303 // Evaluate the operand into an APInt we can extract from.
5304 llvm::APInt SValInt;
5305 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5306 return false;
5307 // Extract the elements
5308 QualType EltTy = VTy->getElementType();
5309 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5310 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5311 SmallVector<APValue, 4> Elts;
5312 if (EltTy->isRealFloatingType()) {
5313 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005314 unsigned FloatEltSize = EltSize;
5315 if (&Sem == &APFloat::x87DoubleExtended)
5316 FloatEltSize = 80;
5317 for (unsigned i = 0; i < NElts; i++) {
5318 llvm::APInt Elt;
5319 if (BigEndian)
5320 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5321 else
5322 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005323 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005324 }
5325 } else if (EltTy->isIntegerType()) {
5326 for (unsigned i = 0; i < NElts; i++) {
5327 llvm::APInt Elt;
5328 if (BigEndian)
5329 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5330 else
5331 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5332 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5333 }
5334 } else {
5335 return Error(E);
5336 }
5337 return Success(Elts, E);
5338 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005339 default:
Richard Smith11562c52011-10-28 17:51:58 +00005340 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005341 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005342}
5343
Richard Smith2d406342011-10-22 21:10:00 +00005344bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005345VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005346 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005347 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005348 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005349
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005350 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005351 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005352
Eli Friedmanb9c71292012-01-03 23:24:20 +00005353 // The number of initializers can be less than the number of
5354 // vector elements. For OpenCL, this can be due to nested vector
5355 // initialization. For GCC compatibility, missing trailing elements
5356 // should be initialized with zeroes.
5357 unsigned CountInits = 0, CountElts = 0;
5358 while (CountElts < NumElements) {
5359 // Handle nested vector initialization.
5360 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005361 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005362 APValue v;
5363 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5364 return Error(E);
5365 unsigned vlen = v.getVectorLength();
5366 for (unsigned j = 0; j < vlen; j++)
5367 Elements.push_back(v.getVectorElt(j));
5368 CountElts += vlen;
5369 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005370 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005371 if (CountInits < NumInits) {
5372 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005373 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005374 } else // trailing integer zero.
5375 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5376 Elements.push_back(APValue(sInt));
5377 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005378 } else {
5379 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005380 if (CountInits < NumInits) {
5381 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005382 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005383 } else // trailing float zero.
5384 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5385 Elements.push_back(APValue(f));
5386 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005387 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005388 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005389 }
Richard Smith2d406342011-10-22 21:10:00 +00005390 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005391}
5392
Richard Smith2d406342011-10-22 21:10:00 +00005393bool
Richard Smithfddd3842011-12-30 21:15:51 +00005394VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005395 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005396 QualType EltTy = VT->getElementType();
5397 APValue ZeroElement;
5398 if (EltTy->isIntegerType())
5399 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5400 else
5401 ZeroElement =
5402 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5403
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005404 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005405 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005406}
5407
Richard Smith2d406342011-10-22 21:10:00 +00005408bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005409 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005410 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005411}
5412
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005413//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005414// Array Evaluation
5415//===----------------------------------------------------------------------===//
5416
5417namespace {
5418 class ArrayExprEvaluator
5419 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005420 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005421 APValue &Result;
5422 public:
5423
Richard Smithd62306a2011-11-10 06:34:14 +00005424 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5425 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005426
5427 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005428 assert((V.isArray() || V.isLValue()) &&
5429 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005430 Result = V;
5431 return true;
5432 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005433
Richard Smithfddd3842011-12-30 21:15:51 +00005434 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005435 const ConstantArrayType *CAT =
5436 Info.Ctx.getAsConstantArrayType(E->getType());
5437 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005438 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005439
5440 Result = APValue(APValue::UninitArray(), 0,
5441 CAT->getSize().getZExtValue());
5442 if (!Result.hasArrayFiller()) return true;
5443
Richard Smithfddd3842011-12-30 21:15:51 +00005444 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005445 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005446 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005447 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005448 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005449 }
5450
Richard Smithf3e9e432011-11-07 09:22:26 +00005451 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005452 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005453 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5454 const LValue &Subobject,
5455 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005456 };
5457} // end anonymous namespace
5458
Richard Smithd62306a2011-11-10 06:34:14 +00005459static bool EvaluateArray(const Expr *E, const LValue &This,
5460 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005461 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005462 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005463}
5464
5465bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5466 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5467 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005468 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005469
Richard Smithca2cfbf2011-12-22 01:07:19 +00005470 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5471 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005472 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005473 LValue LV;
5474 if (!EvaluateLValue(E->getInit(0), LV, Info))
5475 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005476 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005477 LV.moveInto(Val);
5478 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005479 }
5480
Richard Smith253c2a32012-01-27 01:14:48 +00005481 bool Success = true;
5482
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005483 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5484 "zero-initialized array shouldn't have any initialized elts");
5485 APValue Filler;
5486 if (Result.isArray() && Result.hasArrayFiller())
5487 Filler = Result.getArrayFiller();
5488
Richard Smith9543c5e2013-04-22 14:44:29 +00005489 unsigned NumEltsToInit = E->getNumInits();
5490 unsigned NumElts = CAT->getSize().getZExtValue();
5491 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5492
5493 // If the initializer might depend on the array index, run it for each
5494 // array element. For now, just whitelist non-class value-initialization.
5495 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5496 NumEltsToInit = NumElts;
5497
5498 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005499
5500 // If the array was previously zero-initialized, preserve the
5501 // zero-initialized values.
5502 if (!Filler.isUninit()) {
5503 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5504 Result.getArrayInitializedElt(I) = Filler;
5505 if (Result.hasArrayFiller())
5506 Result.getArrayFiller() = Filler;
5507 }
5508
Richard Smithd62306a2011-11-10 06:34:14 +00005509 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005510 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005511 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5512 const Expr *Init =
5513 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005514 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005515 Info, Subobject, Init) ||
5516 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005517 CAT->getElementType(), 1)) {
5518 if (!Info.keepEvaluatingAfterFailure())
5519 return false;
5520 Success = false;
5521 }
Richard Smithd62306a2011-11-10 06:34:14 +00005522 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005523
Richard Smith9543c5e2013-04-22 14:44:29 +00005524 if (!Result.hasArrayFiller())
5525 return Success;
5526
5527 // If we get here, we have a trivial filler, which we can just evaluate
5528 // once and splat over the rest of the array elements.
5529 assert(FillerExpr && "no array filler for incomplete init list");
5530 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5531 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005532}
5533
Richard Smith027bf112011-11-17 22:56:20 +00005534bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005535 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5536}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005537
Richard Smith9543c5e2013-04-22 14:44:29 +00005538bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5539 const LValue &Subobject,
5540 APValue *Value,
5541 QualType Type) {
5542 bool HadZeroInit = !Value->isUninit();
5543
5544 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5545 unsigned N = CAT->getSize().getZExtValue();
5546
5547 // Preserve the array filler if we had prior zero-initialization.
5548 APValue Filler =
5549 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5550 : APValue();
5551
5552 *Value = APValue(APValue::UninitArray(), N, N);
5553
5554 if (HadZeroInit)
5555 for (unsigned I = 0; I != N; ++I)
5556 Value->getArrayInitializedElt(I) = Filler;
5557
5558 // Initialize the elements.
5559 LValue ArrayElt = Subobject;
5560 ArrayElt.addArray(Info, E, CAT);
5561 for (unsigned I = 0; I != N; ++I)
5562 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5563 CAT->getElementType()) ||
5564 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5565 CAT->getElementType(), 1))
5566 return false;
5567
5568 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005569 }
Richard Smith027bf112011-11-17 22:56:20 +00005570
Richard Smith9543c5e2013-04-22 14:44:29 +00005571 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005572 return Error(E);
5573
Richard Smith027bf112011-11-17 22:56:20 +00005574 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005575
Richard Smithfddd3842011-12-30 21:15:51 +00005576 bool ZeroInit = E->requiresZeroInitialization();
5577 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005578 if (HadZeroInit)
5579 return true;
5580
Richard Smithfddd3842011-12-30 21:15:51 +00005581 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005582 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005583 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005584 }
5585
Richard Smithcc36f692011-12-22 02:22:31 +00005586 const CXXRecordDecl *RD = FD->getParent();
5587 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005588 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005589 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005590 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005591 APValue(APValue::UninitStruct(), RD->getNumBases(),
5592 std::distance(RD->field_begin(), RD->field_end()));
5593 return true;
5594 }
5595
Richard Smith027bf112011-11-17 22:56:20 +00005596 const FunctionDecl *Definition = 0;
5597 FD->getBody(Definition);
5598
Richard Smith357362d2011-12-13 06:39:58 +00005599 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5600 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005601
Richard Smith9eae7232012-01-12 18:54:33 +00005602 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005603 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005604 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005605 return false;
5606 }
5607
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005608 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005609 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005610 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005611 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005612}
5613
Richard Smithf3e9e432011-11-07 09:22:26 +00005614//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005615// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005616//
5617// As a GNU extension, we support casting pointers to sufficiently-wide integer
5618// types and back in constant folding. Integer values are thus represented
5619// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005620//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005621
5622namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005623class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005624 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005625 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005626public:
Richard Smith2e312c82012-03-03 22:46:17 +00005627 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005628 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005629
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005630 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005631 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005632 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005633 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005634 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005635 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005636 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005637 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005638 return true;
5639 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005640 bool Success(const llvm::APSInt &SI, const Expr *E) {
5641 return Success(SI, E, Result);
5642 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005643
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005644 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005645 assert(E->getType()->isIntegralOrEnumerationType() &&
5646 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005647 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005648 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005649 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005650 Result.getInt().setIsUnsigned(
5651 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005652 return true;
5653 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005654 bool Success(const llvm::APInt &I, const Expr *E) {
5655 return Success(I, E, Result);
5656 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005657
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005658 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005659 assert(E->getType()->isIntegralOrEnumerationType() &&
5660 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005661 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005662 return true;
5663 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005664 bool Success(uint64_t Value, const Expr *E) {
5665 return Success(Value, E, Result);
5666 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005667
Ken Dyckdbc01912011-03-11 02:13:43 +00005668 bool Success(CharUnits Size, const Expr *E) {
5669 return Success(Size.getQuantity(), E);
5670 }
5671
Richard Smith2e312c82012-03-03 22:46:17 +00005672 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005673 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005674 Result = V;
5675 return true;
5676 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005677 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
Richard Smithfddd3842011-12-30 21:15:51 +00005680 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005681
Peter Collingbournee9200682011-05-13 03:29:01 +00005682 //===--------------------------------------------------------------------===//
5683 // Visitor Methods
5684 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005685
Chris Lattner7174bf32008-07-12 00:38:25 +00005686 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005687 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005688 }
5689 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005690 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005691 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005692
5693 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5694 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005695 if (CheckReferencedDecl(E, E->getDecl()))
5696 return true;
5697
5698 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005699 }
5700 bool VisitMemberExpr(const MemberExpr *E) {
5701 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005702 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005703 return true;
5704 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005705
5706 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005707 }
5708
Peter Collingbournee9200682011-05-13 03:29:01 +00005709 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005710 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005711 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005712 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005713
Peter Collingbournee9200682011-05-13 03:29:01 +00005714 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005715 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005716
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005717 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005718 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005719 }
Mike Stump11289f42009-09-09 15:08:12 +00005720
Ted Kremeneke65b0862012-03-06 20:05:56 +00005721 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5722 return Success(E->getValue(), E);
5723 }
5724
Richard Smith4ce706a2011-10-11 21:43:33 +00005725 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005726 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005727 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005728 }
5729
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005730 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005731 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005732 }
5733
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005734 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5735 return Success(E->getValue(), E);
5736 }
5737
Douglas Gregor29c42f22012-02-24 07:38:34 +00005738 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5739 return Success(E->getValue(), E);
5740 }
5741
John Wiegley6242b6a2011-04-28 00:16:57 +00005742 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5743 return Success(E->getValue(), E);
5744 }
5745
John Wiegleyf9f65842011-04-25 06:54:41 +00005746 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5747 return Success(E->getValue(), E);
5748 }
5749
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005750 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005751 bool VisitUnaryImag(const UnaryOperator *E);
5752
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005753 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005754 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005755
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005756private:
Ken Dyck160146e2010-01-27 17:10:57 +00005757 CharUnits GetAlignOfExpr(const Expr *E);
5758 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005759 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005760 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005761 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005762};
Chris Lattner05706e882008-07-11 18:11:29 +00005763} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005764
Richard Smith11562c52011-10-28 17:51:58 +00005765/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5766/// produce either the integer value or a pointer.
5767///
5768/// GCC has a heinous extension which folds casts between pointer types and
5769/// pointer-sized integral types. We support this by allowing the evaluation of
5770/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5771/// Some simple arithmetic on such values is supported (they are treated much
5772/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005773static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005774 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005775 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005776 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005777}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005778
Richard Smithf57d8cb2011-12-09 22:58:01 +00005779static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005780 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005781 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005782 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005783 if (!Val.isInt()) {
5784 // FIXME: It would be better to produce the diagnostic for casting
5785 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005786 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005787 return false;
5788 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005789 Result = Val.getInt();
5790 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005791}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005792
Richard Smithf57d8cb2011-12-09 22:58:01 +00005793/// Check whether the given declaration can be directly converted to an integral
5794/// rvalue. If not, no diagnostic is produced; there are other things we can
5795/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005796bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005797 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005798 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005799 // Check for signedness/width mismatches between E type and ECD value.
5800 bool SameSign = (ECD->getInitVal().isSigned()
5801 == E->getType()->isSignedIntegerOrEnumerationType());
5802 bool SameWidth = (ECD->getInitVal().getBitWidth()
5803 == Info.Ctx.getIntWidth(E->getType()));
5804 if (SameSign && SameWidth)
5805 return Success(ECD->getInitVal(), E);
5806 else {
5807 // Get rid of mismatch (otherwise Success assertions will fail)
5808 // by computing a new value matching the type of E.
5809 llvm::APSInt Val = ECD->getInitVal();
5810 if (!SameSign)
5811 Val.setIsSigned(!ECD->getInitVal().isSigned());
5812 if (!SameWidth)
5813 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5814 return Success(Val, E);
5815 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005816 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005817 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005818}
5819
Chris Lattner86ee2862008-10-06 06:40:35 +00005820/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5821/// as GCC.
5822static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5823 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005824 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005825 enum gcc_type_class {
5826 no_type_class = -1,
5827 void_type_class, integer_type_class, char_type_class,
5828 enumeral_type_class, boolean_type_class,
5829 pointer_type_class, reference_type_class, offset_type_class,
5830 real_type_class, complex_type_class,
5831 function_type_class, method_type_class,
5832 record_type_class, union_type_class,
5833 array_type_class, string_type_class,
5834 lang_type_class
5835 };
Mike Stump11289f42009-09-09 15:08:12 +00005836
5837 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005838 // ideal, however it is what gcc does.
5839 if (E->getNumArgs() == 0)
5840 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005841
Chris Lattner86ee2862008-10-06 06:40:35 +00005842 QualType ArgTy = E->getArg(0)->getType();
5843 if (ArgTy->isVoidType())
5844 return void_type_class;
5845 else if (ArgTy->isEnumeralType())
5846 return enumeral_type_class;
5847 else if (ArgTy->isBooleanType())
5848 return boolean_type_class;
5849 else if (ArgTy->isCharType())
5850 return string_type_class; // gcc doesn't appear to use char_type_class
5851 else if (ArgTy->isIntegerType())
5852 return integer_type_class;
5853 else if (ArgTy->isPointerType())
5854 return pointer_type_class;
5855 else if (ArgTy->isReferenceType())
5856 return reference_type_class;
5857 else if (ArgTy->isRealType())
5858 return real_type_class;
5859 else if (ArgTy->isComplexType())
5860 return complex_type_class;
5861 else if (ArgTy->isFunctionType())
5862 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005863 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005864 return record_type_class;
5865 else if (ArgTy->isUnionType())
5866 return union_type_class;
5867 else if (ArgTy->isArrayType())
5868 return array_type_class;
5869 else if (ArgTy->isUnionType())
5870 return union_type_class;
5871 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005872 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005873}
5874
Richard Smith5fab0c92011-12-28 19:48:30 +00005875/// EvaluateBuiltinConstantPForLValue - Determine the result of
5876/// __builtin_constant_p when applied to the given lvalue.
5877///
5878/// An lvalue is only "constant" if it is a pointer or reference to the first
5879/// character of a string literal.
5880template<typename LValue>
5881static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005882 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005883 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5884}
5885
5886/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5887/// GCC as we can manage.
5888static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5889 QualType ArgType = Arg->getType();
5890
5891 // __builtin_constant_p always has one operand. The rules which gcc follows
5892 // are not precisely documented, but are as follows:
5893 //
5894 // - If the operand is of integral, floating, complex or enumeration type,
5895 // and can be folded to a known value of that type, it returns 1.
5896 // - If the operand and can be folded to a pointer to the first character
5897 // of a string literal (or such a pointer cast to an integral type), it
5898 // returns 1.
5899 //
5900 // Otherwise, it returns 0.
5901 //
5902 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5903 // its support for this does not currently work.
5904 if (ArgType->isIntegralOrEnumerationType()) {
5905 Expr::EvalResult Result;
5906 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5907 return false;
5908
5909 APValue &V = Result.Val;
5910 if (V.getKind() == APValue::Int)
5911 return true;
5912
5913 return EvaluateBuiltinConstantPForLValue(V);
5914 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5915 return Arg->isEvaluatable(Ctx);
5916 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5917 LValue LV;
5918 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005919 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005920 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5921 : EvaluatePointer(Arg, LV, Info)) &&
5922 !Status.HasSideEffects)
5923 return EvaluateBuiltinConstantPForLValue(LV);
5924 }
5925
5926 // Anything else isn't considered to be sufficiently constant.
5927 return false;
5928}
5929
John McCall95007602010-05-10 23:27:23 +00005930/// Retrieves the "underlying object type" of the given expression,
5931/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005932QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5933 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5934 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005935 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005936 } else if (const Expr *E = B.get<const Expr*>()) {
5937 if (isa<CompoundLiteralExpr>(E))
5938 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005939 }
5940
5941 return QualType();
5942}
5943
Peter Collingbournee9200682011-05-13 03:29:01 +00005944bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005945 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005946
5947 {
5948 // The operand of __builtin_object_size is never evaluated for side-effects.
5949 // If there are any, but we can determine the pointed-to object anyway, then
5950 // ignore the side-effects.
5951 SpeculativeEvaluationRAII SpeculativeEval(Info);
5952 if (!EvaluatePointer(E->getArg(0), Base, Info))
5953 return false;
5954 }
John McCall95007602010-05-10 23:27:23 +00005955
5956 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005957 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005958
Richard Smithce40ad62011-11-12 22:28:03 +00005959 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005960 if (T.isNull() ||
5961 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005962 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005963 T->isVariablyModifiedType() ||
5964 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005965 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005966
5967 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5968 CharUnits Offset = Base.getLValueOffset();
5969
5970 if (!Offset.isNegative() && Offset <= Size)
5971 Size -= Offset;
5972 else
5973 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005974 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005975}
5976
Peter Collingbournee9200682011-05-13 03:29:01 +00005977bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005978 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005979 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005980 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005981
5982 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005983 if (TryEvaluateBuiltinObjectSize(E))
5984 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005985
Richard Smith0421ce72012-08-07 04:16:51 +00005986 // If evaluating the argument has side-effects, we can't determine the size
5987 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5988 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005989 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005990 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005991 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005992 return Success(0, E);
5993 }
Mike Stump876387b2009-10-27 22:09:17 +00005994
Richard Smith01ade172012-05-23 04:13:20 +00005995 // Expression had no side effects, but we couldn't statically determine the
5996 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005997 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005998 }
5999
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006000 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006001 case Builtin::BI__builtin_bswap32:
6002 case Builtin::BI__builtin_bswap64: {
6003 APSInt Val;
6004 if (!EvaluateInteger(E->getArg(0), Val, Info))
6005 return false;
6006
6007 return Success(Val.byteSwap(), E);
6008 }
6009
Richard Smith8889a3d2013-06-13 06:26:32 +00006010 case Builtin::BI__builtin_classify_type:
6011 return Success(EvaluateBuiltinClassifyType(E), E);
6012
6013 // FIXME: BI__builtin_clrsb
6014 // FIXME: BI__builtin_clrsbl
6015 // FIXME: BI__builtin_clrsbll
6016
Richard Smith80b3c8e2013-06-13 05:04:16 +00006017 case Builtin::BI__builtin_clz:
6018 case Builtin::BI__builtin_clzl:
6019 case Builtin::BI__builtin_clzll: {
6020 APSInt Val;
6021 if (!EvaluateInteger(E->getArg(0), Val, Info))
6022 return false;
6023 if (!Val)
6024 return Error(E);
6025
6026 return Success(Val.countLeadingZeros(), E);
6027 }
6028
Richard Smith8889a3d2013-06-13 06:26:32 +00006029 case Builtin::BI__builtin_constant_p:
6030 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6031
Richard Smith80b3c8e2013-06-13 05:04:16 +00006032 case Builtin::BI__builtin_ctz:
6033 case Builtin::BI__builtin_ctzl:
6034 case Builtin::BI__builtin_ctzll: {
6035 APSInt Val;
6036 if (!EvaluateInteger(E->getArg(0), Val, Info))
6037 return false;
6038 if (!Val)
6039 return Error(E);
6040
6041 return Success(Val.countTrailingZeros(), E);
6042 }
6043
Richard Smith8889a3d2013-06-13 06:26:32 +00006044 case Builtin::BI__builtin_eh_return_data_regno: {
6045 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6046 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6047 return Success(Operand, E);
6048 }
6049
6050 case Builtin::BI__builtin_expect:
6051 return Visit(E->getArg(0));
6052
6053 case Builtin::BI__builtin_ffs:
6054 case Builtin::BI__builtin_ffsl:
6055 case Builtin::BI__builtin_ffsll: {
6056 APSInt Val;
6057 if (!EvaluateInteger(E->getArg(0), Val, Info))
6058 return false;
6059
6060 unsigned N = Val.countTrailingZeros();
6061 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6062 }
6063
6064 case Builtin::BI__builtin_fpclassify: {
6065 APFloat Val(0.0);
6066 if (!EvaluateFloat(E->getArg(5), Val, Info))
6067 return false;
6068 unsigned Arg;
6069 switch (Val.getCategory()) {
6070 case APFloat::fcNaN: Arg = 0; break;
6071 case APFloat::fcInfinity: Arg = 1; break;
6072 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6073 case APFloat::fcZero: Arg = 4; break;
6074 }
6075 return Visit(E->getArg(Arg));
6076 }
6077
6078 case Builtin::BI__builtin_isinf_sign: {
6079 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006080 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006081 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6082 }
6083
Richard Smithea3019d2013-10-15 19:07:14 +00006084 case Builtin::BI__builtin_isinf: {
6085 APFloat Val(0.0);
6086 return EvaluateFloat(E->getArg(0), Val, Info) &&
6087 Success(Val.isInfinity() ? 1 : 0, E);
6088 }
6089
6090 case Builtin::BI__builtin_isfinite: {
6091 APFloat Val(0.0);
6092 return EvaluateFloat(E->getArg(0), Val, Info) &&
6093 Success(Val.isFinite() ? 1 : 0, E);
6094 }
6095
6096 case Builtin::BI__builtin_isnan: {
6097 APFloat Val(0.0);
6098 return EvaluateFloat(E->getArg(0), Val, Info) &&
6099 Success(Val.isNaN() ? 1 : 0, E);
6100 }
6101
6102 case Builtin::BI__builtin_isnormal: {
6103 APFloat Val(0.0);
6104 return EvaluateFloat(E->getArg(0), Val, Info) &&
6105 Success(Val.isNormal() ? 1 : 0, E);
6106 }
6107
Richard Smith8889a3d2013-06-13 06:26:32 +00006108 case Builtin::BI__builtin_parity:
6109 case Builtin::BI__builtin_parityl:
6110 case Builtin::BI__builtin_parityll: {
6111 APSInt Val;
6112 if (!EvaluateInteger(E->getArg(0), Val, Info))
6113 return false;
6114
6115 return Success(Val.countPopulation() % 2, E);
6116 }
6117
Richard Smith80b3c8e2013-06-13 05:04:16 +00006118 case Builtin::BI__builtin_popcount:
6119 case Builtin::BI__builtin_popcountl:
6120 case Builtin::BI__builtin_popcountll: {
6121 APSInt Val;
6122 if (!EvaluateInteger(E->getArg(0), Val, Info))
6123 return false;
6124
6125 return Success(Val.countPopulation(), E);
6126 }
6127
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006128 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006129 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006130 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006131 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006132 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6133 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006134 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006135 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006136 case Builtin::BI__builtin_strlen: {
6137 // As an extension, we support __builtin_strlen() as a constant expression,
6138 // and support folding strlen() to a constant.
6139 LValue String;
6140 if (!EvaluatePointer(E->getArg(0), String, Info))
6141 return false;
6142
6143 // Fast path: if it's a string literal, search the string value.
6144 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6145 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006146 // The string literal may have embedded null characters. Find the first
6147 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006148 StringRef Str = S->getBytes();
6149 int64_t Off = String.Offset.getQuantity();
6150 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6151 S->getCharByteWidth() == 1) {
6152 Str = Str.substr(Off);
6153
6154 StringRef::size_type Pos = Str.find(0);
6155 if (Pos != StringRef::npos)
6156 Str = Str.substr(0, Pos);
6157
6158 return Success(Str.size(), E);
6159 }
6160
6161 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006162 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006163
6164 // Slow path: scan the bytes of the string looking for the terminating 0.
6165 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6166 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6167 APValue Char;
6168 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6169 !Char.isInt())
6170 return false;
6171 if (!Char.getInt())
6172 return Success(Strlen, E);
6173 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6174 return false;
6175 }
6176 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006177
Richard Smith01ba47d2012-04-13 00:45:38 +00006178 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006179 case Builtin::BI__atomic_is_lock_free:
6180 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006181 APSInt SizeVal;
6182 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6183 return false;
6184
6185 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6186 // of two less than the maximum inline atomic width, we know it is
6187 // lock-free. If the size isn't a power of two, or greater than the
6188 // maximum alignment where we promote atomics, we know it is not lock-free
6189 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6190 // the answer can only be determined at runtime; for example, 16-byte
6191 // atomics have lock-free implementations on some, but not all,
6192 // x86-64 processors.
6193
6194 // Check power-of-two.
6195 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006196 if (Size.isPowerOfTwo()) {
6197 // Check against inlining width.
6198 unsigned InlineWidthBits =
6199 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6200 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6201 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6202 Size == CharUnits::One() ||
6203 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6204 Expr::NPC_NeverValueDependent))
6205 // OK, we will inline appropriately-aligned operations of this size,
6206 // and _Atomic(T) is appropriately-aligned.
6207 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006208
Richard Smith01ba47d2012-04-13 00:45:38 +00006209 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6210 castAs<PointerType>()->getPointeeType();
6211 if (!PointeeType->isIncompleteType() &&
6212 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6213 // OK, we will inline operations on this object.
6214 return Success(1, E);
6215 }
6216 }
6217 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006218
Richard Smith01ba47d2012-04-13 00:45:38 +00006219 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6220 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006221 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006222 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006223}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006224
Richard Smith8b3497e2011-10-31 01:37:14 +00006225static bool HasSameBase(const LValue &A, const LValue &B) {
6226 if (!A.getLValueBase())
6227 return !B.getLValueBase();
6228 if (!B.getLValueBase())
6229 return false;
6230
Richard Smithce40ad62011-11-12 22:28:03 +00006231 if (A.getLValueBase().getOpaqueValue() !=
6232 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006233 const Decl *ADecl = GetLValueBaseDecl(A);
6234 if (!ADecl)
6235 return false;
6236 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006237 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006238 return false;
6239 }
6240
6241 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006242 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006243}
6244
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006245namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006246
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006247/// \brief Data recursive integer evaluator of certain binary operators.
6248///
6249/// We use a data recursive algorithm for binary operators so that we are able
6250/// to handle extreme cases of chained binary operators without causing stack
6251/// overflow.
6252class DataRecursiveIntBinOpEvaluator {
6253 struct EvalResult {
6254 APValue Val;
6255 bool Failed;
6256
6257 EvalResult() : Failed(false) { }
6258
6259 void swap(EvalResult &RHS) {
6260 Val.swap(RHS.Val);
6261 Failed = RHS.Failed;
6262 RHS.Failed = false;
6263 }
6264 };
6265
6266 struct Job {
6267 const Expr *E;
6268 EvalResult LHSResult; // meaningful only for binary operator expression.
6269 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6270
6271 Job() : StoredInfo(0) { }
6272 void startSpeculativeEval(EvalInfo &Info) {
6273 OldEvalStatus = Info.EvalStatus;
6274 Info.EvalStatus.Diag = 0;
6275 StoredInfo = &Info;
6276 }
6277 ~Job() {
6278 if (StoredInfo) {
6279 StoredInfo->EvalStatus = OldEvalStatus;
6280 }
6281 }
6282 private:
6283 EvalInfo *StoredInfo; // non-null if status changed.
6284 Expr::EvalStatus OldEvalStatus;
6285 };
6286
6287 SmallVector<Job, 16> Queue;
6288
6289 IntExprEvaluator &IntEval;
6290 EvalInfo &Info;
6291 APValue &FinalResult;
6292
6293public:
6294 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6295 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6296
6297 /// \brief True if \param E is a binary operator that we are going to handle
6298 /// data recursively.
6299 /// We handle binary operators that are comma, logical, or that have operands
6300 /// with integral or enumeration type.
6301 static bool shouldEnqueue(const BinaryOperator *E) {
6302 return E->getOpcode() == BO_Comma ||
6303 E->isLogicalOp() ||
6304 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6305 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006306 }
6307
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006308 bool Traverse(const BinaryOperator *E) {
6309 enqueue(E);
6310 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006311 while (!Queue.empty())
6312 process(PrevResult);
6313
6314 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006316 FinalResult.swap(PrevResult.Val);
6317 return true;
6318 }
6319
6320private:
6321 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6322 return IntEval.Success(Value, E, Result);
6323 }
6324 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6325 return IntEval.Success(Value, E, Result);
6326 }
6327 bool Error(const Expr *E) {
6328 return IntEval.Error(E);
6329 }
6330 bool Error(const Expr *E, diag::kind D) {
6331 return IntEval.Error(E, D);
6332 }
6333
6334 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6335 return Info.CCEDiag(E, D);
6336 }
6337
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006338 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6339 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006340 bool &SuppressRHSDiags);
6341
6342 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6343 const BinaryOperator *E, APValue &Result);
6344
6345 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6346 Result.Failed = !Evaluate(Result.Val, Info, E);
6347 if (Result.Failed)
6348 Result.Val = APValue();
6349 }
6350
Richard Trieuba4d0872012-03-21 23:30:30 +00006351 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006352
6353 void enqueue(const Expr *E) {
6354 E = E->IgnoreParens();
6355 Queue.resize(Queue.size()+1);
6356 Queue.back().E = E;
6357 Queue.back().Kind = Job::AnyExprKind;
6358 }
6359};
6360
6361}
6362
6363bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006364 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006365 bool &SuppressRHSDiags) {
6366 if (E->getOpcode() == BO_Comma) {
6367 // Ignore LHS but note if we could not evaluate it.
6368 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006369 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006370 return true;
6371 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006372
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006373 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006374 bool LHSAsBool;
6375 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006376 // We were able to evaluate the LHS, see if we can get away with not
6377 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006378 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6379 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006380 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006381 }
6382 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006383 LHSResult.Failed = true;
6384
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006385 // Since we weren't able to evaluate the left hand side, it
6386 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006387 if (!Info.noteSideEffect())
6388 return false;
6389
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006390 // We can't evaluate the LHS; however, sometimes the result
6391 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6392 // Don't ignore RHS and suppress diagnostics from this arm.
6393 SuppressRHSDiags = true;
6394 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006395
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006396 return true;
6397 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006398
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006399 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6400 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006401
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006402 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006403 return false; // Ignore RHS;
6404
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006405 return true;
6406}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006407
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006408bool DataRecursiveIntBinOpEvaluator::
6409 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6410 const BinaryOperator *E, APValue &Result) {
6411 if (E->getOpcode() == BO_Comma) {
6412 if (RHSResult.Failed)
6413 return false;
6414 Result = RHSResult.Val;
6415 return true;
6416 }
6417
6418 if (E->isLogicalOp()) {
6419 bool lhsResult, rhsResult;
6420 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6421 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6422
6423 if (LHSIsOK) {
6424 if (RHSIsOK) {
6425 if (E->getOpcode() == BO_LOr)
6426 return Success(lhsResult || rhsResult, E, Result);
6427 else
6428 return Success(lhsResult && rhsResult, E, Result);
6429 }
6430 } else {
6431 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006432 // We can't evaluate the LHS; however, sometimes the result
6433 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6434 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006435 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006436 }
6437 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006438
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006439 return false;
6440 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006441
6442 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6443 E->getRHS()->getType()->isIntegralOrEnumerationType());
6444
6445 if (LHSResult.Failed || RHSResult.Failed)
6446 return false;
6447
6448 const APValue &LHSVal = LHSResult.Val;
6449 const APValue &RHSVal = RHSResult.Val;
6450
6451 // Handle cases like (unsigned long)&a + 4.
6452 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6453 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006454 CharUnits AdditionalOffset =
6455 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006456 if (E->getOpcode() == BO_Add)
6457 Result.getLValueOffset() += AdditionalOffset;
6458 else
6459 Result.getLValueOffset() -= AdditionalOffset;
6460 return true;
6461 }
6462
6463 // Handle cases like 4 + (unsigned long)&a
6464 if (E->getOpcode() == BO_Add &&
6465 RHSVal.isLValue() && LHSVal.isInt()) {
6466 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006467 Result.getLValueOffset() +=
6468 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006469 return true;
6470 }
6471
6472 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6473 // Handle (intptr_t)&&A - (intptr_t)&&B.
6474 if (!LHSVal.getLValueOffset().isZero() ||
6475 !RHSVal.getLValueOffset().isZero())
6476 return false;
6477 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6478 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6479 if (!LHSExpr || !RHSExpr)
6480 return false;
6481 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6482 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6483 if (!LHSAddrExpr || !RHSAddrExpr)
6484 return false;
6485 // Make sure both labels come from the same function.
6486 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6487 RHSAddrExpr->getLabel()->getDeclContext())
6488 return false;
6489 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6490 return true;
6491 }
Richard Smith43e77732013-05-07 04:50:00 +00006492
6493 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006494 if (!LHSVal.isInt() || !RHSVal.isInt())
6495 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006496
6497 // Set up the width and signedness manually, in case it can't be deduced
6498 // from the operation we're performing.
6499 // FIXME: Don't do this in the cases where we can deduce it.
6500 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6501 E->getType()->isUnsignedIntegerOrEnumerationType());
6502 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6503 RHSVal.getInt(), Value))
6504 return false;
6505 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006506}
6507
Richard Trieuba4d0872012-03-21 23:30:30 +00006508void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006509 Job &job = Queue.back();
6510
6511 switch (job.Kind) {
6512 case Job::AnyExprKind: {
6513 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6514 if (shouldEnqueue(Bop)) {
6515 job.Kind = Job::BinOpKind;
6516 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006517 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006518 }
6519 }
6520
6521 EvaluateExpr(job.E, Result);
6522 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006523 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006524 }
6525
6526 case Job::BinOpKind: {
6527 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006528 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006529 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006530 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006531 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006532 }
6533 if (SuppressRHSDiags)
6534 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006535 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006536 job.Kind = Job::BinOpVisitedLHSKind;
6537 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006538 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006539 }
6540
6541 case Job::BinOpVisitedLHSKind: {
6542 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6543 EvalResult RHS;
6544 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006545 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006546 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006547 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006548 }
6549 }
6550
6551 llvm_unreachable("Invalid Job::Kind!");
6552}
6553
6554bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6555 if (E->isAssignmentOp())
6556 return Error(E);
6557
6558 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6559 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006560
Anders Carlssonacc79812008-11-16 07:17:21 +00006561 QualType LHSTy = E->getLHS()->getType();
6562 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006563
6564 if (LHSTy->isAnyComplexType()) {
6565 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006566 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006567
Richard Smith253c2a32012-01-27 01:14:48 +00006568 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6569 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006570 return false;
6571
Richard Smith253c2a32012-01-27 01:14:48 +00006572 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006573 return false;
6574
6575 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006576 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006577 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006578 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006579 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6580
John McCalle3027922010-08-25 11:45:40 +00006581 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006582 return Success((CR_r == APFloat::cmpEqual &&
6583 CR_i == APFloat::cmpEqual), E);
6584 else {
John McCalle3027922010-08-25 11:45:40 +00006585 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006586 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006587 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006588 CR_r == APFloat::cmpLessThan ||
6589 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006590 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006591 CR_i == APFloat::cmpLessThan ||
6592 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006593 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006594 } else {
John McCalle3027922010-08-25 11:45:40 +00006595 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006596 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6597 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6598 else {
John McCalle3027922010-08-25 11:45:40 +00006599 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006600 "Invalid compex comparison.");
6601 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6602 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6603 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006604 }
6605 }
Mike Stump11289f42009-09-09 15:08:12 +00006606
Anders Carlssonacc79812008-11-16 07:17:21 +00006607 if (LHSTy->isRealFloatingType() &&
6608 RHSTy->isRealFloatingType()) {
6609 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006610
Richard Smith253c2a32012-01-27 01:14:48 +00006611 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6612 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006613 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006614
Richard Smith253c2a32012-01-27 01:14:48 +00006615 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006616 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006617
Anders Carlssonacc79812008-11-16 07:17:21 +00006618 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006619
Anders Carlssonacc79812008-11-16 07:17:21 +00006620 switch (E->getOpcode()) {
6621 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006622 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006623 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006624 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006625 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006626 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006627 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006628 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006629 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006630 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006631 E);
John McCalle3027922010-08-25 11:45:40 +00006632 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006633 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006634 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006635 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006636 || CR == APFloat::cmpLessThan
6637 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006638 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006639 }
Mike Stump11289f42009-09-09 15:08:12 +00006640
Eli Friedmana38da572009-04-28 19:17:36 +00006641 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006642 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006643 LValue LHSValue, RHSValue;
6644
6645 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6646 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006647 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006648
Richard Smith253c2a32012-01-27 01:14:48 +00006649 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006650 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006651
Richard Smith8b3497e2011-10-31 01:37:14 +00006652 // Reject differing bases from the normal codepath; we special-case
6653 // comparisons to null.
6654 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006655 if (E->getOpcode() == BO_Sub) {
6656 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006657 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6658 return false;
6659 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006660 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006661 if (!LHSExpr || !RHSExpr)
6662 return false;
6663 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6664 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6665 if (!LHSAddrExpr || !RHSAddrExpr)
6666 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006667 // Make sure both labels come from the same function.
6668 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6669 RHSAddrExpr->getLabel()->getDeclContext())
6670 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006671 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006672 return true;
6673 }
Richard Smith83c68212011-10-31 05:11:32 +00006674 // Inequalities and subtractions between unrelated pointers have
6675 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006676 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006677 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006678 // A constant address may compare equal to the address of a symbol.
6679 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006680 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006681 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6682 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006683 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006684 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006685 // distinct addresses. In clang, the result of such a comparison is
6686 // unspecified, so it is not a constant expression. However, we do know
6687 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006688 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6689 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006690 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006691 // We can't tell whether weak symbols will end up pointing to the same
6692 // object.
6693 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006694 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006695 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006696 // (Note that clang defaults to -fmerge-all-constants, which can
6697 // lead to inconsistent results for comparisons involving the address
6698 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006699 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006700 }
Eli Friedman64004332009-03-23 04:38:34 +00006701
Richard Smith1b470412012-02-01 08:10:20 +00006702 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6703 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6704
Richard Smith84f6dcf2012-02-02 01:16:57 +00006705 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6706 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6707
John McCalle3027922010-08-25 11:45:40 +00006708 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006709 // C++11 [expr.add]p6:
6710 // Unless both pointers point to elements of the same array object, or
6711 // one past the last element of the array object, the behavior is
6712 // undefined.
6713 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6714 !AreElementsOfSameArray(getType(LHSValue.Base),
6715 LHSDesignator, RHSDesignator))
6716 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6717
Chris Lattner882bdf22010-04-20 17:13:14 +00006718 QualType Type = E->getLHS()->getType();
6719 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006720
Richard Smithd62306a2011-11-10 06:34:14 +00006721 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006722 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006723 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006724
Richard Smith84c6b3d2013-09-10 21:34:14 +00006725 // As an extension, a type may have zero size (empty struct or union in
6726 // C, array of zero length). Pointer subtraction in such cases has
6727 // undefined behavior, so is not constant.
6728 if (ElementSize.isZero()) {
6729 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6730 << ElementType;
6731 return false;
6732 }
6733
Richard Smith1b470412012-02-01 08:10:20 +00006734 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6735 // and produce incorrect results when it overflows. Such behavior
6736 // appears to be non-conforming, but is common, so perhaps we should
6737 // assume the standard intended for such cases to be undefined behavior
6738 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006739
Richard Smith1b470412012-02-01 08:10:20 +00006740 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6741 // overflow in the final conversion to ptrdiff_t.
6742 APSInt LHS(
6743 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6744 APSInt RHS(
6745 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6746 APSInt ElemSize(
6747 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6748 APSInt TrueResult = (LHS - RHS) / ElemSize;
6749 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6750
6751 if (Result.extend(65) != TrueResult)
6752 HandleOverflow(Info, E, TrueResult, E->getType());
6753 return Success(Result, E);
6754 }
Richard Smithde21b242012-01-31 06:41:30 +00006755
6756 // C++11 [expr.rel]p3:
6757 // Pointers to void (after pointer conversions) can be compared, with a
6758 // result defined as follows: If both pointers represent the same
6759 // address or are both the null pointer value, the result is true if the
6760 // operator is <= or >= and false otherwise; otherwise the result is
6761 // unspecified.
6762 // We interpret this as applying to pointers to *cv* void.
6763 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006764 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006765 CCEDiag(E, diag::note_constexpr_void_comparison);
6766
Richard Smith84f6dcf2012-02-02 01:16:57 +00006767 // C++11 [expr.rel]p2:
6768 // - If two pointers point to non-static data members of the same object,
6769 // or to subobjects or array elements fo such members, recursively, the
6770 // pointer to the later declared member compares greater provided the
6771 // two members have the same access control and provided their class is
6772 // not a union.
6773 // [...]
6774 // - Otherwise pointer comparisons are unspecified.
6775 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6776 E->isRelationalOp()) {
6777 bool WasArrayIndex;
6778 unsigned Mismatch =
6779 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6780 RHSDesignator, WasArrayIndex);
6781 // At the point where the designators diverge, the comparison has a
6782 // specified value if:
6783 // - we are comparing array indices
6784 // - we are comparing fields of a union, or fields with the same access
6785 // Otherwise, the result is unspecified and thus the comparison is not a
6786 // constant expression.
6787 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6788 Mismatch < RHSDesignator.Entries.size()) {
6789 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6790 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6791 if (!LF && !RF)
6792 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6793 else if (!LF)
6794 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6795 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6796 << RF->getParent() << RF;
6797 else if (!RF)
6798 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6799 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6800 << LF->getParent() << LF;
6801 else if (!LF->getParent()->isUnion() &&
6802 LF->getAccess() != RF->getAccess())
6803 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6804 << LF << LF->getAccess() << RF << RF->getAccess()
6805 << LF->getParent();
6806 }
6807 }
6808
Eli Friedman6c31cb42012-04-16 04:30:08 +00006809 // The comparison here must be unsigned, and performed with the same
6810 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006811 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6812 uint64_t CompareLHS = LHSOffset.getQuantity();
6813 uint64_t CompareRHS = RHSOffset.getQuantity();
6814 assert(PtrSize <= 64 && "Unexpected pointer width");
6815 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6816 CompareLHS &= Mask;
6817 CompareRHS &= Mask;
6818
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006819 // If there is a base and this is a relational operator, we can only
6820 // compare pointers within the object in question; otherwise, the result
6821 // depends on where the object is located in memory.
6822 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6823 QualType BaseTy = getType(LHSValue.Base);
6824 if (BaseTy->isIncompleteType())
6825 return Error(E);
6826 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6827 uint64_t OffsetLimit = Size.getQuantity();
6828 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6829 return Error(E);
6830 }
6831
Richard Smith8b3497e2011-10-31 01:37:14 +00006832 switch (E->getOpcode()) {
6833 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006834 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6835 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6836 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6837 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6838 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6839 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006840 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006841 }
6842 }
Richard Smith7bb00672012-02-01 01:42:44 +00006843
6844 if (LHSTy->isMemberPointerType()) {
6845 assert(E->isEqualityOp() && "unexpected member pointer operation");
6846 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6847
6848 MemberPtr LHSValue, RHSValue;
6849
6850 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6851 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6852 return false;
6853
6854 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6855 return false;
6856
6857 // C++11 [expr.eq]p2:
6858 // If both operands are null, they compare equal. Otherwise if only one is
6859 // null, they compare unequal.
6860 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6861 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6862 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6863 }
6864
6865 // Otherwise if either is a pointer to a virtual member function, the
6866 // result is unspecified.
6867 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6868 if (MD->isVirtual())
6869 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6870 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6871 if (MD->isVirtual())
6872 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6873
6874 // Otherwise they compare equal if and only if they would refer to the
6875 // same member of the same most derived object or the same subobject if
6876 // they were dereferenced with a hypothetical object of the associated
6877 // class type.
6878 bool Equal = LHSValue == RHSValue;
6879 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6880 }
6881
Richard Smithab44d9b2012-02-14 22:35:28 +00006882 if (LHSTy->isNullPtrType()) {
6883 assert(E->isComparisonOp() && "unexpected nullptr operation");
6884 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6885 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6886 // are compared, the result is true of the operator is <=, >= or ==, and
6887 // false otherwise.
6888 BinaryOperator::Opcode Opcode = E->getOpcode();
6889 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6890 }
6891
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006892 assert((!LHSTy->isIntegralOrEnumerationType() ||
6893 !RHSTy->isIntegralOrEnumerationType()) &&
6894 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6895 // We can't continue from here for non-integral types.
6896 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006897}
6898
Ken Dyck160146e2010-01-27 17:10:57 +00006899CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006900 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6901 // result shall be the alignment of the referenced type."
6902 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6903 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006904
6905 // __alignof is defined to return the preferred alignment.
6906 return Info.Ctx.toCharUnitsFromBits(
6907 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006908}
6909
Ken Dyck160146e2010-01-27 17:10:57 +00006910CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006911 E = E->IgnoreParens();
6912
John McCall768439e2013-05-06 07:40:34 +00006913 // The kinds of expressions that we have special-case logic here for
6914 // should be kept up to date with the special checks for those
6915 // expressions in Sema.
6916
Chris Lattner68061312009-01-24 21:53:27 +00006917 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006918 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006919 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006920 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6921 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006922
Chris Lattner68061312009-01-24 21:53:27 +00006923 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006924 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6925 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006926
Chris Lattner24aeeab2009-01-24 21:09:06 +00006927 return GetAlignOfType(E->getType());
6928}
6929
6930
Peter Collingbournee190dee2011-03-11 19:24:49 +00006931/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6932/// a result as the expression's type.
6933bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6934 const UnaryExprOrTypeTraitExpr *E) {
6935 switch(E->getKind()) {
6936 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006937 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006938 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006939 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006940 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006941 }
Eli Friedman64004332009-03-23 04:38:34 +00006942
Peter Collingbournee190dee2011-03-11 19:24:49 +00006943 case UETT_VecStep: {
6944 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006945
Peter Collingbournee190dee2011-03-11 19:24:49 +00006946 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006947 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006948
Peter Collingbournee190dee2011-03-11 19:24:49 +00006949 // The vec_step built-in functions that take a 3-component
6950 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6951 if (n == 3)
6952 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006953
Peter Collingbournee190dee2011-03-11 19:24:49 +00006954 return Success(n, E);
6955 } else
6956 return Success(1, E);
6957 }
6958
6959 case UETT_SizeOf: {
6960 QualType SrcTy = E->getTypeOfArgument();
6961 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6962 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006963 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6964 SrcTy = Ref->getPointeeType();
6965
Richard Smithd62306a2011-11-10 06:34:14 +00006966 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006967 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006968 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006969 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006970 }
6971 }
6972
6973 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006974}
6975
Peter Collingbournee9200682011-05-13 03:29:01 +00006976bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006977 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006978 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006979 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006980 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006981 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006982 for (unsigned i = 0; i != n; ++i) {
6983 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6984 switch (ON.getKind()) {
6985 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006986 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006987 APSInt IdxResult;
6988 if (!EvaluateInteger(Idx, IdxResult, Info))
6989 return false;
6990 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6991 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006992 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006993 CurrentType = AT->getElementType();
6994 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6995 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006996 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006997 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006998
Douglas Gregor882211c2010-04-28 22:16:22 +00006999 case OffsetOfExpr::OffsetOfNode::Field: {
7000 FieldDecl *MemberDecl = ON.getField();
7001 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007002 if (!RT)
7003 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007004 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007005 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007006 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007007 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007008 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007009 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007010 CurrentType = MemberDecl->getType().getNonReferenceType();
7011 break;
7012 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007013
Douglas Gregor882211c2010-04-28 22:16:22 +00007014 case OffsetOfExpr::OffsetOfNode::Identifier:
7015 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007016
Douglas Gregord1702062010-04-29 00:18:15 +00007017 case OffsetOfExpr::OffsetOfNode::Base: {
7018 CXXBaseSpecifier *BaseSpec = ON.getBase();
7019 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007020 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007021
7022 // Find the layout of the class whose base we are looking into.
7023 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007024 if (!RT)
7025 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007026 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007027 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007028 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7029
7030 // Find the base class itself.
7031 CurrentType = BaseSpec->getType();
7032 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7033 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007034 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007035
7036 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007037 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007038 break;
7039 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007040 }
7041 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007042 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007043}
7044
Chris Lattnere13042c2008-07-11 19:10:17 +00007045bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007046 switch (E->getOpcode()) {
7047 default:
7048 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7049 // See C99 6.6p3.
7050 return Error(E);
7051 case UO_Extension:
7052 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7053 // If so, we could clear the diagnostic ID.
7054 return Visit(E->getSubExpr());
7055 case UO_Plus:
7056 // The result is just the value.
7057 return Visit(E->getSubExpr());
7058 case UO_Minus: {
7059 if (!Visit(E->getSubExpr()))
7060 return false;
7061 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007062 const APSInt &Value = Result.getInt();
7063 if (Value.isSigned() && Value.isMinSignedValue())
7064 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7065 E->getType());
7066 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007067 }
7068 case UO_Not: {
7069 if (!Visit(E->getSubExpr()))
7070 return false;
7071 if (!Result.isInt()) return Error(E);
7072 return Success(~Result.getInt(), E);
7073 }
7074 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007075 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007076 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007077 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007078 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007079 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007080 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007081}
Mike Stump11289f42009-09-09 15:08:12 +00007082
Chris Lattner477c4be2008-07-12 01:15:53 +00007083/// HandleCast - This is used to evaluate implicit or explicit casts where the
7084/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007085bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7086 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007087 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007088 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007089
Eli Friedmanc757de22011-03-25 00:43:55 +00007090 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007091 case CK_BaseToDerived:
7092 case CK_DerivedToBase:
7093 case CK_UncheckedDerivedToBase:
7094 case CK_Dynamic:
7095 case CK_ToUnion:
7096 case CK_ArrayToPointerDecay:
7097 case CK_FunctionToPointerDecay:
7098 case CK_NullToPointer:
7099 case CK_NullToMemberPointer:
7100 case CK_BaseToDerivedMemberPointer:
7101 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007102 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007103 case CK_ConstructorConversion:
7104 case CK_IntegralToPointer:
7105 case CK_ToVoid:
7106 case CK_VectorSplat:
7107 case CK_IntegralToFloating:
7108 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007109 case CK_CPointerToObjCPointerCast:
7110 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007111 case CK_AnyPointerToBlockPointerCast:
7112 case CK_ObjCObjectLValueCast:
7113 case CK_FloatingRealToComplex:
7114 case CK_FloatingComplexToReal:
7115 case CK_FloatingComplexCast:
7116 case CK_FloatingComplexToIntegralComplex:
7117 case CK_IntegralRealToComplex:
7118 case CK_IntegralComplexCast:
7119 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007120 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007121 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007122 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007123 llvm_unreachable("invalid cast kind for integral value");
7124
Eli Friedman9faf2f92011-03-25 19:07:11 +00007125 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007126 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007127 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007128 case CK_ARCProduceObject:
7129 case CK_ARCConsumeObject:
7130 case CK_ARCReclaimReturnedObject:
7131 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007132 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007133 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007134
Richard Smith4ef685b2012-01-17 21:17:26 +00007135 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007136 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007137 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007138 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007139 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007140
7141 case CK_MemberPointerToBoolean:
7142 case CK_PointerToBoolean:
7143 case CK_IntegralToBoolean:
7144 case CK_FloatingToBoolean:
7145 case CK_FloatingComplexToBoolean:
7146 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007147 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007148 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007149 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007150 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007151 }
7152
Eli Friedmanc757de22011-03-25 00:43:55 +00007153 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007154 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007155 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007156
Eli Friedman742421e2009-02-20 01:15:07 +00007157 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007158 // Allow casts of address-of-label differences if they are no-ops
7159 // or narrowing. (The narrowing case isn't actually guaranteed to
7160 // be constant-evaluatable except in some narrow cases which are hard
7161 // to detect here. We let it through on the assumption the user knows
7162 // what they are doing.)
7163 if (Result.isAddrLabelDiff())
7164 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007165 // Only allow casts of lvalues if they are lossless.
7166 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7167 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007168
Richard Smith911e1422012-01-30 22:27:01 +00007169 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7170 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007171 }
Mike Stump11289f42009-09-09 15:08:12 +00007172
Eli Friedmanc757de22011-03-25 00:43:55 +00007173 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007174 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7175
John McCall45d55e42010-05-07 21:00:08 +00007176 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007177 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007178 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007179
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007180 if (LV.getLValueBase()) {
7181 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007182 // FIXME: Allow a larger integer size than the pointer size, and allow
7183 // narrowing back down to pointer width in subsequent integral casts.
7184 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007185 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007186 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007187
Richard Smithcf74da72011-11-16 07:18:12 +00007188 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007189 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007190 return true;
7191 }
7192
Ken Dyck02990832010-01-15 12:37:54 +00007193 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7194 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007195 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007196 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007197
Eli Friedmanc757de22011-03-25 00:43:55 +00007198 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007199 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007200 if (!EvaluateComplex(SubExpr, C, Info))
7201 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007202 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007203 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007204
Eli Friedmanc757de22011-03-25 00:43:55 +00007205 case CK_FloatingToIntegral: {
7206 APFloat F(0.0);
7207 if (!EvaluateFloat(SubExpr, F, Info))
7208 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007209
Richard Smith357362d2011-12-13 06:39:58 +00007210 APSInt Value;
7211 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7212 return false;
7213 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007214 }
7215 }
Mike Stump11289f42009-09-09 15:08:12 +00007216
Eli Friedmanc757de22011-03-25 00:43:55 +00007217 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007218}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007219
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007220bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7221 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007222 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007223 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7224 return false;
7225 if (!LV.isComplexInt())
7226 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007227 return Success(LV.getComplexIntReal(), E);
7228 }
7229
7230 return Visit(E->getSubExpr());
7231}
7232
Eli Friedman4e7a2412009-02-27 04:45:43 +00007233bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007234 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007235 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007236 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7237 return false;
7238 if (!LV.isComplexInt())
7239 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007240 return Success(LV.getComplexIntImag(), E);
7241 }
7242
Richard Smith4a678122011-10-24 18:44:57 +00007243 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007244 return Success(0, E);
7245}
7246
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007247bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7248 return Success(E->getPackLength(), E);
7249}
7250
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007251bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7252 return Success(E->getValue(), E);
7253}
7254
Chris Lattner05706e882008-07-11 18:11:29 +00007255//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007256// Float Evaluation
7257//===----------------------------------------------------------------------===//
7258
7259namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007260class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007261 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007262 APFloat &Result;
7263public:
7264 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007265 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007266
Richard Smith2e312c82012-03-03 22:46:17 +00007267 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007268 Result = V.getFloat();
7269 return true;
7270 }
Eli Friedman24c01542008-08-22 00:06:13 +00007271
Richard Smithfddd3842011-12-30 21:15:51 +00007272 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007273 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7274 return true;
7275 }
7276
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007277 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007278
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007279 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007280 bool VisitBinaryOperator(const BinaryOperator *E);
7281 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007282 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007283
John McCallb1fb0d32010-05-07 22:08:54 +00007284 bool VisitUnaryReal(const UnaryOperator *E);
7285 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007286
Richard Smithfddd3842011-12-30 21:15:51 +00007287 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007288};
7289} // end anonymous namespace
7290
7291static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007292 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007293 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007294}
7295
Jay Foad39c79802011-01-12 09:06:06 +00007296static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007297 QualType ResultTy,
7298 const Expr *Arg,
7299 bool SNaN,
7300 llvm::APFloat &Result) {
7301 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7302 if (!S) return false;
7303
7304 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7305
7306 llvm::APInt fill;
7307
7308 // Treat empty strings as if they were zero.
7309 if (S->getString().empty())
7310 fill = llvm::APInt(32, 0);
7311 else if (S->getString().getAsInteger(0, fill))
7312 return false;
7313
7314 if (SNaN)
7315 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7316 else
7317 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7318 return true;
7319}
7320
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007321bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007322 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007323 default:
7324 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7325
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007326 case Builtin::BI__builtin_huge_val:
7327 case Builtin::BI__builtin_huge_valf:
7328 case Builtin::BI__builtin_huge_vall:
7329 case Builtin::BI__builtin_inf:
7330 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007331 case Builtin::BI__builtin_infl: {
7332 const llvm::fltSemantics &Sem =
7333 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007334 Result = llvm::APFloat::getInf(Sem);
7335 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007336 }
Mike Stump11289f42009-09-09 15:08:12 +00007337
John McCall16291492010-02-28 13:00:19 +00007338 case Builtin::BI__builtin_nans:
7339 case Builtin::BI__builtin_nansf:
7340 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007341 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7342 true, Result))
7343 return Error(E);
7344 return true;
John McCall16291492010-02-28 13:00:19 +00007345
Chris Lattner0b7282e2008-10-06 06:31:58 +00007346 case Builtin::BI__builtin_nan:
7347 case Builtin::BI__builtin_nanf:
7348 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007349 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007350 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007351 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7352 false, Result))
7353 return Error(E);
7354 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007355
7356 case Builtin::BI__builtin_fabs:
7357 case Builtin::BI__builtin_fabsf:
7358 case Builtin::BI__builtin_fabsl:
7359 if (!EvaluateFloat(E->getArg(0), Result, Info))
7360 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007361
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007362 if (Result.isNegative())
7363 Result.changeSign();
7364 return true;
7365
Richard Smith8889a3d2013-06-13 06:26:32 +00007366 // FIXME: Builtin::BI__builtin_powi
7367 // FIXME: Builtin::BI__builtin_powif
7368 // FIXME: Builtin::BI__builtin_powil
7369
Mike Stump11289f42009-09-09 15:08:12 +00007370 case Builtin::BI__builtin_copysign:
7371 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007372 case Builtin::BI__builtin_copysignl: {
7373 APFloat RHS(0.);
7374 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7375 !EvaluateFloat(E->getArg(1), RHS, Info))
7376 return false;
7377 Result.copySign(RHS);
7378 return true;
7379 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007380 }
7381}
7382
John McCallb1fb0d32010-05-07 22:08:54 +00007383bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007384 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7385 ComplexValue CV;
7386 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7387 return false;
7388 Result = CV.FloatReal;
7389 return true;
7390 }
7391
7392 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007393}
7394
7395bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007396 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7397 ComplexValue CV;
7398 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7399 return false;
7400 Result = CV.FloatImag;
7401 return true;
7402 }
7403
Richard Smith4a678122011-10-24 18:44:57 +00007404 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007405 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7406 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007407 return true;
7408}
7409
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007410bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007411 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007412 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007413 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007414 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007415 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007416 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7417 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007418 Result.changeSign();
7419 return true;
7420 }
7421}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007422
Eli Friedman24c01542008-08-22 00:06:13 +00007423bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007424 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7425 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007426
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007427 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007428 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7429 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007430 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007431 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7432 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007433}
7434
7435bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7436 Result = E->getValue();
7437 return true;
7438}
7439
Peter Collingbournee9200682011-05-13 03:29:01 +00007440bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7441 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007442
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007443 switch (E->getCastKind()) {
7444 default:
Richard Smith11562c52011-10-28 17:51:58 +00007445 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007446
7447 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007448 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007449 return EvaluateInteger(SubExpr, IntResult, Info) &&
7450 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7451 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007452 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007453
7454 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007455 if (!Visit(SubExpr))
7456 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007457 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7458 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007459 }
John McCalld7646252010-11-14 08:17:51 +00007460
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007461 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007462 ComplexValue V;
7463 if (!EvaluateComplex(SubExpr, V, Info))
7464 return false;
7465 Result = V.getComplexFloatReal();
7466 return true;
7467 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007468 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007469}
7470
Eli Friedman24c01542008-08-22 00:06:13 +00007471//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007472// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007473//===----------------------------------------------------------------------===//
7474
7475namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007476class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007477 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007478 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007479
Anders Carlsson537969c2008-11-16 20:27:53 +00007480public:
John McCall93d91dc2010-05-07 17:22:02 +00007481 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007482 : ExprEvaluatorBaseTy(info), Result(Result) {}
7483
Richard Smith2e312c82012-03-03 22:46:17 +00007484 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007485 Result.setFrom(V);
7486 return true;
7487 }
Mike Stump11289f42009-09-09 15:08:12 +00007488
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007489 bool ZeroInitialization(const Expr *E);
7490
Anders Carlsson537969c2008-11-16 20:27:53 +00007491 //===--------------------------------------------------------------------===//
7492 // Visitor Methods
7493 //===--------------------------------------------------------------------===//
7494
Peter Collingbournee9200682011-05-13 03:29:01 +00007495 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007496 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007497 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007498 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007499 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007500};
7501} // end anonymous namespace
7502
John McCall93d91dc2010-05-07 17:22:02 +00007503static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7504 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007505 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007506 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007507}
7508
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007509bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007510 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007511 if (ElemTy->isRealFloatingType()) {
7512 Result.makeComplexFloat();
7513 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7514 Result.FloatReal = Zero;
7515 Result.FloatImag = Zero;
7516 } else {
7517 Result.makeComplexInt();
7518 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7519 Result.IntReal = Zero;
7520 Result.IntImag = Zero;
7521 }
7522 return true;
7523}
7524
Peter Collingbournee9200682011-05-13 03:29:01 +00007525bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7526 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007527
7528 if (SubExpr->getType()->isRealFloatingType()) {
7529 Result.makeComplexFloat();
7530 APFloat &Imag = Result.FloatImag;
7531 if (!EvaluateFloat(SubExpr, Imag, Info))
7532 return false;
7533
7534 Result.FloatReal = APFloat(Imag.getSemantics());
7535 return true;
7536 } else {
7537 assert(SubExpr->getType()->isIntegerType() &&
7538 "Unexpected imaginary literal.");
7539
7540 Result.makeComplexInt();
7541 APSInt &Imag = Result.IntImag;
7542 if (!EvaluateInteger(SubExpr, Imag, Info))
7543 return false;
7544
7545 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7546 return true;
7547 }
7548}
7549
Peter Collingbournee9200682011-05-13 03:29:01 +00007550bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007551
John McCallfcef3cf2010-12-14 17:51:41 +00007552 switch (E->getCastKind()) {
7553 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007554 case CK_BaseToDerived:
7555 case CK_DerivedToBase:
7556 case CK_UncheckedDerivedToBase:
7557 case CK_Dynamic:
7558 case CK_ToUnion:
7559 case CK_ArrayToPointerDecay:
7560 case CK_FunctionToPointerDecay:
7561 case CK_NullToPointer:
7562 case CK_NullToMemberPointer:
7563 case CK_BaseToDerivedMemberPointer:
7564 case CK_DerivedToBaseMemberPointer:
7565 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007566 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007567 case CK_ConstructorConversion:
7568 case CK_IntegralToPointer:
7569 case CK_PointerToIntegral:
7570 case CK_PointerToBoolean:
7571 case CK_ToVoid:
7572 case CK_VectorSplat:
7573 case CK_IntegralCast:
7574 case CK_IntegralToBoolean:
7575 case CK_IntegralToFloating:
7576 case CK_FloatingToIntegral:
7577 case CK_FloatingToBoolean:
7578 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007579 case CK_CPointerToObjCPointerCast:
7580 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007581 case CK_AnyPointerToBlockPointerCast:
7582 case CK_ObjCObjectLValueCast:
7583 case CK_FloatingComplexToReal:
7584 case CK_FloatingComplexToBoolean:
7585 case CK_IntegralComplexToReal:
7586 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007587 case CK_ARCProduceObject:
7588 case CK_ARCConsumeObject:
7589 case CK_ARCReclaimReturnedObject:
7590 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007591 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007592 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007593 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007594 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007595 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007596
John McCallfcef3cf2010-12-14 17:51:41 +00007597 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007598 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007599 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007600 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007601
7602 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007603 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007604 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007605 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007606
7607 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007608 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007609 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007610 return false;
7611
John McCallfcef3cf2010-12-14 17:51:41 +00007612 Result.makeComplexFloat();
7613 Result.FloatImag = APFloat(Real.getSemantics());
7614 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007615 }
7616
John McCallfcef3cf2010-12-14 17:51:41 +00007617 case CK_FloatingComplexCast: {
7618 if (!Visit(E->getSubExpr()))
7619 return false;
7620
7621 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7622 QualType From
7623 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7624
Richard Smith357362d2011-12-13 06:39:58 +00007625 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7626 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007627 }
7628
7629 case CK_FloatingComplexToIntegralComplex: {
7630 if (!Visit(E->getSubExpr()))
7631 return false;
7632
7633 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7634 QualType From
7635 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7636 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007637 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7638 To, Result.IntReal) &&
7639 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7640 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007641 }
7642
7643 case CK_IntegralRealToComplex: {
7644 APSInt &Real = Result.IntReal;
7645 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7646 return false;
7647
7648 Result.makeComplexInt();
7649 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7650 return true;
7651 }
7652
7653 case CK_IntegralComplexCast: {
7654 if (!Visit(E->getSubExpr()))
7655 return false;
7656
7657 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7658 QualType From
7659 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7660
Richard Smith911e1422012-01-30 22:27:01 +00007661 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7662 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007663 return true;
7664 }
7665
7666 case CK_IntegralComplexToFloatingComplex: {
7667 if (!Visit(E->getSubExpr()))
7668 return false;
7669
Ted Kremenek28831752012-08-23 20:46:57 +00007670 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007671 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007672 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007673 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007674 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7675 To, Result.FloatReal) &&
7676 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7677 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007678 }
7679 }
7680
7681 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007682}
7683
John McCall93d91dc2010-05-07 17:22:02 +00007684bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007685 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007686 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7687
Richard Smith253c2a32012-01-27 01:14:48 +00007688 bool LHSOK = Visit(E->getLHS());
7689 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007690 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007691
John McCall93d91dc2010-05-07 17:22:02 +00007692 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007693 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007694 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007695
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007696 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7697 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007698 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007699 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007700 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007701 if (Result.isComplexFloat()) {
7702 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7703 APFloat::rmNearestTiesToEven);
7704 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7705 APFloat::rmNearestTiesToEven);
7706 } else {
7707 Result.getComplexIntReal() += RHS.getComplexIntReal();
7708 Result.getComplexIntImag() += RHS.getComplexIntImag();
7709 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007710 break;
John McCalle3027922010-08-25 11:45:40 +00007711 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007712 if (Result.isComplexFloat()) {
7713 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7714 APFloat::rmNearestTiesToEven);
7715 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7716 APFloat::rmNearestTiesToEven);
7717 } else {
7718 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7719 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7720 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007721 break;
John McCalle3027922010-08-25 11:45:40 +00007722 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007723 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007724 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007725 APFloat &LHS_r = LHS.getComplexFloatReal();
7726 APFloat &LHS_i = LHS.getComplexFloatImag();
7727 APFloat &RHS_r = RHS.getComplexFloatReal();
7728 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007729
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007730 APFloat Tmp = LHS_r;
7731 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7732 Result.getComplexFloatReal() = Tmp;
7733 Tmp = LHS_i;
7734 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7735 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7736
7737 Tmp = LHS_r;
7738 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7739 Result.getComplexFloatImag() = Tmp;
7740 Tmp = LHS_i;
7741 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7742 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7743 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007744 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007745 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007746 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7747 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007748 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007749 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7750 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7751 }
7752 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007753 case BO_Div:
7754 if (Result.isComplexFloat()) {
7755 ComplexValue LHS = Result;
7756 APFloat &LHS_r = LHS.getComplexFloatReal();
7757 APFloat &LHS_i = LHS.getComplexFloatImag();
7758 APFloat &RHS_r = RHS.getComplexFloatReal();
7759 APFloat &RHS_i = RHS.getComplexFloatImag();
7760 APFloat &Res_r = Result.getComplexFloatReal();
7761 APFloat &Res_i = Result.getComplexFloatImag();
7762
7763 APFloat Den = RHS_r;
7764 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7765 APFloat Tmp = RHS_i;
7766 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7767 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7768
7769 Res_r = LHS_r;
7770 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7771 Tmp = LHS_i;
7772 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7773 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7774 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7775
7776 Res_i = LHS_i;
7777 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7778 Tmp = LHS_r;
7779 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7780 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7781 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7782 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007783 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7784 return Error(E, diag::note_expr_divide_by_zero);
7785
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007786 ComplexValue LHS = Result;
7787 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7788 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7789 Result.getComplexIntReal() =
7790 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7791 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7792 Result.getComplexIntImag() =
7793 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7794 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7795 }
7796 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007797 }
7798
John McCall93d91dc2010-05-07 17:22:02 +00007799 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007800}
7801
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007802bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7803 // Get the operand value into 'Result'.
7804 if (!Visit(E->getSubExpr()))
7805 return false;
7806
7807 switch (E->getOpcode()) {
7808 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007809 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007810 case UO_Extension:
7811 return true;
7812 case UO_Plus:
7813 // The result is always just the subexpr.
7814 return true;
7815 case UO_Minus:
7816 if (Result.isComplexFloat()) {
7817 Result.getComplexFloatReal().changeSign();
7818 Result.getComplexFloatImag().changeSign();
7819 }
7820 else {
7821 Result.getComplexIntReal() = -Result.getComplexIntReal();
7822 Result.getComplexIntImag() = -Result.getComplexIntImag();
7823 }
7824 return true;
7825 case UO_Not:
7826 if (Result.isComplexFloat())
7827 Result.getComplexFloatImag().changeSign();
7828 else
7829 Result.getComplexIntImag() = -Result.getComplexIntImag();
7830 return true;
7831 }
7832}
7833
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007834bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7835 if (E->getNumInits() == 2) {
7836 if (E->getType()->isComplexType()) {
7837 Result.makeComplexFloat();
7838 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7839 return false;
7840 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7841 return false;
7842 } else {
7843 Result.makeComplexInt();
7844 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7845 return false;
7846 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7847 return false;
7848 }
7849 return true;
7850 }
7851 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7852}
7853
Anders Carlsson537969c2008-11-16 20:27:53 +00007854//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007855// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7856// implicit conversion.
7857//===----------------------------------------------------------------------===//
7858
7859namespace {
7860class AtomicExprEvaluator :
7861 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7862 APValue &Result;
7863public:
7864 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7865 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7866
7867 bool Success(const APValue &V, const Expr *E) {
7868 Result = V;
7869 return true;
7870 }
7871
7872 bool ZeroInitialization(const Expr *E) {
7873 ImplicitValueInitExpr VIE(
7874 E->getType()->castAs<AtomicType>()->getValueType());
7875 return Evaluate(Result, Info, &VIE);
7876 }
7877
7878 bool VisitCastExpr(const CastExpr *E) {
7879 switch (E->getCastKind()) {
7880 default:
7881 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7882 case CK_NonAtomicToAtomic:
7883 return Evaluate(Result, Info, E->getSubExpr());
7884 }
7885 }
7886};
7887} // end anonymous namespace
7888
7889static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7890 assert(E->isRValue() && E->getType()->isAtomicType());
7891 return AtomicExprEvaluator(Info, Result).Visit(E);
7892}
7893
7894//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007895// Void expression evaluation, primarily for a cast to void on the LHS of a
7896// comma operator
7897//===----------------------------------------------------------------------===//
7898
7899namespace {
7900class VoidExprEvaluator
7901 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7902public:
7903 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7904
Richard Smith2e312c82012-03-03 22:46:17 +00007905 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007906
7907 bool VisitCastExpr(const CastExpr *E) {
7908 switch (E->getCastKind()) {
7909 default:
7910 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7911 case CK_ToVoid:
7912 VisitIgnoredValue(E->getSubExpr());
7913 return true;
7914 }
7915 }
7916};
7917} // end anonymous namespace
7918
7919static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7920 assert(E->isRValue() && E->getType()->isVoidType());
7921 return VoidExprEvaluator(Info).Visit(E);
7922}
7923
7924//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007925// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007926//===----------------------------------------------------------------------===//
7927
Richard Smith2e312c82012-03-03 22:46:17 +00007928static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007929 // In C, function designators are not lvalues, but we evaluate them as if they
7930 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007931 QualType T = E->getType();
7932 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007933 LValue LV;
7934 if (!EvaluateLValue(E, LV, Info))
7935 return false;
7936 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007937 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007938 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007939 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007940 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007941 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007942 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007943 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007944 LValue LV;
7945 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007946 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007947 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007948 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007949 llvm::APFloat F(0.0);
7950 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007951 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007952 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007953 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007954 ComplexValue C;
7955 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007956 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007957 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007958 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007959 MemberPtr P;
7960 if (!EvaluateMemberPointer(E, P, Info))
7961 return false;
7962 P.moveInto(Result);
7963 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007964 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007965 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007966 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007967 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7968 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007969 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007970 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007971 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007972 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007973 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007974 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7975 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007976 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007977 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007978 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007979 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007980 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007981 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007982 if (!EvaluateVoid(E, Info))
7983 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007984 } else if (T->isAtomicType()) {
7985 if (!EvaluateAtomic(E, Result, Info))
7986 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007987 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007988 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007989 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007990 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007991 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007992 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007993 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007994
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007995 return true;
7996}
7997
Richard Smithb228a862012-02-15 02:18:13 +00007998/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7999/// cases, the in-place evaluation is essential, since later initializers for
8000/// an object can indirectly refer to subobjects which were initialized earlier.
8001static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008002 const Expr *E, bool AllowNonLiteralTypes) {
8003 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008004 return false;
8005
8006 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008007 // Evaluate arrays and record types in-place, so that later initializers can
8008 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008009 if (E->getType()->isArrayType())
8010 return EvaluateArray(E, This, Result, Info);
8011 else if (E->getType()->isRecordType())
8012 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008013 }
8014
8015 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008016 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008017}
8018
Richard Smithf57d8cb2011-12-09 22:58:01 +00008019/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8020/// lvalue-to-rvalue cast if it is an lvalue.
8021static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00008022 if (!CheckLiteralType(Info, E))
8023 return false;
8024
Richard Smith2e312c82012-03-03 22:46:17 +00008025 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008026 return false;
8027
8028 if (E->isGLValue()) {
8029 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008030 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008031 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008032 return false;
8033 }
8034
Richard Smith2e312c82012-03-03 22:46:17 +00008035 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008036 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008037}
Richard Smith11562c52011-10-28 17:51:58 +00008038
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008039static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8040 const ASTContext &Ctx, bool &IsConst) {
8041 // Fast-path evaluations of integer literals, since we sometimes see files
8042 // containing vast quantities of these.
8043 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8044 Result.Val = APValue(APSInt(L->getValue(),
8045 L->getType()->isUnsignedIntegerType()));
8046 IsConst = true;
8047 return true;
8048 }
8049
8050 // FIXME: Evaluating values of large array and record types can cause
8051 // performance problems. Only do so in C++11 for now.
8052 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8053 Exp->getType()->isRecordType()) &&
8054 !Ctx.getLangOpts().CPlusPlus11) {
8055 IsConst = false;
8056 return true;
8057 }
8058 return false;
8059}
8060
8061
Richard Smith7b553f12011-10-29 00:50:52 +00008062/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008063/// any crazy technique (that has nothing to do with language standards) that
8064/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008065/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8066/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008067bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008068 bool IsConst;
8069 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8070 return IsConst;
8071
Richard Smith6d4c6582013-11-05 22:18:15 +00008072 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008073 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008074}
8075
Jay Foad39c79802011-01-12 09:06:06 +00008076bool Expr::EvaluateAsBooleanCondition(bool &Result,
8077 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008078 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008079 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008080 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008081}
8082
Richard Smith5fab0c92011-12-28 19:48:30 +00008083bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8084 SideEffectsKind AllowSideEffects) const {
8085 if (!getType()->isIntegralOrEnumerationType())
8086 return false;
8087
Richard Smith11562c52011-10-28 17:51:58 +00008088 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008089 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8090 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008091 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008092
Richard Smith11562c52011-10-28 17:51:58 +00008093 Result = ExprResult.Val.getInt();
8094 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008095}
8096
Jay Foad39c79802011-01-12 09:06:06 +00008097bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008098 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008099
John McCall45d55e42010-05-07 21:00:08 +00008100 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008101 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8102 !CheckLValueConstantExpression(Info, getExprLoc(),
8103 Ctx.getLValueReferenceType(getType()), LV))
8104 return false;
8105
Richard Smith2e312c82012-03-03 22:46:17 +00008106 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008107 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008108}
8109
Richard Smithd0b4dd62011-12-19 06:19:21 +00008110bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8111 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008112 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008113 // FIXME: Evaluating initializers for large array and record types can cause
8114 // performance problems. Only do so in C++11 for now.
8115 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008116 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008117 return false;
8118
Richard Smithd0b4dd62011-12-19 06:19:21 +00008119 Expr::EvalStatus EStatus;
8120 EStatus.Diag = &Notes;
8121
Richard Smith6d4c6582013-11-05 22:18:15 +00008122 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008123 InitInfo.setEvaluatingDecl(VD, Value);
8124
8125 LValue LVal;
8126 LVal.set(VD);
8127
Richard Smithfddd3842011-12-30 21:15:51 +00008128 // C++11 [basic.start.init]p2:
8129 // Variables with static storage duration or thread storage duration shall be
8130 // zero-initialized before any other initialization takes place.
8131 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008132 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008133 !VD->getType()->isReferenceType()) {
8134 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008135 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008136 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008137 return false;
8138 }
8139
Richard Smith7525ff62013-05-09 07:14:00 +00008140 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8141 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008142 EStatus.HasSideEffects)
8143 return false;
8144
8145 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8146 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008147}
8148
Richard Smith7b553f12011-10-29 00:50:52 +00008149/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8150/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008151bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008152 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008153 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008154}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008155
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008156APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008157 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008158 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008159 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008160 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008161 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008162 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008163 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008164
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008165 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008166}
John McCall864e3962010-05-07 05:32:02 +00008167
Richard Smithe9ff7702013-11-05 22:23:30 +00008168void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008169 bool IsConst;
8170 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008171 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008172 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008173 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8174 }
8175}
8176
Richard Smithe6c01442013-06-05 00:46:14 +00008177bool Expr::EvalResult::isGlobalLValue() const {
8178 assert(Val.isLValue());
8179 return IsGlobalLValue(Val.getLValueBase());
8180}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008181
8182
John McCall864e3962010-05-07 05:32:02 +00008183/// isIntegerConstantExpr - this recursive routine will test if an expression is
8184/// an integer constant expression.
8185
8186/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8187/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008188
8189// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008190// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8191// and a (possibly null) SourceLocation indicating the location of the problem.
8192//
John McCall864e3962010-05-07 05:32:02 +00008193// Note that to reduce code duplication, this helper does no evaluation
8194// itself; the caller checks whether the expression is evaluatable, and
8195// in the rare cases where CheckICE actually cares about the evaluated
8196// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008197
Dan Gohman28ade552010-07-26 21:25:24 +00008198namespace {
8199
Richard Smith9e575da2012-12-28 13:25:52 +00008200enum ICEKind {
8201 /// This expression is an ICE.
8202 IK_ICE,
8203 /// This expression is not an ICE, but if it isn't evaluated, it's
8204 /// a legal subexpression for an ICE. This return value is used to handle
8205 /// the comma operator in C99 mode, and non-constant subexpressions.
8206 IK_ICEIfUnevaluated,
8207 /// This expression is not an ICE, and is not a legal subexpression for one.
8208 IK_NotICE
8209};
8210
John McCall864e3962010-05-07 05:32:02 +00008211struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008212 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008213 SourceLocation Loc;
8214
Richard Smith9e575da2012-12-28 13:25:52 +00008215 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008216};
8217
Dan Gohman28ade552010-07-26 21:25:24 +00008218}
8219
Richard Smith9e575da2012-12-28 13:25:52 +00008220static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8221
8222static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008223
Craig Toppera31a8822013-08-22 07:09:37 +00008224static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008225 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008226 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008227 !EVResult.Val.isInt())
8228 return ICEDiag(IK_NotICE, E->getLocStart());
8229
John McCall864e3962010-05-07 05:32:02 +00008230 return NoDiag();
8231}
8232
Craig Toppera31a8822013-08-22 07:09:37 +00008233static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008234 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008235 if (!E->getType()->isIntegralOrEnumerationType())
8236 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008237
8238 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008239#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008240#define STMT(Node, Base) case Expr::Node##Class:
8241#define EXPR(Node, Base)
8242#include "clang/AST/StmtNodes.inc"
8243 case Expr::PredefinedExprClass:
8244 case Expr::FloatingLiteralClass:
8245 case Expr::ImaginaryLiteralClass:
8246 case Expr::StringLiteralClass:
8247 case Expr::ArraySubscriptExprClass:
8248 case Expr::MemberExprClass:
8249 case Expr::CompoundAssignOperatorClass:
8250 case Expr::CompoundLiteralExprClass:
8251 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008252 case Expr::DesignatedInitExprClass:
8253 case Expr::ImplicitValueInitExprClass:
8254 case Expr::ParenListExprClass:
8255 case Expr::VAArgExprClass:
8256 case Expr::AddrLabelExprClass:
8257 case Expr::StmtExprClass:
8258 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008259 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008260 case Expr::CXXDynamicCastExprClass:
8261 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008262 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008263 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008264 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008265 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008266 case Expr::CXXThisExprClass:
8267 case Expr::CXXThrowExprClass:
8268 case Expr::CXXNewExprClass:
8269 case Expr::CXXDeleteExprClass:
8270 case Expr::CXXPseudoDestructorExprClass:
8271 case Expr::UnresolvedLookupExprClass:
8272 case Expr::DependentScopeDeclRefExprClass:
8273 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008274 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008275 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008276 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008277 case Expr::CXXTemporaryObjectExprClass:
8278 case Expr::CXXUnresolvedConstructExprClass:
8279 case Expr::CXXDependentScopeMemberExprClass:
8280 case Expr::UnresolvedMemberExprClass:
8281 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008282 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008283 case Expr::ObjCArrayLiteralClass:
8284 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008285 case Expr::ObjCEncodeExprClass:
8286 case Expr::ObjCMessageExprClass:
8287 case Expr::ObjCSelectorExprClass:
8288 case Expr::ObjCProtocolExprClass:
8289 case Expr::ObjCIvarRefExprClass:
8290 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008291 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008292 case Expr::ObjCIsaExprClass:
8293 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008294 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008295 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008296 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008297 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008298 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008299 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008300 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008301 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008302 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008303 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008304 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008305 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00008306 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008307 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008308 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008309
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008310 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008311 case Expr::GNUNullExprClass:
8312 // GCC considers the GNU __null value to be an integral constant expression.
8313 return NoDiag();
8314
John McCall7c454bb2011-07-15 05:09:51 +00008315 case Expr::SubstNonTypeTemplateParmExprClass:
8316 return
8317 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8318
John McCall864e3962010-05-07 05:32:02 +00008319 case Expr::ParenExprClass:
8320 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008321 case Expr::GenericSelectionExprClass:
8322 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008323 case Expr::IntegerLiteralClass:
8324 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008325 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008326 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008327 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008328 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008329 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008330 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008331 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008332 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008333 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008334 return NoDiag();
8335 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008336 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008337 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8338 // constant expressions, but they can never be ICEs because an ICE cannot
8339 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008340 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008341 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008342 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008343 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008344 }
Richard Smith6365c912012-02-24 22:12:32 +00008345 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008346 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8347 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008348 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008349 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008350 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008351 // Parameter variables are never constants. Without this check,
8352 // getAnyInitializer() can find a default argument, which leads
8353 // to chaos.
8354 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008355 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008356
8357 // C++ 7.1.5.1p2
8358 // A variable of non-volatile const-qualified integral or enumeration
8359 // type initialized by an ICE can be used in ICEs.
8360 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008361 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008362 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008363
Richard Smithd0b4dd62011-12-19 06:19:21 +00008364 const VarDecl *VD;
8365 // Look for a declaration of this variable that has an initializer, and
8366 // check whether it is an ICE.
8367 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8368 return NoDiag();
8369 else
Richard Smith9e575da2012-12-28 13:25:52 +00008370 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008371 }
8372 }
Richard Smith9e575da2012-12-28 13:25:52 +00008373 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008374 }
John McCall864e3962010-05-07 05:32:02 +00008375 case Expr::UnaryOperatorClass: {
8376 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8377 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008378 case UO_PostInc:
8379 case UO_PostDec:
8380 case UO_PreInc:
8381 case UO_PreDec:
8382 case UO_AddrOf:
8383 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008384 // C99 6.6/3 allows increment and decrement within unevaluated
8385 // subexpressions of constant expressions, but they can never be ICEs
8386 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008387 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008388 case UO_Extension:
8389 case UO_LNot:
8390 case UO_Plus:
8391 case UO_Minus:
8392 case UO_Not:
8393 case UO_Real:
8394 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008395 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008396 }
Richard Smith9e575da2012-12-28 13:25:52 +00008397
John McCall864e3962010-05-07 05:32:02 +00008398 // OffsetOf falls through here.
8399 }
8400 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008401 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8402 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8403 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8404 // compliance: we should warn earlier for offsetof expressions with
8405 // array subscripts that aren't ICEs, and if the array subscripts
8406 // are ICEs, the value of the offsetof must be an integer constant.
8407 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008408 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008409 case Expr::UnaryExprOrTypeTraitExprClass: {
8410 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8411 if ((Exp->getKind() == UETT_SizeOf) &&
8412 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008413 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008414 return NoDiag();
8415 }
8416 case Expr::BinaryOperatorClass: {
8417 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8418 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008419 case BO_PtrMemD:
8420 case BO_PtrMemI:
8421 case BO_Assign:
8422 case BO_MulAssign:
8423 case BO_DivAssign:
8424 case BO_RemAssign:
8425 case BO_AddAssign:
8426 case BO_SubAssign:
8427 case BO_ShlAssign:
8428 case BO_ShrAssign:
8429 case BO_AndAssign:
8430 case BO_XorAssign:
8431 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008432 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8433 // constant expressions, but they can never be ICEs because an ICE cannot
8434 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008435 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008436
John McCalle3027922010-08-25 11:45:40 +00008437 case BO_Mul:
8438 case BO_Div:
8439 case BO_Rem:
8440 case BO_Add:
8441 case BO_Sub:
8442 case BO_Shl:
8443 case BO_Shr:
8444 case BO_LT:
8445 case BO_GT:
8446 case BO_LE:
8447 case BO_GE:
8448 case BO_EQ:
8449 case BO_NE:
8450 case BO_And:
8451 case BO_Xor:
8452 case BO_Or:
8453 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008454 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8455 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008456 if (Exp->getOpcode() == BO_Div ||
8457 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008458 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008459 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008460 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008461 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008462 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008463 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008464 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008465 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008466 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008467 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008468 }
8469 }
8470 }
John McCalle3027922010-08-25 11:45:40 +00008471 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008472 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008473 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8474 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008475 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8476 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008477 } else {
8478 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008479 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008480 }
8481 }
Richard Smith9e575da2012-12-28 13:25:52 +00008482 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008483 }
John McCalle3027922010-08-25 11:45:40 +00008484 case BO_LAnd:
8485 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008486 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8487 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008488 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008489 // Rare case where the RHS has a comma "side-effect"; we need
8490 // to actually check the condition to see whether the side
8491 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008492 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008493 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008494 return RHSResult;
8495 return NoDiag();
8496 }
8497
Richard Smith9e575da2012-12-28 13:25:52 +00008498 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008499 }
8500 }
8501 }
8502 case Expr::ImplicitCastExprClass:
8503 case Expr::CStyleCastExprClass:
8504 case Expr::CXXFunctionalCastExprClass:
8505 case Expr::CXXStaticCastExprClass:
8506 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008507 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008508 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008509 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008510 if (isa<ExplicitCastExpr>(E)) {
8511 if (const FloatingLiteral *FL
8512 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8513 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8514 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8515 APSInt IgnoredVal(DestWidth, !DestSigned);
8516 bool Ignored;
8517 // If the value does not fit in the destination type, the behavior is
8518 // undefined, so we are not required to treat it as a constant
8519 // expression.
8520 if (FL->getValue().convertToInteger(IgnoredVal,
8521 llvm::APFloat::rmTowardZero,
8522 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008523 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008524 return NoDiag();
8525 }
8526 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008527 switch (cast<CastExpr>(E)->getCastKind()) {
8528 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008529 case CK_AtomicToNonAtomic:
8530 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008531 case CK_NoOp:
8532 case CK_IntegralToBoolean:
8533 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008534 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008535 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008536 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008537 }
John McCall864e3962010-05-07 05:32:02 +00008538 }
John McCallc07a0c72011-02-17 10:25:35 +00008539 case Expr::BinaryConditionalOperatorClass: {
8540 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8541 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008542 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008543 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008544 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8545 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8546 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008547 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008548 return FalseResult;
8549 }
John McCall864e3962010-05-07 05:32:02 +00008550 case Expr::ConditionalOperatorClass: {
8551 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8552 // If the condition (ignoring parens) is a __builtin_constant_p call,
8553 // then only the true side is actually considered in an integer constant
8554 // expression, and it is fully evaluated. This is an important GNU
8555 // extension. See GCC PR38377 for discussion.
8556 if (const CallExpr *CallCE
8557 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008558 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8559 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008560 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008561 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008562 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008563
Richard Smithf57d8cb2011-12-09 22:58:01 +00008564 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8565 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008566
Richard Smith9e575da2012-12-28 13:25:52 +00008567 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008568 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008569 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008570 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008571 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008572 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008573 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008574 return NoDiag();
8575 // Rare case where the diagnostics depend on which side is evaluated
8576 // Note that if we get here, CondResult is 0, and at least one of
8577 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008578 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008579 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008580 return TrueResult;
8581 }
8582 case Expr::CXXDefaultArgExprClass:
8583 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008584 case Expr::CXXDefaultInitExprClass:
8585 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008586 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008587 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008588 }
8589 }
8590
David Blaikiee4d798f2012-01-20 21:50:17 +00008591 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008592}
8593
Richard Smithf57d8cb2011-12-09 22:58:01 +00008594/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008595static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008596 const Expr *E,
8597 llvm::APSInt *Value,
8598 SourceLocation *Loc) {
8599 if (!E->getType()->isIntegralOrEnumerationType()) {
8600 if (Loc) *Loc = E->getExprLoc();
8601 return false;
8602 }
8603
Richard Smith66e05fe2012-01-18 05:21:49 +00008604 APValue Result;
8605 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008606 return false;
8607
Richard Smith66e05fe2012-01-18 05:21:49 +00008608 assert(Result.isInt() && "pointer cast to int is not an ICE");
8609 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008610 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008611}
8612
Craig Toppera31a8822013-08-22 07:09:37 +00008613bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8614 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008615 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008616 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8617
Richard Smith9e575da2012-12-28 13:25:52 +00008618 ICEDiag D = CheckICE(this, Ctx);
8619 if (D.Kind != IK_ICE) {
8620 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008621 return false;
8622 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008623 return true;
8624}
8625
Craig Toppera31a8822013-08-22 07:09:37 +00008626bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008627 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008628 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008629 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8630
8631 if (!isIntegerConstantExpr(Ctx, Loc))
8632 return false;
8633 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008634 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008635 return true;
8636}
Richard Smith66e05fe2012-01-18 05:21:49 +00008637
Craig Toppera31a8822013-08-22 07:09:37 +00008638bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008639 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008640}
8641
Craig Toppera31a8822013-08-22 07:09:37 +00008642bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008643 SourceLocation *Loc) const {
8644 // We support this checking in C++98 mode in order to diagnose compatibility
8645 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008646 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008647
Richard Smith98a0a492012-02-14 21:38:30 +00008648 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008649 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008650 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008651 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008652 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008653
8654 APValue Scratch;
8655 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8656
8657 if (!Diags.empty()) {
8658 IsConstExpr = false;
8659 if (Loc) *Loc = Diags[0].first;
8660 } else if (!IsConstExpr) {
8661 // FIXME: This shouldn't happen.
8662 if (Loc) *Loc = getExprLoc();
8663 }
8664
8665 return IsConstExpr;
8666}
Richard Smith253c2a32012-01-27 01:14:48 +00008667
8668bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008669 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008670 PartialDiagnosticAt> &Diags) {
8671 // FIXME: It would be useful to check constexpr function templates, but at the
8672 // moment the constant expression evaluator cannot cope with the non-rigorous
8673 // ASTs which we build for dependent expressions.
8674 if (FD->isDependentContext())
8675 return true;
8676
8677 Expr::EvalStatus Status;
8678 Status.Diag = &Diags;
8679
Richard Smith6d4c6582013-11-05 22:18:15 +00008680 EvalInfo Info(FD->getASTContext(), Status,
8681 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008682
8683 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8684 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8685
Richard Smith7525ff62013-05-09 07:14:00 +00008686 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008687 // is a temporary being used as the 'this' pointer.
8688 LValue This;
8689 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008690 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008691
Richard Smith253c2a32012-01-27 01:14:48 +00008692 ArrayRef<const Expr*> Args;
8693
8694 SourceLocation Loc = FD->getLocation();
8695
Richard Smith2e312c82012-03-03 22:46:17 +00008696 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008697 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8698 // Evaluate the call as a constant initializer, to allow the construction
8699 // of objects of non-literal types.
8700 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008701 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008702 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008703 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8704 Args, FD->getBody(), Info, Scratch);
8705
8706 return Diags.empty();
8707}