blob: 2412facf05c6dad627164dfb5d172e3906839654 [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 Smithd9f663b2013-04-22 15:31:51 +00003626 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3627 return false;
3628 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003629 }
3630
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003631 // For a trivial copy or move constructor, perform an APValue copy. This is
3632 // essential for unions, where the operations performed by the constructor
3633 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003634 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003635 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3636 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003637 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003638 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003639 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003640 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003641 }
3642
3643 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003644 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003645 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3646 std::distance(RD->field_begin(), RD->field_end()));
3647
John McCalld7bca762012-05-01 00:38:49 +00003648 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003649 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3650
Richard Smith08d6a2c2013-07-24 07:11:57 +00003651 // A scope for temporaries lifetime-extended by reference members.
3652 BlockScopeRAII LifetimeExtendedScope(Info);
3653
Richard Smith253c2a32012-01-27 01:14:48 +00003654 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003655 unsigned BasesSeen = 0;
3656#ifndef NDEBUG
3657 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3658#endif
3659 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3660 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003661 LValue Subobject = This;
3662 APValue *Value = &Result;
3663
3664 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003665 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003666 if ((*I)->isBaseInitializer()) {
3667 QualType BaseType((*I)->getBaseClass(), 0);
3668#ifndef NDEBUG
3669 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003670 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003671 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3672 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3673 "base class initializers not in expected order");
3674 ++BaseIt;
3675#endif
John McCalld7bca762012-05-01 00:38:49 +00003676 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3677 BaseType->getAsCXXRecordDecl(), &Layout))
3678 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003679 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003680 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003681 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3682 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003683 if (RD->isUnion()) {
3684 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003685 Value = &Result.getUnionValue();
3686 } else {
3687 Value = &Result.getStructField(FD->getFieldIndex());
3688 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003689 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003690 // Walk the indirect field decl's chain to find the object to initialize,
3691 // and make sure we've initialized every step along it.
3692 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3693 CE = IFD->chain_end();
3694 C != CE; ++C) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003695 FD = cast<FieldDecl>(*C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003696 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3697 // Switch the union field if it differs. This happens if we had
3698 // preceding zero-initialization, and we're now initializing a union
3699 // subobject other than the first.
3700 // FIXME: In this case, the values of the other subobjects are
3701 // specified, since zero-initialization sets all padding bits to zero.
3702 if (Value->isUninit() ||
3703 (Value->isUnion() && Value->getUnionField() != FD)) {
3704 if (CD->isUnion())
3705 *Value = APValue(FD);
3706 else
3707 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3708 std::distance(CD->field_begin(), CD->field_end()));
3709 }
John McCalld7bca762012-05-01 00:38:49 +00003710 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3711 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003712 if (CD->isUnion())
3713 Value = &Value->getUnionValue();
3714 else
3715 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003716 }
Richard Smithd62306a2011-11-10 06:34:14 +00003717 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003718 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003719 }
Richard Smith253c2a32012-01-27 01:14:48 +00003720
Richard Smith08d6a2c2013-07-24 07:11:57 +00003721 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003722 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3723 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3724 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003725 // If we're checking for a potential constant expression, evaluate all
3726 // initializers even if some of them fail.
3727 if (!Info.keepEvaluatingAfterFailure())
3728 return false;
3729 Success = false;
3730 }
Richard Smithd62306a2011-11-10 06:34:14 +00003731 }
3732
Richard Smithd9f663b2013-04-22 15:31:51 +00003733 return Success &&
3734 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003735}
3736
Eli Friedman9a156e52008-11-12 09:44:48 +00003737//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003738// Generic Evaluation
3739//===----------------------------------------------------------------------===//
3740namespace {
3741
Richard Smithf57d8cb2011-12-09 22:58:01 +00003742// FIXME: RetTy is always bool. Remove it.
3743template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003744class ExprEvaluatorBase
3745 : public ConstStmtVisitor<Derived, RetTy> {
3746private:
Richard Smith2e312c82012-03-03 22:46:17 +00003747 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003748 return static_cast<Derived*>(this)->Success(V, E);
3749 }
Richard Smithfddd3842011-12-30 21:15:51 +00003750 RetTy DerivedZeroInitialization(const Expr *E) {
3751 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003752 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003753
Richard Smith17100ba2012-02-16 02:46:34 +00003754 // Check whether a conditional operator with a non-constant condition is a
3755 // potential constant expression. If neither arm is a potential constant
3756 // expression, then the conditional operator is not either.
3757 template<typename ConditionalOperator>
3758 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003759 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003760
3761 // Speculatively evaluate both arms.
3762 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003763 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003764 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3765
3766 StmtVisitorTy::Visit(E->getFalseExpr());
3767 if (Diag.empty())
3768 return;
3769
3770 Diag.clear();
3771 StmtVisitorTy::Visit(E->getTrueExpr());
3772 if (Diag.empty())
3773 return;
3774 }
3775
3776 Error(E, diag::note_constexpr_conditional_never_const);
3777 }
3778
3779
3780 template<typename ConditionalOperator>
3781 bool HandleConditionalOperator(const ConditionalOperator *E) {
3782 bool BoolResult;
3783 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003784 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003785 CheckPotentialConstantConditional(E);
3786 return false;
3787 }
3788
3789 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3790 return StmtVisitorTy::Visit(EvalExpr);
3791 }
3792
Peter Collingbournee9200682011-05-13 03:29:01 +00003793protected:
3794 EvalInfo &Info;
3795 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3796 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3797
Richard Smith92b1ce02011-12-12 09:28:41 +00003798 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003799 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003800 }
3801
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003802 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3803
3804public:
3805 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3806
3807 EvalInfo &getEvalInfo() { return Info; }
3808
Richard Smithf57d8cb2011-12-09 22:58:01 +00003809 /// Report an evaluation error. This should only be called when an error is
3810 /// first discovered. When propagating an error, just return false.
3811 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003812 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003813 return false;
3814 }
3815 bool Error(const Expr *E) {
3816 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3817 }
3818
Peter Collingbournee9200682011-05-13 03:29:01 +00003819 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003820 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003821 }
3822 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003823 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003824 }
3825
3826 RetTy VisitParenExpr(const ParenExpr *E)
3827 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3828 RetTy VisitUnaryExtension(const UnaryOperator *E)
3829 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3830 RetTy VisitUnaryPlus(const UnaryOperator *E)
3831 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3832 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003833 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003834 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3835 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003836 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3837 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003838 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3839 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith17e32462013-09-13 20:51:45 +00003840 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3841 // The initializer may not have been parsed yet, or might be erroneous.
3842 if (!E->getExpr())
3843 return Error(E);
3844 return StmtVisitorTy::Visit(E->getExpr());
3845 }
Richard Smith5894a912011-12-19 22:12:41 +00003846 // We cannot create any objects for which cleanups are required, so there is
3847 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3848 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3849 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003850
Richard Smith6d6ecc32011-12-12 12:46:16 +00003851 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3852 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3853 return static_cast<Derived*>(this)->VisitCastExpr(E);
3854 }
3855 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3856 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3857 return static_cast<Derived*>(this)->VisitCastExpr(E);
3858 }
3859
Richard Smith027bf112011-11-17 22:56:20 +00003860 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3861 switch (E->getOpcode()) {
3862 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003863 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003864
3865 case BO_Comma:
3866 VisitIgnoredValue(E->getLHS());
3867 return StmtVisitorTy::Visit(E->getRHS());
3868
3869 case BO_PtrMemD:
3870 case BO_PtrMemI: {
3871 LValue Obj;
3872 if (!HandleMemberPointerAccess(Info, E, Obj))
3873 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003874 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003875 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003876 return false;
3877 return DerivedSuccess(Result, E);
3878 }
3879 }
3880 }
3881
Peter Collingbournee9200682011-05-13 03:29:01 +00003882 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003883 // Evaluate and cache the common expression. We treat it as a temporary,
3884 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003885 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003886 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003887 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003888
Richard Smith17100ba2012-02-16 02:46:34 +00003889 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003890 }
3891
3892 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003893 bool IsBcpCall = false;
3894 // If the condition (ignoring parens) is a __builtin_constant_p call,
3895 // the result is a constant expression if it can be folded without
3896 // side-effects. This is an important GNU extension. See GCC PR38377
3897 // for discussion.
3898 if (const CallExpr *CallCE =
3899 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3900 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3901 IsBcpCall = true;
3902
3903 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3904 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003905 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003906 return false;
3907
Richard Smith6d4c6582013-11-05 22:18:15 +00003908 FoldConstant Fold(Info, IsBcpCall);
3909 if (!HandleConditionalOperator(E)) {
3910 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003911 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003912 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003913
3914 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003915 }
3916
3917 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003918 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3919 return DerivedSuccess(*Value, E);
3920
3921 const Expr *Source = E->getSourceExpr();
3922 if (!Source)
3923 return Error(E);
3924 if (Source == E) { // sanity checking.
3925 assert(0 && "OpaqueValueExpr recursively refers to itself");
3926 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003927 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003928 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003929 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003930
Richard Smith254a73d2011-10-28 22:34:42 +00003931 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003932 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003933 QualType CalleeType = Callee->getType();
3934
Richard Smith254a73d2011-10-28 22:34:42 +00003935 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003936 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003937 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003938 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003939
Richard Smithe97cbd72011-11-11 04:05:33 +00003940 // Extract function decl and 'this' pointer from the callee.
3941 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003942 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003943 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3944 // Explicit bound member calls, such as x.f() or p->g();
3945 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003946 return false;
3947 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003948 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003949 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003950 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3951 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003952 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3953 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003954 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003955 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003956 return Error(Callee);
3957
3958 FD = dyn_cast<FunctionDecl>(Member);
3959 if (!FD)
3960 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003961 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003962 LValue Call;
3963 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003964 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003965
Richard Smitha8105bc2012-01-06 16:39:00 +00003966 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003967 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003968 FD = dyn_cast_or_null<FunctionDecl>(
3969 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003970 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003971 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003972
3973 // Overloaded operator calls to member functions are represented as normal
3974 // calls with '*this' as the first argument.
3975 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3976 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003977 // FIXME: When selecting an implicit conversion for an overloaded
3978 // operator delete, we sometimes try to evaluate calls to conversion
3979 // operators without a 'this' parameter!
3980 if (Args.empty())
3981 return Error(E);
3982
Richard Smithe97cbd72011-11-11 04:05:33 +00003983 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3984 return false;
3985 This = &ThisVal;
3986 Args = Args.slice(1);
3987 }
3988
3989 // Don't call function pointers which have been cast to some other type.
3990 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003991 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003992 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003993 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003994
Richard Smith47b34932012-02-01 02:39:43 +00003995 if (This && !This->checkSubobject(Info, E, CSK_This))
3996 return false;
3997
Richard Smith3607ffe2012-02-13 03:54:03 +00003998 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3999 // calls to such functions in constant expressions.
4000 if (This && !HasQualifier &&
4001 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4002 return Error(E, diag::note_constexpr_virtual_call);
4003
Richard Smith357362d2011-12-13 06:39:58 +00004004 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004005 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004006 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004007
Richard Smith357362d2011-12-13 06:39:58 +00004008 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004009 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4010 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004011 return false;
4012
Richard Smithb228a862012-02-15 02:18:13 +00004013 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004014 }
4015
Richard Smith11562c52011-10-28 17:51:58 +00004016 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4017 return StmtVisitorTy::Visit(E->getInitializer());
4018 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004019 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004020 if (E->getNumInits() == 0)
4021 return DerivedZeroInitialization(E);
4022 if (E->getNumInits() == 1)
4023 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004024 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004025 }
4026 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004027 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004028 }
4029 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004030 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004031 }
Richard Smith027bf112011-11-17 22:56:20 +00004032 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004033 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004034 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004035
Richard Smithd62306a2011-11-10 06:34:14 +00004036 /// A member expression where the object is a prvalue is itself a prvalue.
4037 RetTy VisitMemberExpr(const MemberExpr *E) {
4038 assert(!E->isArrow() && "missing call to bound member function?");
4039
Richard Smith2e312c82012-03-03 22:46:17 +00004040 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004041 if (!Evaluate(Val, Info, E->getBase()))
4042 return false;
4043
4044 QualType BaseTy = E->getBase()->getType();
4045
4046 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004047 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004048 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004049 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004050 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4051
Richard Smith3229b742013-05-05 21:17:10 +00004052 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004053 SubobjectDesignator Designator(BaseTy);
4054 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004055
Richard Smith3229b742013-05-05 21:17:10 +00004056 APValue Result;
4057 return extractSubobject(Info, E, Obj, Designator, Result) &&
4058 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004059 }
4060
Richard Smith11562c52011-10-28 17:51:58 +00004061 RetTy VisitCastExpr(const CastExpr *E) {
4062 switch (E->getCastKind()) {
4063 default:
4064 break;
4065
Richard Smitha23ab512013-05-23 00:30:41 +00004066 case CK_AtomicToNonAtomic: {
4067 APValue AtomicVal;
4068 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4069 return false;
4070 return DerivedSuccess(AtomicVal, E);
4071 }
4072
Richard Smith11562c52011-10-28 17:51:58 +00004073 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004074 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004075 return StmtVisitorTy::Visit(E->getSubExpr());
4076
4077 case CK_LValueToRValue: {
4078 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004079 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4080 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004081 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004082 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004083 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004084 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004085 return false;
4086 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004087 }
4088 }
4089
Richard Smithf57d8cb2011-12-09 22:58:01 +00004090 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004091 }
4092
Richard Smith243ef902013-05-05 23:31:59 +00004093 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4094 return VisitUnaryPostIncDec(UO);
4095 }
4096 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4097 return VisitUnaryPostIncDec(UO);
4098 }
4099 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4100 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4101 return Error(UO);
4102
4103 LValue LVal;
4104 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4105 return false;
4106 APValue RVal;
4107 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4108 UO->isIncrementOp(), &RVal))
4109 return false;
4110 return DerivedSuccess(RVal, UO);
4111 }
4112
Richard Smith51f03172013-06-20 03:00:05 +00004113 RetTy VisitStmtExpr(const StmtExpr *E) {
4114 // We will have checked the full-expressions inside the statement expression
4115 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004116 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004117 return Error(E);
4118
Richard Smith08d6a2c2013-07-24 07:11:57 +00004119 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004120 const CompoundStmt *CS = E->getSubStmt();
4121 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4122 BE = CS->body_end();
4123 /**/; ++BI) {
4124 if (BI + 1 == BE) {
4125 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4126 if (!FinalExpr) {
4127 Info.Diag((*BI)->getLocStart(),
4128 diag::note_constexpr_stmt_expr_unsupported);
4129 return false;
4130 }
4131 return this->Visit(FinalExpr);
4132 }
4133
4134 APValue ReturnValue;
4135 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4136 if (ESR != ESR_Succeeded) {
4137 // FIXME: If the statement-expression terminated due to 'return',
4138 // 'break', or 'continue', it would be nice to propagate that to
4139 // the outer statement evaluation rather than bailing out.
4140 if (ESR != ESR_Failed)
4141 Info.Diag((*BI)->getLocStart(),
4142 diag::note_constexpr_stmt_expr_unsupported);
4143 return false;
4144 }
4145 }
4146 }
4147
Richard Smith4a678122011-10-24 18:44:57 +00004148 /// Visit a value which is evaluated, but whose value is ignored.
4149 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004150 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004151 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004152};
4153
4154}
4155
4156//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004157// Common base class for lvalue and temporary evaluation.
4158//===----------------------------------------------------------------------===//
4159namespace {
4160template<class Derived>
4161class LValueExprEvaluatorBase
4162 : public ExprEvaluatorBase<Derived, bool> {
4163protected:
4164 LValue &Result;
4165 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4166 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4167
4168 bool Success(APValue::LValueBase B) {
4169 Result.set(B);
4170 return true;
4171 }
4172
4173public:
4174 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4175 ExprEvaluatorBaseTy(Info), Result(Result) {}
4176
Richard Smith2e312c82012-03-03 22:46:17 +00004177 bool Success(const APValue &V, const Expr *E) {
4178 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004179 return true;
4180 }
Richard Smith027bf112011-11-17 22:56:20 +00004181
Richard Smith027bf112011-11-17 22:56:20 +00004182 bool VisitMemberExpr(const MemberExpr *E) {
4183 // Handle non-static data members.
4184 QualType BaseTy;
4185 if (E->isArrow()) {
4186 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4187 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004188 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004189 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004190 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004191 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4192 return false;
4193 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004194 } else {
4195 if (!this->Visit(E->getBase()))
4196 return false;
4197 BaseTy = E->getBase()->getType();
4198 }
Richard Smith027bf112011-11-17 22:56:20 +00004199
Richard Smith1b78b3d2012-01-25 22:15:11 +00004200 const ValueDecl *MD = E->getMemberDecl();
4201 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4202 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4203 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4204 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004205 if (!HandleLValueMember(this->Info, E, Result, FD))
4206 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004207 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004208 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4209 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004210 } else
4211 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004212
Richard Smith1b78b3d2012-01-25 22:15:11 +00004213 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004214 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004215 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004216 RefValue))
4217 return false;
4218 return Success(RefValue, E);
4219 }
4220 return true;
4221 }
4222
4223 bool VisitBinaryOperator(const BinaryOperator *E) {
4224 switch (E->getOpcode()) {
4225 default:
4226 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4227
4228 case BO_PtrMemD:
4229 case BO_PtrMemI:
4230 return HandleMemberPointerAccess(this->Info, E, Result);
4231 }
4232 }
4233
4234 bool VisitCastExpr(const CastExpr *E) {
4235 switch (E->getCastKind()) {
4236 default:
4237 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4238
4239 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004240 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004241 if (!this->Visit(E->getSubExpr()))
4242 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004243
4244 // Now figure out the necessary offset to add to the base LV to get from
4245 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004246 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4247 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004248 }
4249 }
4250};
4251}
4252
4253//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004254// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004255//
4256// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4257// function designators (in C), decl references to void objects (in C), and
4258// temporaries (if building with -Wno-address-of-temporary).
4259//
4260// LValue evaluation produces values comprising a base expression of one of the
4261// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004262// - Declarations
4263// * VarDecl
4264// * FunctionDecl
4265// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004266// * CompoundLiteralExpr in C
4267// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004268// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004269// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004270// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004271// * ObjCEncodeExpr
4272// * AddrLabelExpr
4273// * BlockExpr
4274// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004275// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004276// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004277// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004278// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4279// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004280// * A MaterializeTemporaryExpr that has static storage duration, with no
4281// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004282// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004283//===----------------------------------------------------------------------===//
4284namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004285class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004286 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004287public:
Richard Smith027bf112011-11-17 22:56:20 +00004288 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4289 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004290
Richard Smith11562c52011-10-28 17:51:58 +00004291 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004292 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004293
Peter Collingbournee9200682011-05-13 03:29:01 +00004294 bool VisitDeclRefExpr(const DeclRefExpr *E);
4295 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004296 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004297 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4298 bool VisitMemberExpr(const MemberExpr *E);
4299 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4300 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004301 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004302 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004303 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4304 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004305 bool VisitUnaryReal(const UnaryOperator *E);
4306 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004307 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4308 return VisitUnaryPreIncDec(UO);
4309 }
4310 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4311 return VisitUnaryPreIncDec(UO);
4312 }
Richard Smith3229b742013-05-05 21:17:10 +00004313 bool VisitBinAssign(const BinaryOperator *BO);
4314 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004315
Peter Collingbournee9200682011-05-13 03:29:01 +00004316 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004317 switch (E->getCastKind()) {
4318 default:
Richard Smith027bf112011-11-17 22:56:20 +00004319 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004320
Eli Friedmance3e02a2011-10-11 00:13:24 +00004321 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004322 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004323 if (!Visit(E->getSubExpr()))
4324 return false;
4325 Result.Designator.setInvalid();
4326 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004327
Richard Smith027bf112011-11-17 22:56:20 +00004328 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004329 if (!Visit(E->getSubExpr()))
4330 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004331 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004332 }
4333 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004334};
4335} // end anonymous namespace
4336
Richard Smith11562c52011-10-28 17:51:58 +00004337/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004338/// expressions which are not glvalues, in two cases:
4339/// * function designators in C, and
4340/// * "extern void" objects
4341static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4342 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4343 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004344 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004345}
4346
Peter Collingbournee9200682011-05-13 03:29:01 +00004347bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004348 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4349 return Success(FD);
4350 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004351 return VisitVarDecl(E, VD);
4352 return Error(E);
4353}
Richard Smith733237d2011-10-24 23:14:33 +00004354
Richard Smith11562c52011-10-28 17:51:58 +00004355bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004356 CallStackFrame *Frame = 0;
4357 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4358 Frame = Info.CurrentCall;
4359
Richard Smithfec09922011-11-01 16:57:24 +00004360 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004361 if (Frame) {
4362 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004363 return true;
4364 }
Richard Smithce40ad62011-11-12 22:28:03 +00004365 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004366 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004367
Richard Smith3229b742013-05-05 21:17:10 +00004368 APValue *V;
4369 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004370 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004371 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004372 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004373 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4374 return false;
4375 }
Richard Smith3229b742013-05-05 21:17:10 +00004376 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004377}
4378
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004379bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4380 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004381 // Walk through the expression to find the materialized temporary itself.
4382 SmallVector<const Expr *, 2> CommaLHSs;
4383 SmallVector<SubobjectAdjustment, 2> Adjustments;
4384 const Expr *Inner = E->GetTemporaryExpr()->
4385 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004386
Richard Smith84401042013-06-03 05:03:02 +00004387 // If we passed any comma operators, evaluate their LHSs.
4388 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4389 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4390 return false;
4391
Richard Smithe6c01442013-06-05 00:46:14 +00004392 // A materialized temporary with static storage duration can appear within the
4393 // result of a constant expression evaluation, so we need to preserve its
4394 // value for use outside this evaluation.
4395 APValue *Value;
4396 if (E->getStorageDuration() == SD_Static) {
4397 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004398 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004399 Result.set(E);
4400 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004401 Value = &Info.CurrentCall->
4402 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004403 Result.set(E, Info.CurrentCall->Index);
4404 }
4405
Richard Smithea4ad5d2013-06-06 08:19:16 +00004406 QualType Type = Inner->getType();
4407
Richard Smith84401042013-06-03 05:03:02 +00004408 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004409 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4410 (E->getStorageDuration() == SD_Static &&
4411 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4412 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004413 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004414 }
Richard Smith84401042013-06-03 05:03:02 +00004415
4416 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004417 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4418 --I;
4419 switch (Adjustments[I].Kind) {
4420 case SubobjectAdjustment::DerivedToBaseAdjustment:
4421 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4422 Type, Result))
4423 return false;
4424 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4425 break;
4426
4427 case SubobjectAdjustment::FieldAdjustment:
4428 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4429 return false;
4430 Type = Adjustments[I].Field->getType();
4431 break;
4432
4433 case SubobjectAdjustment::MemberPointerAdjustment:
4434 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4435 Adjustments[I].Ptr.RHS))
4436 return false;
4437 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4438 break;
4439 }
4440 }
4441
4442 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004443}
4444
Peter Collingbournee9200682011-05-13 03:29:01 +00004445bool
4446LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004447 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4448 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4449 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004450 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004451}
4452
Richard Smith6e525142011-12-27 12:18:28 +00004453bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004454 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004455 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004456
4457 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4458 << E->getExprOperand()->getType()
4459 << E->getExprOperand()->getSourceRange();
4460 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004461}
4462
Francois Pichet0066db92012-04-16 04:08:35 +00004463bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4464 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004465}
Francois Pichet0066db92012-04-16 04:08:35 +00004466
Peter Collingbournee9200682011-05-13 03:29:01 +00004467bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004468 // Handle static data members.
4469 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4470 VisitIgnoredValue(E->getBase());
4471 return VisitVarDecl(E, VD);
4472 }
4473
Richard Smith254a73d2011-10-28 22:34:42 +00004474 // Handle static member functions.
4475 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4476 if (MD->isStatic()) {
4477 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004478 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004479 }
4480 }
4481
Richard Smithd62306a2011-11-10 06:34:14 +00004482 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004483 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004484}
4485
Peter Collingbournee9200682011-05-13 03:29:01 +00004486bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004487 // FIXME: Deal with vectors as array subscript bases.
4488 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004489 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004490
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004491 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004492 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004493
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004494 APSInt Index;
4495 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004496 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004497
Richard Smith861b5b52013-05-07 23:34:45 +00004498 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4499 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004500}
Eli Friedman9a156e52008-11-12 09:44:48 +00004501
Peter Collingbournee9200682011-05-13 03:29:01 +00004502bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004503 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004504}
4505
Richard Smith66c96992012-02-18 22:04:06 +00004506bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4507 if (!Visit(E->getSubExpr()))
4508 return false;
4509 // __real is a no-op on scalar lvalues.
4510 if (E->getSubExpr()->getType()->isAnyComplexType())
4511 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4512 return true;
4513}
4514
4515bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4516 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4517 "lvalue __imag__ on scalar?");
4518 if (!Visit(E->getSubExpr()))
4519 return false;
4520 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4521 return true;
4522}
4523
Richard Smith243ef902013-05-05 23:31:59 +00004524bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4525 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004526 return Error(UO);
4527
4528 if (!this->Visit(UO->getSubExpr()))
4529 return false;
4530
Richard Smith243ef902013-05-05 23:31:59 +00004531 return handleIncDec(
4532 this->Info, UO, Result, UO->getSubExpr()->getType(),
4533 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004534}
4535
4536bool LValueExprEvaluator::VisitCompoundAssignOperator(
4537 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004538 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004539 return Error(CAO);
4540
Richard Smith3229b742013-05-05 21:17:10 +00004541 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004542
4543 // The overall lvalue result is the result of evaluating the LHS.
4544 if (!this->Visit(CAO->getLHS())) {
4545 if (Info.keepEvaluatingAfterFailure())
4546 Evaluate(RHS, this->Info, CAO->getRHS());
4547 return false;
4548 }
4549
Richard Smith3229b742013-05-05 21:17:10 +00004550 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4551 return false;
4552
Richard Smith43e77732013-05-07 04:50:00 +00004553 return handleCompoundAssignment(
4554 this->Info, CAO,
4555 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4556 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004557}
4558
4559bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004560 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4561 return Error(E);
4562
Richard Smith3229b742013-05-05 21:17:10 +00004563 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004564
4565 if (!this->Visit(E->getLHS())) {
4566 if (Info.keepEvaluatingAfterFailure())
4567 Evaluate(NewVal, this->Info, E->getRHS());
4568 return false;
4569 }
4570
Richard Smith3229b742013-05-05 21:17:10 +00004571 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4572 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004573
4574 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004575 NewVal);
4576}
4577
Eli Friedman9a156e52008-11-12 09:44:48 +00004578//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004579// Pointer Evaluation
4580//===----------------------------------------------------------------------===//
4581
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004582namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004583class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004584 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004585 LValue &Result;
4586
Peter Collingbournee9200682011-05-13 03:29:01 +00004587 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004588 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004589 return true;
4590 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004591public:
Mike Stump11289f42009-09-09 15:08:12 +00004592
John McCall45d55e42010-05-07 21:00:08 +00004593 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004594 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004595
Richard Smith2e312c82012-03-03 22:46:17 +00004596 bool Success(const APValue &V, const Expr *E) {
4597 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004598 return true;
4599 }
Richard Smithfddd3842011-12-30 21:15:51 +00004600 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004601 return Success((Expr*)0);
4602 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004603
John McCall45d55e42010-05-07 21:00:08 +00004604 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004605 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004606 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004607 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004608 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004609 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004610 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004611 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004612 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004613 bool VisitCallExpr(const CallExpr *E);
4614 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004615 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004616 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004617 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004618 }
Richard Smithd62306a2011-11-10 06:34:14 +00004619 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004620 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004621 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004622 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004623 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004624 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004625 Result = *Info.CurrentCall->This;
4626 return true;
4627 }
John McCallc07a0c72011-02-17 10:25:35 +00004628
Eli Friedman449fe542009-03-23 04:56:01 +00004629 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004630};
Chris Lattner05706e882008-07-11 18:11:29 +00004631} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004632
John McCall45d55e42010-05-07 21:00:08 +00004633static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004634 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004635 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004636}
4637
John McCall45d55e42010-05-07 21:00:08 +00004638bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004639 if (E->getOpcode() != BO_Add &&
4640 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004641 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004642
Chris Lattner05706e882008-07-11 18:11:29 +00004643 const Expr *PExp = E->getLHS();
4644 const Expr *IExp = E->getRHS();
4645 if (IExp->getType()->isPointerType())
4646 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004647
Richard Smith253c2a32012-01-27 01:14:48 +00004648 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4649 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004650 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004651
John McCall45d55e42010-05-07 21:00:08 +00004652 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004653 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004654 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004655
4656 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004657 if (E->getOpcode() == BO_Sub)
4658 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004659
Ted Kremenek28831752012-08-23 20:46:57 +00004660 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004661 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4662 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004663}
Eli Friedman9a156e52008-11-12 09:44:48 +00004664
John McCall45d55e42010-05-07 21:00:08 +00004665bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4666 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004667}
Mike Stump11289f42009-09-09 15:08:12 +00004668
Peter Collingbournee9200682011-05-13 03:29:01 +00004669bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4670 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004671
Eli Friedman847a2bc2009-12-27 05:43:15 +00004672 switch (E->getCastKind()) {
4673 default:
4674 break;
4675
John McCalle3027922010-08-25 11:45:40 +00004676 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004677 case CK_CPointerToObjCPointerCast:
4678 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004679 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004680 if (!Visit(SubExpr))
4681 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004682 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4683 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4684 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004685 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004686 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004687 if (SubExpr->getType()->isVoidPointerType())
4688 CCEDiag(E, diag::note_constexpr_invalid_cast)
4689 << 3 << SubExpr->getType();
4690 else
4691 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4692 }
Richard Smith96e0c102011-11-04 02:25:55 +00004693 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004694
Anders Carlsson18275092010-10-31 20:41:46 +00004695 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004696 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004697 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004698 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004699 if (!Result.Base && Result.Offset.isZero())
4700 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004701
Richard Smithd62306a2011-11-10 06:34:14 +00004702 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004703 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004704 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4705 castAs<PointerType>()->getPointeeType(),
4706 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004707
Richard Smith027bf112011-11-17 22:56:20 +00004708 case CK_BaseToDerived:
4709 if (!Visit(E->getSubExpr()))
4710 return false;
4711 if (!Result.Base && Result.Offset.isZero())
4712 return true;
4713 return HandleBaseToDerivedCast(Info, E, Result);
4714
Richard Smith0b0a0b62011-10-29 20:57:55 +00004715 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004716 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004717 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004718
John McCalle3027922010-08-25 11:45:40 +00004719 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004720 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4721
Richard Smith2e312c82012-03-03 22:46:17 +00004722 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004723 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004724 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004725
John McCall45d55e42010-05-07 21:00:08 +00004726 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004727 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4728 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004729 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004730 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004731 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004732 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004733 return true;
4734 } else {
4735 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004736 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004737 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004738 }
4739 }
John McCalle3027922010-08-25 11:45:40 +00004740 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004741 if (SubExpr->isGLValue()) {
4742 if (!EvaluateLValue(SubExpr, Result, Info))
4743 return false;
4744 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004745 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004746 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004747 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004748 return false;
4749 }
Richard Smith96e0c102011-11-04 02:25:55 +00004750 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004751 if (const ConstantArrayType *CAT
4752 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4753 Result.addArray(Info, E, CAT);
4754 else
4755 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004756 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004757
John McCalle3027922010-08-25 11:45:40 +00004758 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004759 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004760 }
4761
Richard Smith11562c52011-10-28 17:51:58 +00004762 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004763}
Chris Lattner05706e882008-07-11 18:11:29 +00004764
Peter Collingbournee9200682011-05-13 03:29:01 +00004765bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004766 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004767 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004768
Richard Smith6cbd65d2013-07-11 02:27:57 +00004769 switch (E->isBuiltinCall()) {
4770 case Builtin::BI__builtin_addressof:
4771 return EvaluateLValue(E->getArg(0), Result, Info);
4772
4773 default:
4774 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4775 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004776}
Chris Lattner05706e882008-07-11 18:11:29 +00004777
4778//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004779// Member Pointer Evaluation
4780//===----------------------------------------------------------------------===//
4781
4782namespace {
4783class MemberPointerExprEvaluator
4784 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4785 MemberPtr &Result;
4786
4787 bool Success(const ValueDecl *D) {
4788 Result = MemberPtr(D);
4789 return true;
4790 }
4791public:
4792
4793 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4794 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4795
Richard Smith2e312c82012-03-03 22:46:17 +00004796 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004797 Result.setFrom(V);
4798 return true;
4799 }
Richard Smithfddd3842011-12-30 21:15:51 +00004800 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004801 return Success((const ValueDecl*)0);
4802 }
4803
4804 bool VisitCastExpr(const CastExpr *E);
4805 bool VisitUnaryAddrOf(const UnaryOperator *E);
4806};
4807} // end anonymous namespace
4808
4809static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4810 EvalInfo &Info) {
4811 assert(E->isRValue() && E->getType()->isMemberPointerType());
4812 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4813}
4814
4815bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4816 switch (E->getCastKind()) {
4817 default:
4818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4819
4820 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004821 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004822 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004823
4824 case CK_BaseToDerivedMemberPointer: {
4825 if (!Visit(E->getSubExpr()))
4826 return false;
4827 if (E->path_empty())
4828 return true;
4829 // Base-to-derived member pointer casts store the path in derived-to-base
4830 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4831 // the wrong end of the derived->base arc, so stagger the path by one class.
4832 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4833 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4834 PathI != PathE; ++PathI) {
4835 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4836 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4837 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004838 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004839 }
4840 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4841 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004842 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004843 return true;
4844 }
4845
4846 case CK_DerivedToBaseMemberPointer:
4847 if (!Visit(E->getSubExpr()))
4848 return false;
4849 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4850 PathE = E->path_end(); PathI != PathE; ++PathI) {
4851 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4852 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4853 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004854 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004855 }
4856 return true;
4857 }
4858}
4859
4860bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4861 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4862 // member can be formed.
4863 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4864}
4865
4866//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004867// Record Evaluation
4868//===----------------------------------------------------------------------===//
4869
4870namespace {
4871 class RecordExprEvaluator
4872 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4873 const LValue &This;
4874 APValue &Result;
4875 public:
4876
4877 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4878 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4879
Richard Smith2e312c82012-03-03 22:46:17 +00004880 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004881 Result = V;
4882 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004883 }
Richard Smithfddd3842011-12-30 21:15:51 +00004884 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004885
Richard Smithe97cbd72011-11-11 04:05:33 +00004886 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004887 bool VisitInitListExpr(const InitListExpr *E);
4888 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004889 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004890 };
4891}
4892
Richard Smithfddd3842011-12-30 21:15:51 +00004893/// Perform zero-initialization on an object of non-union class type.
4894/// C++11 [dcl.init]p5:
4895/// To zero-initialize an object or reference of type T means:
4896/// [...]
4897/// -- if T is a (possibly cv-qualified) non-union class type,
4898/// each non-static data member and each base-class subobject is
4899/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004900static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4901 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004902 const LValue &This, APValue &Result) {
4903 assert(!RD->isUnion() && "Expected non-union class type");
4904 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4905 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4906 std::distance(RD->field_begin(), RD->field_end()));
4907
John McCalld7bca762012-05-01 00:38:49 +00004908 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004909 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4910
4911 if (CD) {
4912 unsigned Index = 0;
4913 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004914 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004915 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4916 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004917 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4918 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004919 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004920 Result.getStructBase(Index)))
4921 return false;
4922 }
4923 }
4924
Richard Smitha8105bc2012-01-06 16:39:00 +00004925 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4926 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004927 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004928 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004929 continue;
4930
4931 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004932 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004933 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004934
David Blaikie2d7c57e2012-04-30 02:36:29 +00004935 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004936 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004937 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004938 return false;
4939 }
4940
4941 return true;
4942}
4943
4944bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4945 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004946 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004947 if (RD->isUnion()) {
4948 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4949 // object's first non-static named data member is zero-initialized
4950 RecordDecl::field_iterator I = RD->field_begin();
4951 if (I == RD->field_end()) {
4952 Result = APValue((const FieldDecl*)0);
4953 return true;
4954 }
4955
4956 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004957 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004958 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004959 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004960 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004961 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004962 }
4963
Richard Smith5d108602012-02-17 00:44:16 +00004964 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004965 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004966 return false;
4967 }
4968
Richard Smitha8105bc2012-01-06 16:39:00 +00004969 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004970}
4971
Richard Smithe97cbd72011-11-11 04:05:33 +00004972bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4973 switch (E->getCastKind()) {
4974 default:
4975 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4976
4977 case CK_ConstructorConversion:
4978 return Visit(E->getSubExpr());
4979
4980 case CK_DerivedToBase:
4981 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004982 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004983 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004984 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004985 if (!DerivedObject.isStruct())
4986 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004987
4988 // Derived-to-base rvalue conversion: just slice off the derived part.
4989 APValue *Value = &DerivedObject;
4990 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4991 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4992 PathE = E->path_end(); PathI != PathE; ++PathI) {
4993 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4994 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4995 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4996 RD = Base;
4997 }
4998 Result = *Value;
4999 return true;
5000 }
5001 }
5002}
5003
Richard Smithd62306a2011-11-10 06:34:14 +00005004bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5005 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005006 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005007 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5008
5009 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005010 const FieldDecl *Field = E->getInitializedFieldInUnion();
5011 Result = APValue(Field);
5012 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005013 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005014
5015 // If the initializer list for a union does not contain any elements, the
5016 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005017 // FIXME: The element should be initialized from an initializer list.
5018 // Is this difference ever observable for initializer lists which
5019 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005020 ImplicitValueInitExpr VIE(Field->getType());
5021 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5022
Richard Smithd62306a2011-11-10 06:34:14 +00005023 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005024 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5025 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005026
5027 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5028 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5029 isa<CXXDefaultInitExpr>(InitExpr));
5030
Richard Smithb228a862012-02-15 02:18:13 +00005031 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005032 }
5033
5034 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5035 "initializer list for class with base classes");
5036 Result = APValue(APValue::UninitStruct(), 0,
5037 std::distance(RD->field_begin(), RD->field_end()));
5038 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005039 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005040 for (RecordDecl::field_iterator Field = RD->field_begin(),
5041 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5042 // Anonymous bit-fields are not considered members of the class for
5043 // purposes of aggregate initialization.
5044 if (Field->isUnnamedBitfield())
5045 continue;
5046
5047 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005048
Richard Smith253c2a32012-01-27 01:14:48 +00005049 bool HaveInit = ElementNo < E->getNumInits();
5050
5051 // FIXME: Diagnostics here should point to the end of the initializer
5052 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005053 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00005054 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005055 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005056
5057 // Perform an implicit value-initialization for members beyond the end of
5058 // the initializer list.
5059 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005060 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005061
Richard Smith852c9db2013-04-20 22:23:05 +00005062 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5063 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5064 isa<CXXDefaultInitExpr>(Init));
5065
Richard Smith49ca8aa2013-08-06 07:09:20 +00005066 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5067 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5068 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5069 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005070 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005071 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005072 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005073 }
5074 }
5075
Richard Smith253c2a32012-01-27 01:14:48 +00005076 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005077}
5078
5079bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5080 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005081 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5082
Richard Smithfddd3842011-12-30 21:15:51 +00005083 bool ZeroInit = E->requiresZeroInitialization();
5084 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005085 // If we've already performed zero-initialization, we're already done.
5086 if (!Result.isUninit())
5087 return true;
5088
Richard Smithfddd3842011-12-30 21:15:51 +00005089 if (ZeroInit)
5090 return ZeroInitialization(E);
5091
Richard Smithcc36f692011-12-22 02:22:31 +00005092 const CXXRecordDecl *RD = FD->getParent();
5093 if (RD->isUnion())
5094 Result = APValue((FieldDecl*)0);
5095 else
5096 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5097 std::distance(RD->field_begin(), RD->field_end()));
5098 return true;
5099 }
5100
Richard Smithd62306a2011-11-10 06:34:14 +00005101 const FunctionDecl *Definition = 0;
5102 FD->getBody(Definition);
5103
Richard Smith357362d2011-12-13 06:39:58 +00005104 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5105 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005106
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005107 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005108 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005109 if (const MaterializeTemporaryExpr *ME
5110 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5111 return Visit(ME->GetTemporaryExpr());
5112
Richard Smithfddd3842011-12-30 21:15:51 +00005113 if (ZeroInit && !ZeroInitialization(E))
5114 return false;
5115
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005116 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005117 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005118 cast<CXXConstructorDecl>(Definition), Info,
5119 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005120}
5121
Richard Smithcc1b96d2013-06-12 22:31:48 +00005122bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5123 const CXXStdInitializerListExpr *E) {
5124 const ConstantArrayType *ArrayType =
5125 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5126
5127 LValue Array;
5128 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5129 return false;
5130
5131 // Get a pointer to the first element of the array.
5132 Array.addArray(Info, E, ArrayType);
5133
5134 // FIXME: Perform the checks on the field types in SemaInit.
5135 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5136 RecordDecl::field_iterator Field = Record->field_begin();
5137 if (Field == Record->field_end())
5138 return Error(E);
5139
5140 // Start pointer.
5141 if (!Field->getType()->isPointerType() ||
5142 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5143 ArrayType->getElementType()))
5144 return Error(E);
5145
5146 // FIXME: What if the initializer_list type has base classes, etc?
5147 Result = APValue(APValue::UninitStruct(), 0, 2);
5148 Array.moveInto(Result.getStructField(0));
5149
5150 if (++Field == Record->field_end())
5151 return Error(E);
5152
5153 if (Field->getType()->isPointerType() &&
5154 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5155 ArrayType->getElementType())) {
5156 // End pointer.
5157 if (!HandleLValueArrayAdjustment(Info, E, Array,
5158 ArrayType->getElementType(),
5159 ArrayType->getSize().getZExtValue()))
5160 return false;
5161 Array.moveInto(Result.getStructField(1));
5162 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5163 // Length.
5164 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5165 else
5166 return Error(E);
5167
5168 if (++Field != Record->field_end())
5169 return Error(E);
5170
5171 return true;
5172}
5173
Richard Smithd62306a2011-11-10 06:34:14 +00005174static bool EvaluateRecord(const Expr *E, const LValue &This,
5175 APValue &Result, EvalInfo &Info) {
5176 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005177 "can't evaluate expression as a record rvalue");
5178 return RecordExprEvaluator(Info, This, Result).Visit(E);
5179}
5180
5181//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005182// Temporary Evaluation
5183//
5184// Temporaries are represented in the AST as rvalues, but generally behave like
5185// lvalues. The full-object of which the temporary is a subobject is implicitly
5186// materialized so that a reference can bind to it.
5187//===----------------------------------------------------------------------===//
5188namespace {
5189class TemporaryExprEvaluator
5190 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5191public:
5192 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5193 LValueExprEvaluatorBaseTy(Info, Result) {}
5194
5195 /// Visit an expression which constructs the value of this temporary.
5196 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005197 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005198 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5199 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005200 }
5201
5202 bool VisitCastExpr(const CastExpr *E) {
5203 switch (E->getCastKind()) {
5204 default:
5205 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5206
5207 case CK_ConstructorConversion:
5208 return VisitConstructExpr(E->getSubExpr());
5209 }
5210 }
5211 bool VisitInitListExpr(const InitListExpr *E) {
5212 return VisitConstructExpr(E);
5213 }
5214 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5215 return VisitConstructExpr(E);
5216 }
5217 bool VisitCallExpr(const CallExpr *E) {
5218 return VisitConstructExpr(E);
5219 }
5220};
5221} // end anonymous namespace
5222
5223/// Evaluate an expression of record type as a temporary.
5224static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005225 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005226 return TemporaryExprEvaluator(Info, Result).Visit(E);
5227}
5228
5229//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005230// Vector Evaluation
5231//===----------------------------------------------------------------------===//
5232
5233namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005234 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005235 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5236 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005237 public:
Mike Stump11289f42009-09-09 15:08:12 +00005238
Richard Smith2d406342011-10-22 21:10:00 +00005239 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5240 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005241
Richard Smith2d406342011-10-22 21:10:00 +00005242 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5243 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5244 // FIXME: remove this APValue copy.
5245 Result = APValue(V.data(), V.size());
5246 return true;
5247 }
Richard Smith2e312c82012-03-03 22:46:17 +00005248 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005249 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005250 Result = V;
5251 return true;
5252 }
Richard Smithfddd3842011-12-30 21:15:51 +00005253 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005254
Richard Smith2d406342011-10-22 21:10:00 +00005255 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005256 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005257 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005258 bool VisitInitListExpr(const InitListExpr *E);
5259 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005260 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005261 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005262 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005263 };
5264} // end anonymous namespace
5265
5266static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005267 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005268 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005269}
5270
Richard Smith2d406342011-10-22 21:10:00 +00005271bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5272 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005273 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005274
Richard Smith161f09a2011-12-06 22:44:34 +00005275 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005276 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005277
Eli Friedmanc757de22011-03-25 00:43:55 +00005278 switch (E->getCastKind()) {
5279 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005280 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005281 if (SETy->isIntegerType()) {
5282 APSInt IntResult;
5283 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005284 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005285 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005286 } else if (SETy->isRealFloatingType()) {
5287 APFloat F(0.0);
5288 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005289 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005290 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005291 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005292 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005293 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005294
5295 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005296 SmallVector<APValue, 4> Elts(NElts, Val);
5297 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005298 }
Eli Friedman803acb32011-12-22 03:51:45 +00005299 case CK_BitCast: {
5300 // Evaluate the operand into an APInt we can extract from.
5301 llvm::APInt SValInt;
5302 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5303 return false;
5304 // Extract the elements
5305 QualType EltTy = VTy->getElementType();
5306 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5307 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5308 SmallVector<APValue, 4> Elts;
5309 if (EltTy->isRealFloatingType()) {
5310 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005311 unsigned FloatEltSize = EltSize;
5312 if (&Sem == &APFloat::x87DoubleExtended)
5313 FloatEltSize = 80;
5314 for (unsigned i = 0; i < NElts; i++) {
5315 llvm::APInt Elt;
5316 if (BigEndian)
5317 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5318 else
5319 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005320 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005321 }
5322 } else if (EltTy->isIntegerType()) {
5323 for (unsigned i = 0; i < NElts; i++) {
5324 llvm::APInt Elt;
5325 if (BigEndian)
5326 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5327 else
5328 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5329 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5330 }
5331 } else {
5332 return Error(E);
5333 }
5334 return Success(Elts, E);
5335 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005336 default:
Richard Smith11562c52011-10-28 17:51:58 +00005337 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005338 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005339}
5340
Richard Smith2d406342011-10-22 21:10:00 +00005341bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005342VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005343 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005344 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005345 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005346
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005347 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005348 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005349
Eli Friedmanb9c71292012-01-03 23:24:20 +00005350 // The number of initializers can be less than the number of
5351 // vector elements. For OpenCL, this can be due to nested vector
5352 // initialization. For GCC compatibility, missing trailing elements
5353 // should be initialized with zeroes.
5354 unsigned CountInits = 0, CountElts = 0;
5355 while (CountElts < NumElements) {
5356 // Handle nested vector initialization.
5357 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005358 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005359 APValue v;
5360 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5361 return Error(E);
5362 unsigned vlen = v.getVectorLength();
5363 for (unsigned j = 0; j < vlen; j++)
5364 Elements.push_back(v.getVectorElt(j));
5365 CountElts += vlen;
5366 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005367 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005368 if (CountInits < NumInits) {
5369 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005370 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005371 } else // trailing integer zero.
5372 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5373 Elements.push_back(APValue(sInt));
5374 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005375 } else {
5376 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005377 if (CountInits < NumInits) {
5378 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005379 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005380 } else // trailing float zero.
5381 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5382 Elements.push_back(APValue(f));
5383 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005384 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005385 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005386 }
Richard Smith2d406342011-10-22 21:10:00 +00005387 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005388}
5389
Richard Smith2d406342011-10-22 21:10:00 +00005390bool
Richard Smithfddd3842011-12-30 21:15:51 +00005391VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005392 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005393 QualType EltTy = VT->getElementType();
5394 APValue ZeroElement;
5395 if (EltTy->isIntegerType())
5396 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5397 else
5398 ZeroElement =
5399 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5400
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005401 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005402 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005403}
5404
Richard Smith2d406342011-10-22 21:10:00 +00005405bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005406 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005407 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005408}
5409
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005410//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005411// Array Evaluation
5412//===----------------------------------------------------------------------===//
5413
5414namespace {
5415 class ArrayExprEvaluator
5416 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005417 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005418 APValue &Result;
5419 public:
5420
Richard Smithd62306a2011-11-10 06:34:14 +00005421 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5422 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005423
5424 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005425 assert((V.isArray() || V.isLValue()) &&
5426 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005427 Result = V;
5428 return true;
5429 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005430
Richard Smithfddd3842011-12-30 21:15:51 +00005431 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005432 const ConstantArrayType *CAT =
5433 Info.Ctx.getAsConstantArrayType(E->getType());
5434 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005435 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005436
5437 Result = APValue(APValue::UninitArray(), 0,
5438 CAT->getSize().getZExtValue());
5439 if (!Result.hasArrayFiller()) return true;
5440
Richard Smithfddd3842011-12-30 21:15:51 +00005441 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005442 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005443 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005444 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005445 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005446 }
5447
Richard Smithf3e9e432011-11-07 09:22:26 +00005448 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005449 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005450 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5451 const LValue &Subobject,
5452 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005453 };
5454} // end anonymous namespace
5455
Richard Smithd62306a2011-11-10 06:34:14 +00005456static bool EvaluateArray(const Expr *E, const LValue &This,
5457 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005458 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005459 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005460}
5461
5462bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5463 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5464 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005465 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005466
Richard Smithca2cfbf2011-12-22 01:07:19 +00005467 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5468 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005469 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005470 LValue LV;
5471 if (!EvaluateLValue(E->getInit(0), LV, Info))
5472 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005473 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005474 LV.moveInto(Val);
5475 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005476 }
5477
Richard Smith253c2a32012-01-27 01:14:48 +00005478 bool Success = true;
5479
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005480 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5481 "zero-initialized array shouldn't have any initialized elts");
5482 APValue Filler;
5483 if (Result.isArray() && Result.hasArrayFiller())
5484 Filler = Result.getArrayFiller();
5485
Richard Smith9543c5e2013-04-22 14:44:29 +00005486 unsigned NumEltsToInit = E->getNumInits();
5487 unsigned NumElts = CAT->getSize().getZExtValue();
5488 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5489
5490 // If the initializer might depend on the array index, run it for each
5491 // array element. For now, just whitelist non-class value-initialization.
5492 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5493 NumEltsToInit = NumElts;
5494
5495 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005496
5497 // If the array was previously zero-initialized, preserve the
5498 // zero-initialized values.
5499 if (!Filler.isUninit()) {
5500 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5501 Result.getArrayInitializedElt(I) = Filler;
5502 if (Result.hasArrayFiller())
5503 Result.getArrayFiller() = Filler;
5504 }
5505
Richard Smithd62306a2011-11-10 06:34:14 +00005506 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005507 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005508 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5509 const Expr *Init =
5510 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005511 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005512 Info, Subobject, Init) ||
5513 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005514 CAT->getElementType(), 1)) {
5515 if (!Info.keepEvaluatingAfterFailure())
5516 return false;
5517 Success = false;
5518 }
Richard Smithd62306a2011-11-10 06:34:14 +00005519 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005520
Richard Smith9543c5e2013-04-22 14:44:29 +00005521 if (!Result.hasArrayFiller())
5522 return Success;
5523
5524 // If we get here, we have a trivial filler, which we can just evaluate
5525 // once and splat over the rest of the array elements.
5526 assert(FillerExpr && "no array filler for incomplete init list");
5527 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5528 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005529}
5530
Richard Smith027bf112011-11-17 22:56:20 +00005531bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005532 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5533}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005534
Richard Smith9543c5e2013-04-22 14:44:29 +00005535bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5536 const LValue &Subobject,
5537 APValue *Value,
5538 QualType Type) {
5539 bool HadZeroInit = !Value->isUninit();
5540
5541 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5542 unsigned N = CAT->getSize().getZExtValue();
5543
5544 // Preserve the array filler if we had prior zero-initialization.
5545 APValue Filler =
5546 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5547 : APValue();
5548
5549 *Value = APValue(APValue::UninitArray(), N, N);
5550
5551 if (HadZeroInit)
5552 for (unsigned I = 0; I != N; ++I)
5553 Value->getArrayInitializedElt(I) = Filler;
5554
5555 // Initialize the elements.
5556 LValue ArrayElt = Subobject;
5557 ArrayElt.addArray(Info, E, CAT);
5558 for (unsigned I = 0; I != N; ++I)
5559 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5560 CAT->getElementType()) ||
5561 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5562 CAT->getElementType(), 1))
5563 return false;
5564
5565 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005566 }
Richard Smith027bf112011-11-17 22:56:20 +00005567
Richard Smith9543c5e2013-04-22 14:44:29 +00005568 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005569 return Error(E);
5570
Richard Smith027bf112011-11-17 22:56:20 +00005571 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005572
Richard Smithfddd3842011-12-30 21:15:51 +00005573 bool ZeroInit = E->requiresZeroInitialization();
5574 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005575 if (HadZeroInit)
5576 return true;
5577
Richard Smithfddd3842011-12-30 21:15:51 +00005578 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005579 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005580 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005581 }
5582
Richard Smithcc36f692011-12-22 02:22:31 +00005583 const CXXRecordDecl *RD = FD->getParent();
5584 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005585 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005586 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005587 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005588 APValue(APValue::UninitStruct(), RD->getNumBases(),
5589 std::distance(RD->field_begin(), RD->field_end()));
5590 return true;
5591 }
5592
Richard Smith027bf112011-11-17 22:56:20 +00005593 const FunctionDecl *Definition = 0;
5594 FD->getBody(Definition);
5595
Richard Smith357362d2011-12-13 06:39:58 +00005596 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5597 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005598
Richard Smith9eae7232012-01-12 18:54:33 +00005599 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005600 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005601 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005602 return false;
5603 }
5604
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005605 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005606 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005607 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005608 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005609}
5610
Richard Smithf3e9e432011-11-07 09:22:26 +00005611//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005612// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005613//
5614// As a GNU extension, we support casting pointers to sufficiently-wide integer
5615// types and back in constant folding. Integer values are thus represented
5616// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005617//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005618
5619namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005620class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005621 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005622 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005623public:
Richard Smith2e312c82012-03-03 22:46:17 +00005624 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005625 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005626
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005627 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005628 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005629 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005630 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005631 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005632 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005633 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005634 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005635 return true;
5636 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005637 bool Success(const llvm::APSInt &SI, const Expr *E) {
5638 return Success(SI, E, Result);
5639 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005640
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005641 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005642 assert(E->getType()->isIntegralOrEnumerationType() &&
5643 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005644 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005645 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005646 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005647 Result.getInt().setIsUnsigned(
5648 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005649 return true;
5650 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005651 bool Success(const llvm::APInt &I, const Expr *E) {
5652 return Success(I, E, Result);
5653 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005654
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005655 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005656 assert(E->getType()->isIntegralOrEnumerationType() &&
5657 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005658 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005659 return true;
5660 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005661 bool Success(uint64_t Value, const Expr *E) {
5662 return Success(Value, E, Result);
5663 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005664
Ken Dyckdbc01912011-03-11 02:13:43 +00005665 bool Success(CharUnits Size, const Expr *E) {
5666 return Success(Size.getQuantity(), E);
5667 }
5668
Richard Smith2e312c82012-03-03 22:46:17 +00005669 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005670 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005671 Result = V;
5672 return true;
5673 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005674 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005675 }
Mike Stump11289f42009-09-09 15:08:12 +00005676
Richard Smithfddd3842011-12-30 21:15:51 +00005677 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005678
Peter Collingbournee9200682011-05-13 03:29:01 +00005679 //===--------------------------------------------------------------------===//
5680 // Visitor Methods
5681 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005682
Chris Lattner7174bf32008-07-12 00:38:25 +00005683 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005684 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005685 }
5686 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005687 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005688 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005689
5690 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5691 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005692 if (CheckReferencedDecl(E, E->getDecl()))
5693 return true;
5694
5695 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005696 }
5697 bool VisitMemberExpr(const MemberExpr *E) {
5698 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005699 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005700 return true;
5701 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005702
5703 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005704 }
5705
Peter Collingbournee9200682011-05-13 03:29:01 +00005706 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005707 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005708 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005709 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005710
Peter Collingbournee9200682011-05-13 03:29:01 +00005711 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005712 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005713
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005714 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005715 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005716 }
Mike Stump11289f42009-09-09 15:08:12 +00005717
Ted Kremeneke65b0862012-03-06 20:05:56 +00005718 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5719 return Success(E->getValue(), E);
5720 }
5721
Richard Smith4ce706a2011-10-11 21:43:33 +00005722 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005723 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005724 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005725 }
5726
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005727 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005728 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005729 }
5730
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005731 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5732 return Success(E->getValue(), E);
5733 }
5734
Douglas Gregor29c42f22012-02-24 07:38:34 +00005735 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5736 return Success(E->getValue(), E);
5737 }
5738
John Wiegley6242b6a2011-04-28 00:16:57 +00005739 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5740 return Success(E->getValue(), E);
5741 }
5742
John Wiegleyf9f65842011-04-25 06:54:41 +00005743 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5744 return Success(E->getValue(), E);
5745 }
5746
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005747 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005748 bool VisitUnaryImag(const UnaryOperator *E);
5749
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005750 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005751 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005752
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005753private:
Ken Dyck160146e2010-01-27 17:10:57 +00005754 CharUnits GetAlignOfExpr(const Expr *E);
5755 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005756 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005757 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005758 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005759};
Chris Lattner05706e882008-07-11 18:11:29 +00005760} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005761
Richard Smith11562c52011-10-28 17:51:58 +00005762/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5763/// produce either the integer value or a pointer.
5764///
5765/// GCC has a heinous extension which folds casts between pointer types and
5766/// pointer-sized integral types. We support this by allowing the evaluation of
5767/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5768/// Some simple arithmetic on such values is supported (they are treated much
5769/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005770static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005771 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005772 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005773 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005774}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005775
Richard Smithf57d8cb2011-12-09 22:58:01 +00005776static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005777 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005778 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005779 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005780 if (!Val.isInt()) {
5781 // FIXME: It would be better to produce the diagnostic for casting
5782 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005783 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005784 return false;
5785 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005786 Result = Val.getInt();
5787 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005788}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005789
Richard Smithf57d8cb2011-12-09 22:58:01 +00005790/// Check whether the given declaration can be directly converted to an integral
5791/// rvalue. If not, no diagnostic is produced; there are other things we can
5792/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005793bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005794 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005795 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005796 // Check for signedness/width mismatches between E type and ECD value.
5797 bool SameSign = (ECD->getInitVal().isSigned()
5798 == E->getType()->isSignedIntegerOrEnumerationType());
5799 bool SameWidth = (ECD->getInitVal().getBitWidth()
5800 == Info.Ctx.getIntWidth(E->getType()));
5801 if (SameSign && SameWidth)
5802 return Success(ECD->getInitVal(), E);
5803 else {
5804 // Get rid of mismatch (otherwise Success assertions will fail)
5805 // by computing a new value matching the type of E.
5806 llvm::APSInt Val = ECD->getInitVal();
5807 if (!SameSign)
5808 Val.setIsSigned(!ECD->getInitVal().isSigned());
5809 if (!SameWidth)
5810 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5811 return Success(Val, E);
5812 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005813 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005814 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005815}
5816
Chris Lattner86ee2862008-10-06 06:40:35 +00005817/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5818/// as GCC.
5819static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5820 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005821 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005822 enum gcc_type_class {
5823 no_type_class = -1,
5824 void_type_class, integer_type_class, char_type_class,
5825 enumeral_type_class, boolean_type_class,
5826 pointer_type_class, reference_type_class, offset_type_class,
5827 real_type_class, complex_type_class,
5828 function_type_class, method_type_class,
5829 record_type_class, union_type_class,
5830 array_type_class, string_type_class,
5831 lang_type_class
5832 };
Mike Stump11289f42009-09-09 15:08:12 +00005833
5834 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005835 // ideal, however it is what gcc does.
5836 if (E->getNumArgs() == 0)
5837 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005838
Chris Lattner86ee2862008-10-06 06:40:35 +00005839 QualType ArgTy = E->getArg(0)->getType();
5840 if (ArgTy->isVoidType())
5841 return void_type_class;
5842 else if (ArgTy->isEnumeralType())
5843 return enumeral_type_class;
5844 else if (ArgTy->isBooleanType())
5845 return boolean_type_class;
5846 else if (ArgTy->isCharType())
5847 return string_type_class; // gcc doesn't appear to use char_type_class
5848 else if (ArgTy->isIntegerType())
5849 return integer_type_class;
5850 else if (ArgTy->isPointerType())
5851 return pointer_type_class;
5852 else if (ArgTy->isReferenceType())
5853 return reference_type_class;
5854 else if (ArgTy->isRealType())
5855 return real_type_class;
5856 else if (ArgTy->isComplexType())
5857 return complex_type_class;
5858 else if (ArgTy->isFunctionType())
5859 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005860 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005861 return record_type_class;
5862 else if (ArgTy->isUnionType())
5863 return union_type_class;
5864 else if (ArgTy->isArrayType())
5865 return array_type_class;
5866 else if (ArgTy->isUnionType())
5867 return union_type_class;
5868 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005869 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005870}
5871
Richard Smith5fab0c92011-12-28 19:48:30 +00005872/// EvaluateBuiltinConstantPForLValue - Determine the result of
5873/// __builtin_constant_p when applied to the given lvalue.
5874///
5875/// An lvalue is only "constant" if it is a pointer or reference to the first
5876/// character of a string literal.
5877template<typename LValue>
5878static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005879 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005880 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5881}
5882
5883/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5884/// GCC as we can manage.
5885static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5886 QualType ArgType = Arg->getType();
5887
5888 // __builtin_constant_p always has one operand. The rules which gcc follows
5889 // are not precisely documented, but are as follows:
5890 //
5891 // - If the operand is of integral, floating, complex or enumeration type,
5892 // and can be folded to a known value of that type, it returns 1.
5893 // - If the operand and can be folded to a pointer to the first character
5894 // of a string literal (or such a pointer cast to an integral type), it
5895 // returns 1.
5896 //
5897 // Otherwise, it returns 0.
5898 //
5899 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5900 // its support for this does not currently work.
5901 if (ArgType->isIntegralOrEnumerationType()) {
5902 Expr::EvalResult Result;
5903 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5904 return false;
5905
5906 APValue &V = Result.Val;
5907 if (V.getKind() == APValue::Int)
5908 return true;
5909
5910 return EvaluateBuiltinConstantPForLValue(V);
5911 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5912 return Arg->isEvaluatable(Ctx);
5913 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5914 LValue LV;
5915 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005916 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005917 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5918 : EvaluatePointer(Arg, LV, Info)) &&
5919 !Status.HasSideEffects)
5920 return EvaluateBuiltinConstantPForLValue(LV);
5921 }
5922
5923 // Anything else isn't considered to be sufficiently constant.
5924 return false;
5925}
5926
John McCall95007602010-05-10 23:27:23 +00005927/// Retrieves the "underlying object type" of the given expression,
5928/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005929QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5930 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5931 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005932 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005933 } else if (const Expr *E = B.get<const Expr*>()) {
5934 if (isa<CompoundLiteralExpr>(E))
5935 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005936 }
5937
5938 return QualType();
5939}
5940
Peter Collingbournee9200682011-05-13 03:29:01 +00005941bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005942 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005943
5944 {
5945 // The operand of __builtin_object_size is never evaluated for side-effects.
5946 // If there are any, but we can determine the pointed-to object anyway, then
5947 // ignore the side-effects.
5948 SpeculativeEvaluationRAII SpeculativeEval(Info);
5949 if (!EvaluatePointer(E->getArg(0), Base, Info))
5950 return false;
5951 }
John McCall95007602010-05-10 23:27:23 +00005952
5953 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005954 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005955
Richard Smithce40ad62011-11-12 22:28:03 +00005956 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005957 if (T.isNull() ||
5958 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005959 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005960 T->isVariablyModifiedType() ||
5961 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005962 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005963
5964 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5965 CharUnits Offset = Base.getLValueOffset();
5966
5967 if (!Offset.isNegative() && Offset <= Size)
5968 Size -= Offset;
5969 else
5970 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005971 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005972}
5973
Peter Collingbournee9200682011-05-13 03:29:01 +00005974bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005975 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005976 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005977 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005978
5979 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005980 if (TryEvaluateBuiltinObjectSize(E))
5981 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005982
Richard Smith0421ce72012-08-07 04:16:51 +00005983 // If evaluating the argument has side-effects, we can't determine the size
5984 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5985 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005986 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005987 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005988 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005989 return Success(0, E);
5990 }
Mike Stump876387b2009-10-27 22:09:17 +00005991
Richard Smith01ade172012-05-23 04:13:20 +00005992 // Expression had no side effects, but we couldn't statically determine the
5993 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005994 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005995 }
5996
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005997 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005998 case Builtin::BI__builtin_bswap32:
5999 case Builtin::BI__builtin_bswap64: {
6000 APSInt Val;
6001 if (!EvaluateInteger(E->getArg(0), Val, Info))
6002 return false;
6003
6004 return Success(Val.byteSwap(), E);
6005 }
6006
Richard Smith8889a3d2013-06-13 06:26:32 +00006007 case Builtin::BI__builtin_classify_type:
6008 return Success(EvaluateBuiltinClassifyType(E), E);
6009
6010 // FIXME: BI__builtin_clrsb
6011 // FIXME: BI__builtin_clrsbl
6012 // FIXME: BI__builtin_clrsbll
6013
Richard Smith80b3c8e2013-06-13 05:04:16 +00006014 case Builtin::BI__builtin_clz:
6015 case Builtin::BI__builtin_clzl:
6016 case Builtin::BI__builtin_clzll: {
6017 APSInt Val;
6018 if (!EvaluateInteger(E->getArg(0), Val, Info))
6019 return false;
6020 if (!Val)
6021 return Error(E);
6022
6023 return Success(Val.countLeadingZeros(), E);
6024 }
6025
Richard Smith8889a3d2013-06-13 06:26:32 +00006026 case Builtin::BI__builtin_constant_p:
6027 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6028
Richard Smith80b3c8e2013-06-13 05:04:16 +00006029 case Builtin::BI__builtin_ctz:
6030 case Builtin::BI__builtin_ctzl:
6031 case Builtin::BI__builtin_ctzll: {
6032 APSInt Val;
6033 if (!EvaluateInteger(E->getArg(0), Val, Info))
6034 return false;
6035 if (!Val)
6036 return Error(E);
6037
6038 return Success(Val.countTrailingZeros(), E);
6039 }
6040
Richard Smith8889a3d2013-06-13 06:26:32 +00006041 case Builtin::BI__builtin_eh_return_data_regno: {
6042 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6043 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6044 return Success(Operand, E);
6045 }
6046
6047 case Builtin::BI__builtin_expect:
6048 return Visit(E->getArg(0));
6049
6050 case Builtin::BI__builtin_ffs:
6051 case Builtin::BI__builtin_ffsl:
6052 case Builtin::BI__builtin_ffsll: {
6053 APSInt Val;
6054 if (!EvaluateInteger(E->getArg(0), Val, Info))
6055 return false;
6056
6057 unsigned N = Val.countTrailingZeros();
6058 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6059 }
6060
6061 case Builtin::BI__builtin_fpclassify: {
6062 APFloat Val(0.0);
6063 if (!EvaluateFloat(E->getArg(5), Val, Info))
6064 return false;
6065 unsigned Arg;
6066 switch (Val.getCategory()) {
6067 case APFloat::fcNaN: Arg = 0; break;
6068 case APFloat::fcInfinity: Arg = 1; break;
6069 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6070 case APFloat::fcZero: Arg = 4; break;
6071 }
6072 return Visit(E->getArg(Arg));
6073 }
6074
6075 case Builtin::BI__builtin_isinf_sign: {
6076 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006077 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006078 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6079 }
6080
Richard Smithea3019d2013-10-15 19:07:14 +00006081 case Builtin::BI__builtin_isinf: {
6082 APFloat Val(0.0);
6083 return EvaluateFloat(E->getArg(0), Val, Info) &&
6084 Success(Val.isInfinity() ? 1 : 0, E);
6085 }
6086
6087 case Builtin::BI__builtin_isfinite: {
6088 APFloat Val(0.0);
6089 return EvaluateFloat(E->getArg(0), Val, Info) &&
6090 Success(Val.isFinite() ? 1 : 0, E);
6091 }
6092
6093 case Builtin::BI__builtin_isnan: {
6094 APFloat Val(0.0);
6095 return EvaluateFloat(E->getArg(0), Val, Info) &&
6096 Success(Val.isNaN() ? 1 : 0, E);
6097 }
6098
6099 case Builtin::BI__builtin_isnormal: {
6100 APFloat Val(0.0);
6101 return EvaluateFloat(E->getArg(0), Val, Info) &&
6102 Success(Val.isNormal() ? 1 : 0, E);
6103 }
6104
Richard Smith8889a3d2013-06-13 06:26:32 +00006105 case Builtin::BI__builtin_parity:
6106 case Builtin::BI__builtin_parityl:
6107 case Builtin::BI__builtin_parityll: {
6108 APSInt Val;
6109 if (!EvaluateInteger(E->getArg(0), Val, Info))
6110 return false;
6111
6112 return Success(Val.countPopulation() % 2, E);
6113 }
6114
Richard Smith80b3c8e2013-06-13 05:04:16 +00006115 case Builtin::BI__builtin_popcount:
6116 case Builtin::BI__builtin_popcountl:
6117 case Builtin::BI__builtin_popcountll: {
6118 APSInt Val;
6119 if (!EvaluateInteger(E->getArg(0), Val, Info))
6120 return false;
6121
6122 return Success(Val.countPopulation(), E);
6123 }
6124
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006125 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006126 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006127 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006128 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006129 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6130 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006131 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006132 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006133 case Builtin::BI__builtin_strlen:
6134 // As an extension, we support strlen() and __builtin_strlen() as constant
6135 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00006136 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006137 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6138 // The string literal may have embedded null characters. Find the first
6139 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006140 StringRef Str = S->getString();
6141 StringRef::size_type Pos = Str.find(0);
6142 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006143 Str = Str.substr(0, Pos);
6144
6145 return Success(Str.size(), E);
6146 }
6147
Richard Smithf57d8cb2011-12-09 22:58:01 +00006148 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006149
Richard Smith01ba47d2012-04-13 00:45:38 +00006150 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006151 case Builtin::BI__atomic_is_lock_free:
6152 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006153 APSInt SizeVal;
6154 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6155 return false;
6156
6157 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6158 // of two less than the maximum inline atomic width, we know it is
6159 // lock-free. If the size isn't a power of two, or greater than the
6160 // maximum alignment where we promote atomics, we know it is not lock-free
6161 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6162 // the answer can only be determined at runtime; for example, 16-byte
6163 // atomics have lock-free implementations on some, but not all,
6164 // x86-64 processors.
6165
6166 // Check power-of-two.
6167 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006168 if (Size.isPowerOfTwo()) {
6169 // Check against inlining width.
6170 unsigned InlineWidthBits =
6171 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6172 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6173 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6174 Size == CharUnits::One() ||
6175 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6176 Expr::NPC_NeverValueDependent))
6177 // OK, we will inline appropriately-aligned operations of this size,
6178 // and _Atomic(T) is appropriately-aligned.
6179 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006180
Richard Smith01ba47d2012-04-13 00:45:38 +00006181 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6182 castAs<PointerType>()->getPointeeType();
6183 if (!PointeeType->isIncompleteType() &&
6184 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6185 // OK, we will inline operations on this object.
6186 return Success(1, E);
6187 }
6188 }
6189 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006190
Richard Smith01ba47d2012-04-13 00:45:38 +00006191 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6192 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006193 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006194 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006195}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006196
Richard Smith8b3497e2011-10-31 01:37:14 +00006197static bool HasSameBase(const LValue &A, const LValue &B) {
6198 if (!A.getLValueBase())
6199 return !B.getLValueBase();
6200 if (!B.getLValueBase())
6201 return false;
6202
Richard Smithce40ad62011-11-12 22:28:03 +00006203 if (A.getLValueBase().getOpaqueValue() !=
6204 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006205 const Decl *ADecl = GetLValueBaseDecl(A);
6206 if (!ADecl)
6207 return false;
6208 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006209 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006210 return false;
6211 }
6212
6213 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006214 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006215}
6216
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006217namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006219/// \brief Data recursive integer evaluator of certain binary operators.
6220///
6221/// We use a data recursive algorithm for binary operators so that we are able
6222/// to handle extreme cases of chained binary operators without causing stack
6223/// overflow.
6224class DataRecursiveIntBinOpEvaluator {
6225 struct EvalResult {
6226 APValue Val;
6227 bool Failed;
6228
6229 EvalResult() : Failed(false) { }
6230
6231 void swap(EvalResult &RHS) {
6232 Val.swap(RHS.Val);
6233 Failed = RHS.Failed;
6234 RHS.Failed = false;
6235 }
6236 };
6237
6238 struct Job {
6239 const Expr *E;
6240 EvalResult LHSResult; // meaningful only for binary operator expression.
6241 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6242
6243 Job() : StoredInfo(0) { }
6244 void startSpeculativeEval(EvalInfo &Info) {
6245 OldEvalStatus = Info.EvalStatus;
6246 Info.EvalStatus.Diag = 0;
6247 StoredInfo = &Info;
6248 }
6249 ~Job() {
6250 if (StoredInfo) {
6251 StoredInfo->EvalStatus = OldEvalStatus;
6252 }
6253 }
6254 private:
6255 EvalInfo *StoredInfo; // non-null if status changed.
6256 Expr::EvalStatus OldEvalStatus;
6257 };
6258
6259 SmallVector<Job, 16> Queue;
6260
6261 IntExprEvaluator &IntEval;
6262 EvalInfo &Info;
6263 APValue &FinalResult;
6264
6265public:
6266 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6267 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6268
6269 /// \brief True if \param E is a binary operator that we are going to handle
6270 /// data recursively.
6271 /// We handle binary operators that are comma, logical, or that have operands
6272 /// with integral or enumeration type.
6273 static bool shouldEnqueue(const BinaryOperator *E) {
6274 return E->getOpcode() == BO_Comma ||
6275 E->isLogicalOp() ||
6276 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6277 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006278 }
6279
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006280 bool Traverse(const BinaryOperator *E) {
6281 enqueue(E);
6282 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006283 while (!Queue.empty())
6284 process(PrevResult);
6285
6286 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006287
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006288 FinalResult.swap(PrevResult.Val);
6289 return true;
6290 }
6291
6292private:
6293 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6294 return IntEval.Success(Value, E, Result);
6295 }
6296 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6297 return IntEval.Success(Value, E, Result);
6298 }
6299 bool Error(const Expr *E) {
6300 return IntEval.Error(E);
6301 }
6302 bool Error(const Expr *E, diag::kind D) {
6303 return IntEval.Error(E, D);
6304 }
6305
6306 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6307 return Info.CCEDiag(E, D);
6308 }
6309
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006310 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6311 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006312 bool &SuppressRHSDiags);
6313
6314 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6315 const BinaryOperator *E, APValue &Result);
6316
6317 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6318 Result.Failed = !Evaluate(Result.Val, Info, E);
6319 if (Result.Failed)
6320 Result.Val = APValue();
6321 }
6322
Richard Trieuba4d0872012-03-21 23:30:30 +00006323 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006324
6325 void enqueue(const Expr *E) {
6326 E = E->IgnoreParens();
6327 Queue.resize(Queue.size()+1);
6328 Queue.back().E = E;
6329 Queue.back().Kind = Job::AnyExprKind;
6330 }
6331};
6332
6333}
6334
6335bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006336 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006337 bool &SuppressRHSDiags) {
6338 if (E->getOpcode() == BO_Comma) {
6339 // Ignore LHS but note if we could not evaluate it.
6340 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006341 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006342 return true;
6343 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006344
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006345 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006346 bool LHSAsBool;
6347 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006348 // We were able to evaluate the LHS, see if we can get away with not
6349 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006350 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6351 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006352 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006353 }
6354 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006355 LHSResult.Failed = true;
6356
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006357 // Since we weren't able to evaluate the left hand side, it
6358 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006359 if (!Info.noteSideEffect())
6360 return false;
6361
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006362 // We can't evaluate the LHS; however, sometimes the result
6363 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6364 // Don't ignore RHS and suppress diagnostics from this arm.
6365 SuppressRHSDiags = true;
6366 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006368 return true;
6369 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006370
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006371 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6372 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006373
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006374 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006375 return false; // Ignore RHS;
6376
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006377 return true;
6378}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006379
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006380bool DataRecursiveIntBinOpEvaluator::
6381 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6382 const BinaryOperator *E, APValue &Result) {
6383 if (E->getOpcode() == BO_Comma) {
6384 if (RHSResult.Failed)
6385 return false;
6386 Result = RHSResult.Val;
6387 return true;
6388 }
6389
6390 if (E->isLogicalOp()) {
6391 bool lhsResult, rhsResult;
6392 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6393 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6394
6395 if (LHSIsOK) {
6396 if (RHSIsOK) {
6397 if (E->getOpcode() == BO_LOr)
6398 return Success(lhsResult || rhsResult, E, Result);
6399 else
6400 return Success(lhsResult && rhsResult, E, Result);
6401 }
6402 } else {
6403 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006404 // We can't evaluate the LHS; however, sometimes the result
6405 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6406 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006407 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006408 }
6409 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006411 return false;
6412 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006413
6414 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6415 E->getRHS()->getType()->isIntegralOrEnumerationType());
6416
6417 if (LHSResult.Failed || RHSResult.Failed)
6418 return false;
6419
6420 const APValue &LHSVal = LHSResult.Val;
6421 const APValue &RHSVal = RHSResult.Val;
6422
6423 // Handle cases like (unsigned long)&a + 4.
6424 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6425 Result = LHSVal;
6426 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6427 RHSVal.getInt().getZExtValue());
6428 if (E->getOpcode() == BO_Add)
6429 Result.getLValueOffset() += AdditionalOffset;
6430 else
6431 Result.getLValueOffset() -= AdditionalOffset;
6432 return true;
6433 }
6434
6435 // Handle cases like 4 + (unsigned long)&a
6436 if (E->getOpcode() == BO_Add &&
6437 RHSVal.isLValue() && LHSVal.isInt()) {
6438 Result = RHSVal;
6439 Result.getLValueOffset() += CharUnits::fromQuantity(
6440 LHSVal.getInt().getZExtValue());
6441 return true;
6442 }
6443
6444 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6445 // Handle (intptr_t)&&A - (intptr_t)&&B.
6446 if (!LHSVal.getLValueOffset().isZero() ||
6447 !RHSVal.getLValueOffset().isZero())
6448 return false;
6449 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6450 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6451 if (!LHSExpr || !RHSExpr)
6452 return false;
6453 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6454 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6455 if (!LHSAddrExpr || !RHSAddrExpr)
6456 return false;
6457 // Make sure both labels come from the same function.
6458 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6459 RHSAddrExpr->getLabel()->getDeclContext())
6460 return false;
6461 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6462 return true;
6463 }
Richard Smith43e77732013-05-07 04:50:00 +00006464
6465 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006466 if (!LHSVal.isInt() || !RHSVal.isInt())
6467 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006468
6469 // Set up the width and signedness manually, in case it can't be deduced
6470 // from the operation we're performing.
6471 // FIXME: Don't do this in the cases where we can deduce it.
6472 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6473 E->getType()->isUnsignedIntegerOrEnumerationType());
6474 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6475 RHSVal.getInt(), Value))
6476 return false;
6477 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006478}
6479
Richard Trieuba4d0872012-03-21 23:30:30 +00006480void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006481 Job &job = Queue.back();
6482
6483 switch (job.Kind) {
6484 case Job::AnyExprKind: {
6485 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6486 if (shouldEnqueue(Bop)) {
6487 job.Kind = Job::BinOpKind;
6488 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006489 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006490 }
6491 }
6492
6493 EvaluateExpr(job.E, Result);
6494 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006495 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006496 }
6497
6498 case Job::BinOpKind: {
6499 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006500 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006501 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006502 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006503 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006504 }
6505 if (SuppressRHSDiags)
6506 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006507 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006508 job.Kind = Job::BinOpVisitedLHSKind;
6509 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006510 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006511 }
6512
6513 case Job::BinOpVisitedLHSKind: {
6514 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6515 EvalResult RHS;
6516 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006517 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006518 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006519 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006520 }
6521 }
6522
6523 llvm_unreachable("Invalid Job::Kind!");
6524}
6525
6526bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6527 if (E->isAssignmentOp())
6528 return Error(E);
6529
6530 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6531 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006532
Anders Carlssonacc79812008-11-16 07:17:21 +00006533 QualType LHSTy = E->getLHS()->getType();
6534 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006535
6536 if (LHSTy->isAnyComplexType()) {
6537 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006538 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006539
Richard Smith253c2a32012-01-27 01:14:48 +00006540 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6541 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006542 return false;
6543
Richard Smith253c2a32012-01-27 01:14:48 +00006544 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006545 return false;
6546
6547 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006548 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006549 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006550 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006551 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6552
John McCalle3027922010-08-25 11:45:40 +00006553 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006554 return Success((CR_r == APFloat::cmpEqual &&
6555 CR_i == APFloat::cmpEqual), E);
6556 else {
John McCalle3027922010-08-25 11:45:40 +00006557 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006558 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006559 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006560 CR_r == APFloat::cmpLessThan ||
6561 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006562 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006563 CR_i == APFloat::cmpLessThan ||
6564 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006565 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006566 } else {
John McCalle3027922010-08-25 11:45:40 +00006567 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006568 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6569 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6570 else {
John McCalle3027922010-08-25 11:45:40 +00006571 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006572 "Invalid compex comparison.");
6573 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6574 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6575 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006576 }
6577 }
Mike Stump11289f42009-09-09 15:08:12 +00006578
Anders Carlssonacc79812008-11-16 07:17:21 +00006579 if (LHSTy->isRealFloatingType() &&
6580 RHSTy->isRealFloatingType()) {
6581 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006582
Richard Smith253c2a32012-01-27 01:14:48 +00006583 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6584 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006585 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006586
Richard Smith253c2a32012-01-27 01:14:48 +00006587 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006588 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006589
Anders Carlssonacc79812008-11-16 07:17:21 +00006590 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006591
Anders Carlssonacc79812008-11-16 07:17:21 +00006592 switch (E->getOpcode()) {
6593 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006594 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006595 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006596 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006597 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006598 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006599 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006600 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006601 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006602 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006603 E);
John McCalle3027922010-08-25 11:45:40 +00006604 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006605 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006606 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006607 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006608 || CR == APFloat::cmpLessThan
6609 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006610 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006611 }
Mike Stump11289f42009-09-09 15:08:12 +00006612
Eli Friedmana38da572009-04-28 19:17:36 +00006613 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006614 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006615 LValue LHSValue, RHSValue;
6616
6617 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6618 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006619 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006620
Richard Smith253c2a32012-01-27 01:14:48 +00006621 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006622 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006623
Richard Smith8b3497e2011-10-31 01:37:14 +00006624 // Reject differing bases from the normal codepath; we special-case
6625 // comparisons to null.
6626 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006627 if (E->getOpcode() == BO_Sub) {
6628 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006629 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6630 return false;
6631 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006632 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006633 if (!LHSExpr || !RHSExpr)
6634 return false;
6635 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6636 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6637 if (!LHSAddrExpr || !RHSAddrExpr)
6638 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006639 // Make sure both labels come from the same function.
6640 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6641 RHSAddrExpr->getLabel()->getDeclContext())
6642 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006643 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006644 return true;
6645 }
Richard Smith83c68212011-10-31 05:11:32 +00006646 // Inequalities and subtractions between unrelated pointers have
6647 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006648 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006649 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006650 // A constant address may compare equal to the address of a symbol.
6651 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006652 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006653 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6654 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006655 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006656 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006657 // distinct addresses. In clang, the result of such a comparison is
6658 // unspecified, so it is not a constant expression. However, we do know
6659 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006660 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6661 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006662 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006663 // We can't tell whether weak symbols will end up pointing to the same
6664 // object.
6665 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006666 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006667 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006668 // (Note that clang defaults to -fmerge-all-constants, which can
6669 // lead to inconsistent results for comparisons involving the address
6670 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006671 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006672 }
Eli Friedman64004332009-03-23 04:38:34 +00006673
Richard Smith1b470412012-02-01 08:10:20 +00006674 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6675 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6676
Richard Smith84f6dcf2012-02-02 01:16:57 +00006677 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6678 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6679
John McCalle3027922010-08-25 11:45:40 +00006680 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006681 // C++11 [expr.add]p6:
6682 // Unless both pointers point to elements of the same array object, or
6683 // one past the last element of the array object, the behavior is
6684 // undefined.
6685 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6686 !AreElementsOfSameArray(getType(LHSValue.Base),
6687 LHSDesignator, RHSDesignator))
6688 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6689
Chris Lattner882bdf22010-04-20 17:13:14 +00006690 QualType Type = E->getLHS()->getType();
6691 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006692
Richard Smithd62306a2011-11-10 06:34:14 +00006693 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006694 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006695 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006696
Richard Smith84c6b3d2013-09-10 21:34:14 +00006697 // As an extension, a type may have zero size (empty struct or union in
6698 // C, array of zero length). Pointer subtraction in such cases has
6699 // undefined behavior, so is not constant.
6700 if (ElementSize.isZero()) {
6701 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6702 << ElementType;
6703 return false;
6704 }
6705
Richard Smith1b470412012-02-01 08:10:20 +00006706 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6707 // and produce incorrect results when it overflows. Such behavior
6708 // appears to be non-conforming, but is common, so perhaps we should
6709 // assume the standard intended for such cases to be undefined behavior
6710 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006711
Richard Smith1b470412012-02-01 08:10:20 +00006712 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6713 // overflow in the final conversion to ptrdiff_t.
6714 APSInt LHS(
6715 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6716 APSInt RHS(
6717 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6718 APSInt ElemSize(
6719 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6720 APSInt TrueResult = (LHS - RHS) / ElemSize;
6721 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6722
6723 if (Result.extend(65) != TrueResult)
6724 HandleOverflow(Info, E, TrueResult, E->getType());
6725 return Success(Result, E);
6726 }
Richard Smithde21b242012-01-31 06:41:30 +00006727
6728 // C++11 [expr.rel]p3:
6729 // Pointers to void (after pointer conversions) can be compared, with a
6730 // result defined as follows: If both pointers represent the same
6731 // address or are both the null pointer value, the result is true if the
6732 // operator is <= or >= and false otherwise; otherwise the result is
6733 // unspecified.
6734 // We interpret this as applying to pointers to *cv* void.
6735 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006736 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006737 CCEDiag(E, diag::note_constexpr_void_comparison);
6738
Richard Smith84f6dcf2012-02-02 01:16:57 +00006739 // C++11 [expr.rel]p2:
6740 // - If two pointers point to non-static data members of the same object,
6741 // or to subobjects or array elements fo such members, recursively, the
6742 // pointer to the later declared member compares greater provided the
6743 // two members have the same access control and provided their class is
6744 // not a union.
6745 // [...]
6746 // - Otherwise pointer comparisons are unspecified.
6747 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6748 E->isRelationalOp()) {
6749 bool WasArrayIndex;
6750 unsigned Mismatch =
6751 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6752 RHSDesignator, WasArrayIndex);
6753 // At the point where the designators diverge, the comparison has a
6754 // specified value if:
6755 // - we are comparing array indices
6756 // - we are comparing fields of a union, or fields with the same access
6757 // Otherwise, the result is unspecified and thus the comparison is not a
6758 // constant expression.
6759 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6760 Mismatch < RHSDesignator.Entries.size()) {
6761 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6762 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6763 if (!LF && !RF)
6764 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6765 else if (!LF)
6766 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6767 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6768 << RF->getParent() << RF;
6769 else if (!RF)
6770 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6771 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6772 << LF->getParent() << LF;
6773 else if (!LF->getParent()->isUnion() &&
6774 LF->getAccess() != RF->getAccess())
6775 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6776 << LF << LF->getAccess() << RF << RF->getAccess()
6777 << LF->getParent();
6778 }
6779 }
6780
Eli Friedman6c31cb42012-04-16 04:30:08 +00006781 // The comparison here must be unsigned, and performed with the same
6782 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006783 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6784 uint64_t CompareLHS = LHSOffset.getQuantity();
6785 uint64_t CompareRHS = RHSOffset.getQuantity();
6786 assert(PtrSize <= 64 && "Unexpected pointer width");
6787 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6788 CompareLHS &= Mask;
6789 CompareRHS &= Mask;
6790
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006791 // If there is a base and this is a relational operator, we can only
6792 // compare pointers within the object in question; otherwise, the result
6793 // depends on where the object is located in memory.
6794 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6795 QualType BaseTy = getType(LHSValue.Base);
6796 if (BaseTy->isIncompleteType())
6797 return Error(E);
6798 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6799 uint64_t OffsetLimit = Size.getQuantity();
6800 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6801 return Error(E);
6802 }
6803
Richard Smith8b3497e2011-10-31 01:37:14 +00006804 switch (E->getOpcode()) {
6805 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006806 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6807 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6808 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6809 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6810 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6811 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006812 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006813 }
6814 }
Richard Smith7bb00672012-02-01 01:42:44 +00006815
6816 if (LHSTy->isMemberPointerType()) {
6817 assert(E->isEqualityOp() && "unexpected member pointer operation");
6818 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6819
6820 MemberPtr LHSValue, RHSValue;
6821
6822 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6823 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6824 return false;
6825
6826 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6827 return false;
6828
6829 // C++11 [expr.eq]p2:
6830 // If both operands are null, they compare equal. Otherwise if only one is
6831 // null, they compare unequal.
6832 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6833 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6834 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6835 }
6836
6837 // Otherwise if either is a pointer to a virtual member function, the
6838 // result is unspecified.
6839 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6840 if (MD->isVirtual())
6841 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6842 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6843 if (MD->isVirtual())
6844 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6845
6846 // Otherwise they compare equal if and only if they would refer to the
6847 // same member of the same most derived object or the same subobject if
6848 // they were dereferenced with a hypothetical object of the associated
6849 // class type.
6850 bool Equal = LHSValue == RHSValue;
6851 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6852 }
6853
Richard Smithab44d9b2012-02-14 22:35:28 +00006854 if (LHSTy->isNullPtrType()) {
6855 assert(E->isComparisonOp() && "unexpected nullptr operation");
6856 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6857 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6858 // are compared, the result is true of the operator is <=, >= or ==, and
6859 // false otherwise.
6860 BinaryOperator::Opcode Opcode = E->getOpcode();
6861 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6862 }
6863
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006864 assert((!LHSTy->isIntegralOrEnumerationType() ||
6865 !RHSTy->isIntegralOrEnumerationType()) &&
6866 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6867 // We can't continue from here for non-integral types.
6868 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006869}
6870
Ken Dyck160146e2010-01-27 17:10:57 +00006871CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006872 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6873 // result shall be the alignment of the referenced type."
6874 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6875 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006876
6877 // __alignof is defined to return the preferred alignment.
6878 return Info.Ctx.toCharUnitsFromBits(
6879 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006880}
6881
Ken Dyck160146e2010-01-27 17:10:57 +00006882CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006883 E = E->IgnoreParens();
6884
John McCall768439e2013-05-06 07:40:34 +00006885 // The kinds of expressions that we have special-case logic here for
6886 // should be kept up to date with the special checks for those
6887 // expressions in Sema.
6888
Chris Lattner68061312009-01-24 21:53:27 +00006889 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006890 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006892 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6893 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006894
Chris Lattner68061312009-01-24 21:53:27 +00006895 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006896 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6897 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006898
Chris Lattner24aeeab2009-01-24 21:09:06 +00006899 return GetAlignOfType(E->getType());
6900}
6901
6902
Peter Collingbournee190dee2011-03-11 19:24:49 +00006903/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6904/// a result as the expression's type.
6905bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6906 const UnaryExprOrTypeTraitExpr *E) {
6907 switch(E->getKind()) {
6908 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006909 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006910 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006911 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006912 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006913 }
Eli Friedman64004332009-03-23 04:38:34 +00006914
Peter Collingbournee190dee2011-03-11 19:24:49 +00006915 case UETT_VecStep: {
6916 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006917
Peter Collingbournee190dee2011-03-11 19:24:49 +00006918 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006919 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006920
Peter Collingbournee190dee2011-03-11 19:24:49 +00006921 // The vec_step built-in functions that take a 3-component
6922 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6923 if (n == 3)
6924 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006925
Peter Collingbournee190dee2011-03-11 19:24:49 +00006926 return Success(n, E);
6927 } else
6928 return Success(1, E);
6929 }
6930
6931 case UETT_SizeOf: {
6932 QualType SrcTy = E->getTypeOfArgument();
6933 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6934 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006935 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6936 SrcTy = Ref->getPointeeType();
6937
Richard Smithd62306a2011-11-10 06:34:14 +00006938 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006939 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006940 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006941 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006942 }
6943 }
6944
6945 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006946}
6947
Peter Collingbournee9200682011-05-13 03:29:01 +00006948bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006949 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006950 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006951 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006952 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006953 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006954 for (unsigned i = 0; i != n; ++i) {
6955 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6956 switch (ON.getKind()) {
6957 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006958 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006959 APSInt IdxResult;
6960 if (!EvaluateInteger(Idx, IdxResult, Info))
6961 return false;
6962 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6963 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006964 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006965 CurrentType = AT->getElementType();
6966 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6967 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006968 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006969 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006970
Douglas Gregor882211c2010-04-28 22:16:22 +00006971 case OffsetOfExpr::OffsetOfNode::Field: {
6972 FieldDecl *MemberDecl = ON.getField();
6973 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006974 if (!RT)
6975 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006976 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006977 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006978 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006979 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006980 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006981 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006982 CurrentType = MemberDecl->getType().getNonReferenceType();
6983 break;
6984 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006985
Douglas Gregor882211c2010-04-28 22:16:22 +00006986 case OffsetOfExpr::OffsetOfNode::Identifier:
6987 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006988
Douglas Gregord1702062010-04-29 00:18:15 +00006989 case OffsetOfExpr::OffsetOfNode::Base: {
6990 CXXBaseSpecifier *BaseSpec = ON.getBase();
6991 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006992 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006993
6994 // Find the layout of the class whose base we are looking into.
6995 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006996 if (!RT)
6997 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006998 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006999 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007000 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7001
7002 // Find the base class itself.
7003 CurrentType = BaseSpec->getType();
7004 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7005 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007006 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007007
7008 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007009 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007010 break;
7011 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007012 }
7013 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007014 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007015}
7016
Chris Lattnere13042c2008-07-11 19:10:17 +00007017bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007018 switch (E->getOpcode()) {
7019 default:
7020 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7021 // See C99 6.6p3.
7022 return Error(E);
7023 case UO_Extension:
7024 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7025 // If so, we could clear the diagnostic ID.
7026 return Visit(E->getSubExpr());
7027 case UO_Plus:
7028 // The result is just the value.
7029 return Visit(E->getSubExpr());
7030 case UO_Minus: {
7031 if (!Visit(E->getSubExpr()))
7032 return false;
7033 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007034 const APSInt &Value = Result.getInt();
7035 if (Value.isSigned() && Value.isMinSignedValue())
7036 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7037 E->getType());
7038 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007039 }
7040 case UO_Not: {
7041 if (!Visit(E->getSubExpr()))
7042 return false;
7043 if (!Result.isInt()) return Error(E);
7044 return Success(~Result.getInt(), E);
7045 }
7046 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007047 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007048 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007049 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007050 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007051 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007052 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007053}
Mike Stump11289f42009-09-09 15:08:12 +00007054
Chris Lattner477c4be2008-07-12 01:15:53 +00007055/// HandleCast - This is used to evaluate implicit or explicit casts where the
7056/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007057bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7058 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007059 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007060 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007061
Eli Friedmanc757de22011-03-25 00:43:55 +00007062 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007063 case CK_BaseToDerived:
7064 case CK_DerivedToBase:
7065 case CK_UncheckedDerivedToBase:
7066 case CK_Dynamic:
7067 case CK_ToUnion:
7068 case CK_ArrayToPointerDecay:
7069 case CK_FunctionToPointerDecay:
7070 case CK_NullToPointer:
7071 case CK_NullToMemberPointer:
7072 case CK_BaseToDerivedMemberPointer:
7073 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007074 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007075 case CK_ConstructorConversion:
7076 case CK_IntegralToPointer:
7077 case CK_ToVoid:
7078 case CK_VectorSplat:
7079 case CK_IntegralToFloating:
7080 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007081 case CK_CPointerToObjCPointerCast:
7082 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007083 case CK_AnyPointerToBlockPointerCast:
7084 case CK_ObjCObjectLValueCast:
7085 case CK_FloatingRealToComplex:
7086 case CK_FloatingComplexToReal:
7087 case CK_FloatingComplexCast:
7088 case CK_FloatingComplexToIntegralComplex:
7089 case CK_IntegralRealToComplex:
7090 case CK_IntegralComplexCast:
7091 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007092 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007093 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007094 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007095 llvm_unreachable("invalid cast kind for integral value");
7096
Eli Friedman9faf2f92011-03-25 19:07:11 +00007097 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007098 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007099 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007100 case CK_ARCProduceObject:
7101 case CK_ARCConsumeObject:
7102 case CK_ARCReclaimReturnedObject:
7103 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007104 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007105 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007106
Richard Smith4ef685b2012-01-17 21:17:26 +00007107 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007108 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007109 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007110 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007111 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007112
7113 case CK_MemberPointerToBoolean:
7114 case CK_PointerToBoolean:
7115 case CK_IntegralToBoolean:
7116 case CK_FloatingToBoolean:
7117 case CK_FloatingComplexToBoolean:
7118 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007119 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007120 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007121 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007122 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007123 }
7124
Eli Friedmanc757de22011-03-25 00:43:55 +00007125 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007126 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007127 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007128
Eli Friedman742421e2009-02-20 01:15:07 +00007129 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007130 // Allow casts of address-of-label differences if they are no-ops
7131 // or narrowing. (The narrowing case isn't actually guaranteed to
7132 // be constant-evaluatable except in some narrow cases which are hard
7133 // to detect here. We let it through on the assumption the user knows
7134 // what they are doing.)
7135 if (Result.isAddrLabelDiff())
7136 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007137 // Only allow casts of lvalues if they are lossless.
7138 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7139 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007140
Richard Smith911e1422012-01-30 22:27:01 +00007141 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7142 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007143 }
Mike Stump11289f42009-09-09 15:08:12 +00007144
Eli Friedmanc757de22011-03-25 00:43:55 +00007145 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007146 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7147
John McCall45d55e42010-05-07 21:00:08 +00007148 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007149 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007150 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007151
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007152 if (LV.getLValueBase()) {
7153 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007154 // FIXME: Allow a larger integer size than the pointer size, and allow
7155 // narrowing back down to pointer width in subsequent integral casts.
7156 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007157 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007158 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007159
Richard Smithcf74da72011-11-16 07:18:12 +00007160 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007161 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007162 return true;
7163 }
7164
Ken Dyck02990832010-01-15 12:37:54 +00007165 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7166 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007167 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007168 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007169
Eli Friedmanc757de22011-03-25 00:43:55 +00007170 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007171 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007172 if (!EvaluateComplex(SubExpr, C, Info))
7173 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007174 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007175 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007176
Eli Friedmanc757de22011-03-25 00:43:55 +00007177 case CK_FloatingToIntegral: {
7178 APFloat F(0.0);
7179 if (!EvaluateFloat(SubExpr, F, Info))
7180 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007181
Richard Smith357362d2011-12-13 06:39:58 +00007182 APSInt Value;
7183 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7184 return false;
7185 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007186 }
7187 }
Mike Stump11289f42009-09-09 15:08:12 +00007188
Eli Friedmanc757de22011-03-25 00:43:55 +00007189 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007190}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007191
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007192bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7193 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007194 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007195 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7196 return false;
7197 if (!LV.isComplexInt())
7198 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007199 return Success(LV.getComplexIntReal(), E);
7200 }
7201
7202 return Visit(E->getSubExpr());
7203}
7204
Eli Friedman4e7a2412009-02-27 04:45:43 +00007205bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007206 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007207 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007208 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7209 return false;
7210 if (!LV.isComplexInt())
7211 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007212 return Success(LV.getComplexIntImag(), E);
7213 }
7214
Richard Smith4a678122011-10-24 18:44:57 +00007215 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007216 return Success(0, E);
7217}
7218
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007219bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7220 return Success(E->getPackLength(), E);
7221}
7222
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007223bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7224 return Success(E->getValue(), E);
7225}
7226
Chris Lattner05706e882008-07-11 18:11:29 +00007227//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007228// Float Evaluation
7229//===----------------------------------------------------------------------===//
7230
7231namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007232class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007233 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007234 APFloat &Result;
7235public:
7236 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007237 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007238
Richard Smith2e312c82012-03-03 22:46:17 +00007239 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007240 Result = V.getFloat();
7241 return true;
7242 }
Eli Friedman24c01542008-08-22 00:06:13 +00007243
Richard Smithfddd3842011-12-30 21:15:51 +00007244 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007245 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7246 return true;
7247 }
7248
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007249 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007250
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007251 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007252 bool VisitBinaryOperator(const BinaryOperator *E);
7253 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007254 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007255
John McCallb1fb0d32010-05-07 22:08:54 +00007256 bool VisitUnaryReal(const UnaryOperator *E);
7257 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007258
Richard Smithfddd3842011-12-30 21:15:51 +00007259 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007260};
7261} // end anonymous namespace
7262
7263static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007264 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007265 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007266}
7267
Jay Foad39c79802011-01-12 09:06:06 +00007268static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007269 QualType ResultTy,
7270 const Expr *Arg,
7271 bool SNaN,
7272 llvm::APFloat &Result) {
7273 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7274 if (!S) return false;
7275
7276 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7277
7278 llvm::APInt fill;
7279
7280 // Treat empty strings as if they were zero.
7281 if (S->getString().empty())
7282 fill = llvm::APInt(32, 0);
7283 else if (S->getString().getAsInteger(0, fill))
7284 return false;
7285
7286 if (SNaN)
7287 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7288 else
7289 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7290 return true;
7291}
7292
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007293bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007294 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007295 default:
7296 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7297
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007298 case Builtin::BI__builtin_huge_val:
7299 case Builtin::BI__builtin_huge_valf:
7300 case Builtin::BI__builtin_huge_vall:
7301 case Builtin::BI__builtin_inf:
7302 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007303 case Builtin::BI__builtin_infl: {
7304 const llvm::fltSemantics &Sem =
7305 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007306 Result = llvm::APFloat::getInf(Sem);
7307 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007308 }
Mike Stump11289f42009-09-09 15:08:12 +00007309
John McCall16291492010-02-28 13:00:19 +00007310 case Builtin::BI__builtin_nans:
7311 case Builtin::BI__builtin_nansf:
7312 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007313 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7314 true, Result))
7315 return Error(E);
7316 return true;
John McCall16291492010-02-28 13:00:19 +00007317
Chris Lattner0b7282e2008-10-06 06:31:58 +00007318 case Builtin::BI__builtin_nan:
7319 case Builtin::BI__builtin_nanf:
7320 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007321 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007322 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007323 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7324 false, Result))
7325 return Error(E);
7326 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007327
7328 case Builtin::BI__builtin_fabs:
7329 case Builtin::BI__builtin_fabsf:
7330 case Builtin::BI__builtin_fabsl:
7331 if (!EvaluateFloat(E->getArg(0), Result, Info))
7332 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007333
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007334 if (Result.isNegative())
7335 Result.changeSign();
7336 return true;
7337
Richard Smith8889a3d2013-06-13 06:26:32 +00007338 // FIXME: Builtin::BI__builtin_powi
7339 // FIXME: Builtin::BI__builtin_powif
7340 // FIXME: Builtin::BI__builtin_powil
7341
Mike Stump11289f42009-09-09 15:08:12 +00007342 case Builtin::BI__builtin_copysign:
7343 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007344 case Builtin::BI__builtin_copysignl: {
7345 APFloat RHS(0.);
7346 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7347 !EvaluateFloat(E->getArg(1), RHS, Info))
7348 return false;
7349 Result.copySign(RHS);
7350 return true;
7351 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007352 }
7353}
7354
John McCallb1fb0d32010-05-07 22:08:54 +00007355bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007356 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7357 ComplexValue CV;
7358 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7359 return false;
7360 Result = CV.FloatReal;
7361 return true;
7362 }
7363
7364 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007365}
7366
7367bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007368 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7369 ComplexValue CV;
7370 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7371 return false;
7372 Result = CV.FloatImag;
7373 return true;
7374 }
7375
Richard Smith4a678122011-10-24 18:44:57 +00007376 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007377 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7378 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007379 return true;
7380}
7381
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007382bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007383 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007384 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007385 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007386 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007387 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007388 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7389 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007390 Result.changeSign();
7391 return true;
7392 }
7393}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007394
Eli Friedman24c01542008-08-22 00:06:13 +00007395bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007396 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7397 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007398
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007399 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007400 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7401 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007402 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007403 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7404 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007405}
7406
7407bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7408 Result = E->getValue();
7409 return true;
7410}
7411
Peter Collingbournee9200682011-05-13 03:29:01 +00007412bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7413 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007414
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007415 switch (E->getCastKind()) {
7416 default:
Richard Smith11562c52011-10-28 17:51:58 +00007417 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007418
7419 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007420 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007421 return EvaluateInteger(SubExpr, IntResult, Info) &&
7422 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7423 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007424 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007425
7426 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007427 if (!Visit(SubExpr))
7428 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007429 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7430 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007431 }
John McCalld7646252010-11-14 08:17:51 +00007432
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007433 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007434 ComplexValue V;
7435 if (!EvaluateComplex(SubExpr, V, Info))
7436 return false;
7437 Result = V.getComplexFloatReal();
7438 return true;
7439 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007440 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007441}
7442
Eli Friedman24c01542008-08-22 00:06:13 +00007443//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007444// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007445//===----------------------------------------------------------------------===//
7446
7447namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007448class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007449 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007450 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007451
Anders Carlsson537969c2008-11-16 20:27:53 +00007452public:
John McCall93d91dc2010-05-07 17:22:02 +00007453 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007454 : ExprEvaluatorBaseTy(info), Result(Result) {}
7455
Richard Smith2e312c82012-03-03 22:46:17 +00007456 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007457 Result.setFrom(V);
7458 return true;
7459 }
Mike Stump11289f42009-09-09 15:08:12 +00007460
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007461 bool ZeroInitialization(const Expr *E);
7462
Anders Carlsson537969c2008-11-16 20:27:53 +00007463 //===--------------------------------------------------------------------===//
7464 // Visitor Methods
7465 //===--------------------------------------------------------------------===//
7466
Peter Collingbournee9200682011-05-13 03:29:01 +00007467 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007468 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007469 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007470 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007471 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007472};
7473} // end anonymous namespace
7474
John McCall93d91dc2010-05-07 17:22:02 +00007475static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7476 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007477 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007478 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007479}
7480
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007481bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007482 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007483 if (ElemTy->isRealFloatingType()) {
7484 Result.makeComplexFloat();
7485 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7486 Result.FloatReal = Zero;
7487 Result.FloatImag = Zero;
7488 } else {
7489 Result.makeComplexInt();
7490 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7491 Result.IntReal = Zero;
7492 Result.IntImag = Zero;
7493 }
7494 return true;
7495}
7496
Peter Collingbournee9200682011-05-13 03:29:01 +00007497bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7498 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007499
7500 if (SubExpr->getType()->isRealFloatingType()) {
7501 Result.makeComplexFloat();
7502 APFloat &Imag = Result.FloatImag;
7503 if (!EvaluateFloat(SubExpr, Imag, Info))
7504 return false;
7505
7506 Result.FloatReal = APFloat(Imag.getSemantics());
7507 return true;
7508 } else {
7509 assert(SubExpr->getType()->isIntegerType() &&
7510 "Unexpected imaginary literal.");
7511
7512 Result.makeComplexInt();
7513 APSInt &Imag = Result.IntImag;
7514 if (!EvaluateInteger(SubExpr, Imag, Info))
7515 return false;
7516
7517 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7518 return true;
7519 }
7520}
7521
Peter Collingbournee9200682011-05-13 03:29:01 +00007522bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007523
John McCallfcef3cf2010-12-14 17:51:41 +00007524 switch (E->getCastKind()) {
7525 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007526 case CK_BaseToDerived:
7527 case CK_DerivedToBase:
7528 case CK_UncheckedDerivedToBase:
7529 case CK_Dynamic:
7530 case CK_ToUnion:
7531 case CK_ArrayToPointerDecay:
7532 case CK_FunctionToPointerDecay:
7533 case CK_NullToPointer:
7534 case CK_NullToMemberPointer:
7535 case CK_BaseToDerivedMemberPointer:
7536 case CK_DerivedToBaseMemberPointer:
7537 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007538 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007539 case CK_ConstructorConversion:
7540 case CK_IntegralToPointer:
7541 case CK_PointerToIntegral:
7542 case CK_PointerToBoolean:
7543 case CK_ToVoid:
7544 case CK_VectorSplat:
7545 case CK_IntegralCast:
7546 case CK_IntegralToBoolean:
7547 case CK_IntegralToFloating:
7548 case CK_FloatingToIntegral:
7549 case CK_FloatingToBoolean:
7550 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007551 case CK_CPointerToObjCPointerCast:
7552 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007553 case CK_AnyPointerToBlockPointerCast:
7554 case CK_ObjCObjectLValueCast:
7555 case CK_FloatingComplexToReal:
7556 case CK_FloatingComplexToBoolean:
7557 case CK_IntegralComplexToReal:
7558 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007559 case CK_ARCProduceObject:
7560 case CK_ARCConsumeObject:
7561 case CK_ARCReclaimReturnedObject:
7562 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007563 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007564 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007565 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007566 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007567 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007568
John McCallfcef3cf2010-12-14 17:51:41 +00007569 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007570 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007571 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007572 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007573
7574 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007575 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007576 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007577 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007578
7579 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007580 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007581 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007582 return false;
7583
John McCallfcef3cf2010-12-14 17:51:41 +00007584 Result.makeComplexFloat();
7585 Result.FloatImag = APFloat(Real.getSemantics());
7586 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007587 }
7588
John McCallfcef3cf2010-12-14 17:51:41 +00007589 case CK_FloatingComplexCast: {
7590 if (!Visit(E->getSubExpr()))
7591 return false;
7592
7593 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7594 QualType From
7595 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7596
Richard Smith357362d2011-12-13 06:39:58 +00007597 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7598 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007599 }
7600
7601 case CK_FloatingComplexToIntegralComplex: {
7602 if (!Visit(E->getSubExpr()))
7603 return false;
7604
7605 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7606 QualType From
7607 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7608 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007609 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7610 To, Result.IntReal) &&
7611 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7612 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007613 }
7614
7615 case CK_IntegralRealToComplex: {
7616 APSInt &Real = Result.IntReal;
7617 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7618 return false;
7619
7620 Result.makeComplexInt();
7621 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7622 return true;
7623 }
7624
7625 case CK_IntegralComplexCast: {
7626 if (!Visit(E->getSubExpr()))
7627 return false;
7628
7629 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7630 QualType From
7631 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7632
Richard Smith911e1422012-01-30 22:27:01 +00007633 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7634 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007635 return true;
7636 }
7637
7638 case CK_IntegralComplexToFloatingComplex: {
7639 if (!Visit(E->getSubExpr()))
7640 return false;
7641
Ted Kremenek28831752012-08-23 20:46:57 +00007642 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007643 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007644 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007645 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007646 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7647 To, Result.FloatReal) &&
7648 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7649 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007650 }
7651 }
7652
7653 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007654}
7655
John McCall93d91dc2010-05-07 17:22:02 +00007656bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007657 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007658 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7659
Richard Smith253c2a32012-01-27 01:14:48 +00007660 bool LHSOK = Visit(E->getLHS());
7661 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007662 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007663
John McCall93d91dc2010-05-07 17:22:02 +00007664 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007665 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007666 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007667
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007668 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7669 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007670 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007671 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007672 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007673 if (Result.isComplexFloat()) {
7674 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7675 APFloat::rmNearestTiesToEven);
7676 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7677 APFloat::rmNearestTiesToEven);
7678 } else {
7679 Result.getComplexIntReal() += RHS.getComplexIntReal();
7680 Result.getComplexIntImag() += RHS.getComplexIntImag();
7681 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007682 break;
John McCalle3027922010-08-25 11:45:40 +00007683 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007684 if (Result.isComplexFloat()) {
7685 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7686 APFloat::rmNearestTiesToEven);
7687 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7688 APFloat::rmNearestTiesToEven);
7689 } else {
7690 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7691 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7692 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007693 break;
John McCalle3027922010-08-25 11:45:40 +00007694 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007695 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007696 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007697 APFloat &LHS_r = LHS.getComplexFloatReal();
7698 APFloat &LHS_i = LHS.getComplexFloatImag();
7699 APFloat &RHS_r = RHS.getComplexFloatReal();
7700 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007701
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007702 APFloat Tmp = LHS_r;
7703 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7704 Result.getComplexFloatReal() = Tmp;
7705 Tmp = LHS_i;
7706 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7707 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7708
7709 Tmp = LHS_r;
7710 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7711 Result.getComplexFloatImag() = Tmp;
7712 Tmp = LHS_i;
7713 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7714 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7715 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007716 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007717 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007718 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7719 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007720 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007721 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7722 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7723 }
7724 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007725 case BO_Div:
7726 if (Result.isComplexFloat()) {
7727 ComplexValue LHS = Result;
7728 APFloat &LHS_r = LHS.getComplexFloatReal();
7729 APFloat &LHS_i = LHS.getComplexFloatImag();
7730 APFloat &RHS_r = RHS.getComplexFloatReal();
7731 APFloat &RHS_i = RHS.getComplexFloatImag();
7732 APFloat &Res_r = Result.getComplexFloatReal();
7733 APFloat &Res_i = Result.getComplexFloatImag();
7734
7735 APFloat Den = RHS_r;
7736 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7737 APFloat Tmp = RHS_i;
7738 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7739 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7740
7741 Res_r = LHS_r;
7742 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7743 Tmp = LHS_i;
7744 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7745 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7746 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7747
7748 Res_i = LHS_i;
7749 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7750 Tmp = LHS_r;
7751 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7752 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7753 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7754 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007755 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7756 return Error(E, diag::note_expr_divide_by_zero);
7757
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007758 ComplexValue LHS = Result;
7759 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7760 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7761 Result.getComplexIntReal() =
7762 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7763 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7764 Result.getComplexIntImag() =
7765 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7766 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7767 }
7768 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007769 }
7770
John McCall93d91dc2010-05-07 17:22:02 +00007771 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007772}
7773
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007774bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7775 // Get the operand value into 'Result'.
7776 if (!Visit(E->getSubExpr()))
7777 return false;
7778
7779 switch (E->getOpcode()) {
7780 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007781 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007782 case UO_Extension:
7783 return true;
7784 case UO_Plus:
7785 // The result is always just the subexpr.
7786 return true;
7787 case UO_Minus:
7788 if (Result.isComplexFloat()) {
7789 Result.getComplexFloatReal().changeSign();
7790 Result.getComplexFloatImag().changeSign();
7791 }
7792 else {
7793 Result.getComplexIntReal() = -Result.getComplexIntReal();
7794 Result.getComplexIntImag() = -Result.getComplexIntImag();
7795 }
7796 return true;
7797 case UO_Not:
7798 if (Result.isComplexFloat())
7799 Result.getComplexFloatImag().changeSign();
7800 else
7801 Result.getComplexIntImag() = -Result.getComplexIntImag();
7802 return true;
7803 }
7804}
7805
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007806bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7807 if (E->getNumInits() == 2) {
7808 if (E->getType()->isComplexType()) {
7809 Result.makeComplexFloat();
7810 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7811 return false;
7812 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7813 return false;
7814 } else {
7815 Result.makeComplexInt();
7816 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7817 return false;
7818 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7819 return false;
7820 }
7821 return true;
7822 }
7823 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7824}
7825
Anders Carlsson537969c2008-11-16 20:27:53 +00007826//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007827// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7828// implicit conversion.
7829//===----------------------------------------------------------------------===//
7830
7831namespace {
7832class AtomicExprEvaluator :
7833 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7834 APValue &Result;
7835public:
7836 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7837 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7838
7839 bool Success(const APValue &V, const Expr *E) {
7840 Result = V;
7841 return true;
7842 }
7843
7844 bool ZeroInitialization(const Expr *E) {
7845 ImplicitValueInitExpr VIE(
7846 E->getType()->castAs<AtomicType>()->getValueType());
7847 return Evaluate(Result, Info, &VIE);
7848 }
7849
7850 bool VisitCastExpr(const CastExpr *E) {
7851 switch (E->getCastKind()) {
7852 default:
7853 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7854 case CK_NonAtomicToAtomic:
7855 return Evaluate(Result, Info, E->getSubExpr());
7856 }
7857 }
7858};
7859} // end anonymous namespace
7860
7861static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7862 assert(E->isRValue() && E->getType()->isAtomicType());
7863 return AtomicExprEvaluator(Info, Result).Visit(E);
7864}
7865
7866//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007867// Void expression evaluation, primarily for a cast to void on the LHS of a
7868// comma operator
7869//===----------------------------------------------------------------------===//
7870
7871namespace {
7872class VoidExprEvaluator
7873 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7874public:
7875 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7876
Richard Smith2e312c82012-03-03 22:46:17 +00007877 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007878
7879 bool VisitCastExpr(const CastExpr *E) {
7880 switch (E->getCastKind()) {
7881 default:
7882 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7883 case CK_ToVoid:
7884 VisitIgnoredValue(E->getSubExpr());
7885 return true;
7886 }
7887 }
7888};
7889} // end anonymous namespace
7890
7891static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7892 assert(E->isRValue() && E->getType()->isVoidType());
7893 return VoidExprEvaluator(Info).Visit(E);
7894}
7895
7896//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007897// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007898//===----------------------------------------------------------------------===//
7899
Richard Smith2e312c82012-03-03 22:46:17 +00007900static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007901 // In C, function designators are not lvalues, but we evaluate them as if they
7902 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007903 QualType T = E->getType();
7904 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007905 LValue LV;
7906 if (!EvaluateLValue(E, LV, Info))
7907 return false;
7908 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007909 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007910 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007911 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007912 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007913 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007914 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007915 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007916 LValue LV;
7917 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007918 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007919 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007920 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007921 llvm::APFloat F(0.0);
7922 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007923 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007924 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007925 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007926 ComplexValue C;
7927 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007928 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007929 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007930 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007931 MemberPtr P;
7932 if (!EvaluateMemberPointer(E, P, Info))
7933 return false;
7934 P.moveInto(Result);
7935 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007936 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007937 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007938 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007939 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7940 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007941 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007942 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007943 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007944 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007945 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007946 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7947 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007948 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007949 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007950 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007951 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007952 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007953 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007954 if (!EvaluateVoid(E, Info))
7955 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007956 } else if (T->isAtomicType()) {
7957 if (!EvaluateAtomic(E, Result, Info))
7958 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007959 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007960 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007961 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007962 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007963 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007964 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007965 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007966
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007967 return true;
7968}
7969
Richard Smithb228a862012-02-15 02:18:13 +00007970/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7971/// cases, the in-place evaluation is essential, since later initializers for
7972/// an object can indirectly refer to subobjects which were initialized earlier.
7973static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007974 const Expr *E, bool AllowNonLiteralTypes) {
7975 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007976 return false;
7977
7978 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007979 // Evaluate arrays and record types in-place, so that later initializers can
7980 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007981 if (E->getType()->isArrayType())
7982 return EvaluateArray(E, This, Result, Info);
7983 else if (E->getType()->isRecordType())
7984 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007985 }
7986
7987 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007988 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007989}
7990
Richard Smithf57d8cb2011-12-09 22:58:01 +00007991/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7992/// lvalue-to-rvalue cast if it is an lvalue.
7993static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007994 if (!CheckLiteralType(Info, E))
7995 return false;
7996
Richard Smith2e312c82012-03-03 22:46:17 +00007997 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007998 return false;
7999
8000 if (E->isGLValue()) {
8001 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008002 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008003 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008004 return false;
8005 }
8006
Richard Smith2e312c82012-03-03 22:46:17 +00008007 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008008 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008009}
Richard Smith11562c52011-10-28 17:51:58 +00008010
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008011static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8012 const ASTContext &Ctx, bool &IsConst) {
8013 // Fast-path evaluations of integer literals, since we sometimes see files
8014 // containing vast quantities of these.
8015 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8016 Result.Val = APValue(APSInt(L->getValue(),
8017 L->getType()->isUnsignedIntegerType()));
8018 IsConst = true;
8019 return true;
8020 }
8021
8022 // FIXME: Evaluating values of large array and record types can cause
8023 // performance problems. Only do so in C++11 for now.
8024 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8025 Exp->getType()->isRecordType()) &&
8026 !Ctx.getLangOpts().CPlusPlus11) {
8027 IsConst = false;
8028 return true;
8029 }
8030 return false;
8031}
8032
8033
Richard Smith7b553f12011-10-29 00:50:52 +00008034/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008035/// any crazy technique (that has nothing to do with language standards) that
8036/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008037/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8038/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008039bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008040 bool IsConst;
8041 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8042 return IsConst;
8043
Richard Smith6d4c6582013-11-05 22:18:15 +00008044 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008045 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008046}
8047
Jay Foad39c79802011-01-12 09:06:06 +00008048bool Expr::EvaluateAsBooleanCondition(bool &Result,
8049 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008050 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008051 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008052 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008053}
8054
Richard Smith5fab0c92011-12-28 19:48:30 +00008055bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8056 SideEffectsKind AllowSideEffects) const {
8057 if (!getType()->isIntegralOrEnumerationType())
8058 return false;
8059
Richard Smith11562c52011-10-28 17:51:58 +00008060 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008061 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8062 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008063 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008064
Richard Smith11562c52011-10-28 17:51:58 +00008065 Result = ExprResult.Val.getInt();
8066 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008067}
8068
Jay Foad39c79802011-01-12 09:06:06 +00008069bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008070 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008071
John McCall45d55e42010-05-07 21:00:08 +00008072 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008073 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8074 !CheckLValueConstantExpression(Info, getExprLoc(),
8075 Ctx.getLValueReferenceType(getType()), LV))
8076 return false;
8077
Richard Smith2e312c82012-03-03 22:46:17 +00008078 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008079 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008080}
8081
Richard Smithd0b4dd62011-12-19 06:19:21 +00008082bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8083 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008084 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008085 // FIXME: Evaluating initializers for large array and record types can cause
8086 // performance problems. Only do so in C++11 for now.
8087 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008088 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008089 return false;
8090
Richard Smithd0b4dd62011-12-19 06:19:21 +00008091 Expr::EvalStatus EStatus;
8092 EStatus.Diag = &Notes;
8093
Richard Smith6d4c6582013-11-05 22:18:15 +00008094 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008095 InitInfo.setEvaluatingDecl(VD, Value);
8096
8097 LValue LVal;
8098 LVal.set(VD);
8099
Richard Smithfddd3842011-12-30 21:15:51 +00008100 // C++11 [basic.start.init]p2:
8101 // Variables with static storage duration or thread storage duration shall be
8102 // zero-initialized before any other initialization takes place.
8103 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008104 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008105 !VD->getType()->isReferenceType()) {
8106 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008107 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008108 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008109 return false;
8110 }
8111
Richard Smith7525ff62013-05-09 07:14:00 +00008112 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8113 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008114 EStatus.HasSideEffects)
8115 return false;
8116
8117 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8118 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008119}
8120
Richard Smith7b553f12011-10-29 00:50:52 +00008121/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8122/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008123bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008124 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008125 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008126}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008127
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008128APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008129 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008130 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008131 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008132 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008133 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008134 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008135 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008136
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008137 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008138}
John McCall864e3962010-05-07 05:32:02 +00008139
Richard Smithe9ff7702013-11-05 22:23:30 +00008140void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008141 bool IsConst;
8142 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008143 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008144 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008145 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8146 }
8147}
8148
Richard Smithe6c01442013-06-05 00:46:14 +00008149bool Expr::EvalResult::isGlobalLValue() const {
8150 assert(Val.isLValue());
8151 return IsGlobalLValue(Val.getLValueBase());
8152}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008153
8154
John McCall864e3962010-05-07 05:32:02 +00008155/// isIntegerConstantExpr - this recursive routine will test if an expression is
8156/// an integer constant expression.
8157
8158/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8159/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008160
8161// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008162// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8163// and a (possibly null) SourceLocation indicating the location of the problem.
8164//
John McCall864e3962010-05-07 05:32:02 +00008165// Note that to reduce code duplication, this helper does no evaluation
8166// itself; the caller checks whether the expression is evaluatable, and
8167// in the rare cases where CheckICE actually cares about the evaluated
8168// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008169
Dan Gohman28ade552010-07-26 21:25:24 +00008170namespace {
8171
Richard Smith9e575da2012-12-28 13:25:52 +00008172enum ICEKind {
8173 /// This expression is an ICE.
8174 IK_ICE,
8175 /// This expression is not an ICE, but if it isn't evaluated, it's
8176 /// a legal subexpression for an ICE. This return value is used to handle
8177 /// the comma operator in C99 mode, and non-constant subexpressions.
8178 IK_ICEIfUnevaluated,
8179 /// This expression is not an ICE, and is not a legal subexpression for one.
8180 IK_NotICE
8181};
8182
John McCall864e3962010-05-07 05:32:02 +00008183struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008184 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008185 SourceLocation Loc;
8186
Richard Smith9e575da2012-12-28 13:25:52 +00008187 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008188};
8189
Dan Gohman28ade552010-07-26 21:25:24 +00008190}
8191
Richard Smith9e575da2012-12-28 13:25:52 +00008192static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8193
8194static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008195
Craig Toppera31a8822013-08-22 07:09:37 +00008196static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008197 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008198 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008199 !EVResult.Val.isInt())
8200 return ICEDiag(IK_NotICE, E->getLocStart());
8201
John McCall864e3962010-05-07 05:32:02 +00008202 return NoDiag();
8203}
8204
Craig Toppera31a8822013-08-22 07:09:37 +00008205static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008206 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008207 if (!E->getType()->isIntegralOrEnumerationType())
8208 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008209
8210 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008211#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008212#define STMT(Node, Base) case Expr::Node##Class:
8213#define EXPR(Node, Base)
8214#include "clang/AST/StmtNodes.inc"
8215 case Expr::PredefinedExprClass:
8216 case Expr::FloatingLiteralClass:
8217 case Expr::ImaginaryLiteralClass:
8218 case Expr::StringLiteralClass:
8219 case Expr::ArraySubscriptExprClass:
8220 case Expr::MemberExprClass:
8221 case Expr::CompoundAssignOperatorClass:
8222 case Expr::CompoundLiteralExprClass:
8223 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008224 case Expr::DesignatedInitExprClass:
8225 case Expr::ImplicitValueInitExprClass:
8226 case Expr::ParenListExprClass:
8227 case Expr::VAArgExprClass:
8228 case Expr::AddrLabelExprClass:
8229 case Expr::StmtExprClass:
8230 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008231 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008232 case Expr::CXXDynamicCastExprClass:
8233 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008234 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008235 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008236 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008237 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008238 case Expr::CXXThisExprClass:
8239 case Expr::CXXThrowExprClass:
8240 case Expr::CXXNewExprClass:
8241 case Expr::CXXDeleteExprClass:
8242 case Expr::CXXPseudoDestructorExprClass:
8243 case Expr::UnresolvedLookupExprClass:
8244 case Expr::DependentScopeDeclRefExprClass:
8245 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008246 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008247 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008248 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008249 case Expr::CXXTemporaryObjectExprClass:
8250 case Expr::CXXUnresolvedConstructExprClass:
8251 case Expr::CXXDependentScopeMemberExprClass:
8252 case Expr::UnresolvedMemberExprClass:
8253 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008254 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008255 case Expr::ObjCArrayLiteralClass:
8256 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008257 case Expr::ObjCEncodeExprClass:
8258 case Expr::ObjCMessageExprClass:
8259 case Expr::ObjCSelectorExprClass:
8260 case Expr::ObjCProtocolExprClass:
8261 case Expr::ObjCIvarRefExprClass:
8262 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008263 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008264 case Expr::ObjCIsaExprClass:
8265 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008266 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008267 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008268 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008269 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008270 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008271 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008272 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008273 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008274 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008275 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008276 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008277 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00008278 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008279 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008280 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008281
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008282 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008283 case Expr::GNUNullExprClass:
8284 // GCC considers the GNU __null value to be an integral constant expression.
8285 return NoDiag();
8286
John McCall7c454bb2011-07-15 05:09:51 +00008287 case Expr::SubstNonTypeTemplateParmExprClass:
8288 return
8289 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8290
John McCall864e3962010-05-07 05:32:02 +00008291 case Expr::ParenExprClass:
8292 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008293 case Expr::GenericSelectionExprClass:
8294 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008295 case Expr::IntegerLiteralClass:
8296 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008297 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008298 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008299 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008300 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008301 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008302 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008303 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008304 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008305 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008306 return NoDiag();
8307 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008308 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008309 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8310 // constant expressions, but they can never be ICEs because an ICE cannot
8311 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008312 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008313 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008314 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008315 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008316 }
Richard Smith6365c912012-02-24 22:12:32 +00008317 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008318 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8319 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008320 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008321 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008322 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008323 // Parameter variables are never constants. Without this check,
8324 // getAnyInitializer() can find a default argument, which leads
8325 // to chaos.
8326 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008327 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008328
8329 // C++ 7.1.5.1p2
8330 // A variable of non-volatile const-qualified integral or enumeration
8331 // type initialized by an ICE can be used in ICEs.
8332 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008333 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008334 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008335
Richard Smithd0b4dd62011-12-19 06:19:21 +00008336 const VarDecl *VD;
8337 // Look for a declaration of this variable that has an initializer, and
8338 // check whether it is an ICE.
8339 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8340 return NoDiag();
8341 else
Richard Smith9e575da2012-12-28 13:25:52 +00008342 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008343 }
8344 }
Richard Smith9e575da2012-12-28 13:25:52 +00008345 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008346 }
John McCall864e3962010-05-07 05:32:02 +00008347 case Expr::UnaryOperatorClass: {
8348 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8349 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008350 case UO_PostInc:
8351 case UO_PostDec:
8352 case UO_PreInc:
8353 case UO_PreDec:
8354 case UO_AddrOf:
8355 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008356 // C99 6.6/3 allows increment and decrement within unevaluated
8357 // subexpressions of constant expressions, but they can never be ICEs
8358 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008359 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008360 case UO_Extension:
8361 case UO_LNot:
8362 case UO_Plus:
8363 case UO_Minus:
8364 case UO_Not:
8365 case UO_Real:
8366 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008367 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008368 }
Richard Smith9e575da2012-12-28 13:25:52 +00008369
John McCall864e3962010-05-07 05:32:02 +00008370 // OffsetOf falls through here.
8371 }
8372 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008373 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8374 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8375 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8376 // compliance: we should warn earlier for offsetof expressions with
8377 // array subscripts that aren't ICEs, and if the array subscripts
8378 // are ICEs, the value of the offsetof must be an integer constant.
8379 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008380 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008381 case Expr::UnaryExprOrTypeTraitExprClass: {
8382 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8383 if ((Exp->getKind() == UETT_SizeOf) &&
8384 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008385 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008386 return NoDiag();
8387 }
8388 case Expr::BinaryOperatorClass: {
8389 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8390 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008391 case BO_PtrMemD:
8392 case BO_PtrMemI:
8393 case BO_Assign:
8394 case BO_MulAssign:
8395 case BO_DivAssign:
8396 case BO_RemAssign:
8397 case BO_AddAssign:
8398 case BO_SubAssign:
8399 case BO_ShlAssign:
8400 case BO_ShrAssign:
8401 case BO_AndAssign:
8402 case BO_XorAssign:
8403 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008404 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8405 // constant expressions, but they can never be ICEs because an ICE cannot
8406 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008407 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008408
John McCalle3027922010-08-25 11:45:40 +00008409 case BO_Mul:
8410 case BO_Div:
8411 case BO_Rem:
8412 case BO_Add:
8413 case BO_Sub:
8414 case BO_Shl:
8415 case BO_Shr:
8416 case BO_LT:
8417 case BO_GT:
8418 case BO_LE:
8419 case BO_GE:
8420 case BO_EQ:
8421 case BO_NE:
8422 case BO_And:
8423 case BO_Xor:
8424 case BO_Or:
8425 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008426 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8427 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008428 if (Exp->getOpcode() == BO_Div ||
8429 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008430 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008431 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008432 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008433 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008434 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008435 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008436 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008437 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008438 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008439 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008440 }
8441 }
8442 }
John McCalle3027922010-08-25 11:45:40 +00008443 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008444 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008445 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8446 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008447 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8448 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008449 } else {
8450 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008451 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008452 }
8453 }
Richard Smith9e575da2012-12-28 13:25:52 +00008454 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008455 }
John McCalle3027922010-08-25 11:45:40 +00008456 case BO_LAnd:
8457 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008458 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8459 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008460 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008461 // Rare case where the RHS has a comma "side-effect"; we need
8462 // to actually check the condition to see whether the side
8463 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008464 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008465 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008466 return RHSResult;
8467 return NoDiag();
8468 }
8469
Richard Smith9e575da2012-12-28 13:25:52 +00008470 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008471 }
8472 }
8473 }
8474 case Expr::ImplicitCastExprClass:
8475 case Expr::CStyleCastExprClass:
8476 case Expr::CXXFunctionalCastExprClass:
8477 case Expr::CXXStaticCastExprClass:
8478 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008479 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008480 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008481 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008482 if (isa<ExplicitCastExpr>(E)) {
8483 if (const FloatingLiteral *FL
8484 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8485 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8486 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8487 APSInt IgnoredVal(DestWidth, !DestSigned);
8488 bool Ignored;
8489 // If the value does not fit in the destination type, the behavior is
8490 // undefined, so we are not required to treat it as a constant
8491 // expression.
8492 if (FL->getValue().convertToInteger(IgnoredVal,
8493 llvm::APFloat::rmTowardZero,
8494 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008495 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008496 return NoDiag();
8497 }
8498 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008499 switch (cast<CastExpr>(E)->getCastKind()) {
8500 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008501 case CK_AtomicToNonAtomic:
8502 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008503 case CK_NoOp:
8504 case CK_IntegralToBoolean:
8505 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008506 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008507 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008508 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008509 }
John McCall864e3962010-05-07 05:32:02 +00008510 }
John McCallc07a0c72011-02-17 10:25:35 +00008511 case Expr::BinaryConditionalOperatorClass: {
8512 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8513 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008514 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008515 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008516 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8517 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8518 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008519 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008520 return FalseResult;
8521 }
John McCall864e3962010-05-07 05:32:02 +00008522 case Expr::ConditionalOperatorClass: {
8523 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8524 // If the condition (ignoring parens) is a __builtin_constant_p call,
8525 // then only the true side is actually considered in an integer constant
8526 // expression, and it is fully evaluated. This is an important GNU
8527 // extension. See GCC PR38377 for discussion.
8528 if (const CallExpr *CallCE
8529 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008530 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8531 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008532 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008533 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008534 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008535
Richard Smithf57d8cb2011-12-09 22:58:01 +00008536 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8537 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008538
Richard Smith9e575da2012-12-28 13:25:52 +00008539 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008540 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008541 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008542 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008543 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008544 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008545 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008546 return NoDiag();
8547 // Rare case where the diagnostics depend on which side is evaluated
8548 // Note that if we get here, CondResult is 0, and at least one of
8549 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008550 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008551 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008552 return TrueResult;
8553 }
8554 case Expr::CXXDefaultArgExprClass:
8555 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008556 case Expr::CXXDefaultInitExprClass:
8557 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008558 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008559 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008560 }
8561 }
8562
David Blaikiee4d798f2012-01-20 21:50:17 +00008563 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008564}
8565
Richard Smithf57d8cb2011-12-09 22:58:01 +00008566/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008567static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008568 const Expr *E,
8569 llvm::APSInt *Value,
8570 SourceLocation *Loc) {
8571 if (!E->getType()->isIntegralOrEnumerationType()) {
8572 if (Loc) *Loc = E->getExprLoc();
8573 return false;
8574 }
8575
Richard Smith66e05fe2012-01-18 05:21:49 +00008576 APValue Result;
8577 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008578 return false;
8579
Richard Smith66e05fe2012-01-18 05:21:49 +00008580 assert(Result.isInt() && "pointer cast to int is not an ICE");
8581 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008582 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008583}
8584
Craig Toppera31a8822013-08-22 07:09:37 +00008585bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8586 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008587 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008588 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8589
Richard Smith9e575da2012-12-28 13:25:52 +00008590 ICEDiag D = CheckICE(this, Ctx);
8591 if (D.Kind != IK_ICE) {
8592 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008593 return false;
8594 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008595 return true;
8596}
8597
Craig Toppera31a8822013-08-22 07:09:37 +00008598bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008599 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008600 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008601 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8602
8603 if (!isIntegerConstantExpr(Ctx, Loc))
8604 return false;
8605 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008606 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008607 return true;
8608}
Richard Smith66e05fe2012-01-18 05:21:49 +00008609
Craig Toppera31a8822013-08-22 07:09:37 +00008610bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008611 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008612}
8613
Craig Toppera31a8822013-08-22 07:09:37 +00008614bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008615 SourceLocation *Loc) const {
8616 // We support this checking in C++98 mode in order to diagnose compatibility
8617 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008618 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008619
Richard Smith98a0a492012-02-14 21:38:30 +00008620 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008621 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008622 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008623 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008624 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008625
8626 APValue Scratch;
8627 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8628
8629 if (!Diags.empty()) {
8630 IsConstExpr = false;
8631 if (Loc) *Loc = Diags[0].first;
8632 } else if (!IsConstExpr) {
8633 // FIXME: This shouldn't happen.
8634 if (Loc) *Loc = getExprLoc();
8635 }
8636
8637 return IsConstExpr;
8638}
Richard Smith253c2a32012-01-27 01:14:48 +00008639
8640bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008641 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008642 PartialDiagnosticAt> &Diags) {
8643 // FIXME: It would be useful to check constexpr function templates, but at the
8644 // moment the constant expression evaluator cannot cope with the non-rigorous
8645 // ASTs which we build for dependent expressions.
8646 if (FD->isDependentContext())
8647 return true;
8648
8649 Expr::EvalStatus Status;
8650 Status.Diag = &Diags;
8651
Richard Smith6d4c6582013-11-05 22:18:15 +00008652 EvalInfo Info(FD->getASTContext(), Status,
8653 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008654
8655 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8656 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8657
Richard Smith7525ff62013-05-09 07:14:00 +00008658 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008659 // is a temporary being used as the 'this' pointer.
8660 LValue This;
8661 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008662 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008663
Richard Smith253c2a32012-01-27 01:14:48 +00008664 ArrayRef<const Expr*> Args;
8665
8666 SourceLocation Loc = FD->getLocation();
8667
Richard Smith2e312c82012-03-03 22:46:17 +00008668 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008669 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8670 // Evaluate the call as a constant initializer, to allow the construction
8671 // of objects of non-literal types.
8672 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008673 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008674 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008675 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8676 Args, FD->getBody(), Info, Scratch);
8677
8678 return Diags.empty();
8679}