blob: 01267143e517a5bf8e8be289b5f3fe87d0c87e10 [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) {
567 case EM_ConstantExpression:
568 case EM_PotentialConstantExpression:
569 case EM_EvaluateForOverflow:
570 HasActiveDiagnostic = false;
571 return OptionalDiagnostic();
572
573 case EM_ConstantFold:
574 case EM_IgnoreSideEffects:
575 break;
576 }
577 }
578
Richard Smithf6f003a2011-12-16 19:06:07 +0000579 unsigned CallStackNotes = CallStackDepth - 1;
580 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
581 if (Limit)
582 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000583 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000584 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000585
Richard Smith357362d2011-12-13 06:39:58 +0000586 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000587 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000588 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
589 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000590 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000591 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000592 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000593 }
Richard Smith357362d2011-12-13 06:39:58 +0000594 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000595 return OptionalDiagnostic();
596 }
597
Richard Smithce1ec5e2012-03-15 04:53:45 +0000598 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
599 = diag::note_invalid_subexpr_in_const_expr,
600 unsigned ExtraNotes = 0) {
601 if (EvalStatus.Diag)
602 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
603 HasActiveDiagnostic = false;
604 return OptionalDiagnostic();
605 }
606
Richard Smith92b1ce02011-12-12 09:28:41 +0000607 /// Diagnose that the evaluation does not produce a C++11 core constant
608 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000609 ///
610 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
611 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000612 template<typename LocArg>
613 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000614 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000615 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000616 // Don't override a previous diagnostic. Don't bother collecting
617 // diagnostics if we're evaluating for overflow.
618 if (!EvalStatus.Diag || !EvalStatus.Diag->empty() ||
619 EvalMode == EM_EvaluateForOverflow) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000620 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000621 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000622 }
Richard Smith357362d2011-12-13 06:39:58 +0000623 return Diag(Loc, DiagId, ExtraNotes);
624 }
625
626 /// Add a note to a prior diagnostic.
627 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
628 if (!HasActiveDiagnostic)
629 return OptionalDiagnostic();
630 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000631 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000632
633 /// Add a stack of notes to a prior diagnostic.
634 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
635 if (HasActiveDiagnostic) {
636 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
637 Diags.begin(), Diags.end());
638 }
639 }
Richard Smith253c2a32012-01-27 01:14:48 +0000640
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 /// Should we continue evaluation after encountering a side-effect that we
642 /// couldn't model?
643 bool keepEvaluatingAfterSideEffect() {
644 switch (EvalMode) {
645 case EM_EvaluateForOverflow:
646 case EM_IgnoreSideEffects:
647 return true;
648
649 case EM_PotentialConstantExpression:
650 case EM_ConstantExpression:
651 case EM_ConstantFold:
652 return false;
653 }
654 }
655
656 /// Note that we have had a side-effect, and determine whether we should
657 /// keep evaluating.
658 bool noteSideEffect() {
659 EvalStatus.HasSideEffects = true;
660 return keepEvaluatingAfterSideEffect();
661 }
662
Richard Smith253c2a32012-01-27 01:14:48 +0000663 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000665 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 if (!StepsLeft)
667 return false;
668
669 switch (EvalMode) {
670 case EM_PotentialConstantExpression:
671 case EM_EvaluateForOverflow:
672 return true;
673
674 case EM_ConstantExpression:
675 case EM_ConstantFold:
676 case EM_IgnoreSideEffects:
677 return false;
678 }
Richard Smith253c2a32012-01-27 01:14:48 +0000679 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000680 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000681
682 /// Object used to treat all foldable expressions as constant expressions.
683 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000684 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000685 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000686 bool HadNoPriorDiags;
687 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000688
Richard Smith6d4c6582013-11-05 22:18:15 +0000689 explicit FoldConstant(EvalInfo &Info, bool Enabled)
690 : Info(Info),
691 Enabled(Enabled),
692 HadNoPriorDiags(Info.EvalStatus.Diag &&
693 Info.EvalStatus.Diag->empty() &&
694 !Info.EvalStatus.HasSideEffects),
695 OldMode(Info.EvalMode) {
696 if (Enabled && Info.EvalMode == EvalInfo::EM_ConstantExpression)
697 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000698 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 void keepDiagnostics() { Enabled = false; }
700 ~FoldConstant() {
701 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000702 !Info.EvalStatus.HasSideEffects)
703 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000705 }
706 };
Richard Smith17100ba2012-02-16 02:46:34 +0000707
708 /// RAII object used to suppress diagnostics and side-effects from a
709 /// speculative evaluation.
710 class SpeculativeEvaluationRAII {
711 EvalInfo &Info;
712 Expr::EvalStatus Old;
713
714 public:
715 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000716 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000717 : Info(Info), Old(Info.EvalStatus) {
718 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000719 // If we're speculatively evaluating, we may have skipped over some
720 // evaluations and missed out a side effect.
721 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000722 }
723 ~SpeculativeEvaluationRAII() {
724 Info.EvalStatus = Old;
725 }
726 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000727
728 /// RAII object wrapping a full-expression or block scope, and handling
729 /// the ending of the lifetime of temporaries created within it.
730 template<bool IsFullExpression>
731 class ScopeRAII {
732 EvalInfo &Info;
733 unsigned OldStackSize;
734 public:
735 ScopeRAII(EvalInfo &Info)
736 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
737 ~ScopeRAII() {
738 // Body moved to a static method to encourage the compiler to inline away
739 // instances of this class.
740 cleanup(Info, OldStackSize);
741 }
742 private:
743 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
744 unsigned NewEnd = OldStackSize;
745 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
746 I != N; ++I) {
747 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
748 // Full-expression cleanup of a lifetime-extended temporary: nothing
749 // to do, just move this cleanup to the right place in the stack.
750 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
751 ++NewEnd;
752 } else {
753 // End the lifetime of the object.
754 Info.CleanupStack[I].endLifetime();
755 }
756 }
757 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
758 Info.CleanupStack.end());
759 }
760 };
761 typedef ScopeRAII<false> BlockScopeRAII;
762 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000763}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000764
Richard Smitha8105bc2012-01-06 16:39:00 +0000765bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
766 CheckSubobjectKind CSK) {
767 if (Invalid)
768 return false;
769 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000770 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000771 << CSK;
772 setInvalid();
773 return false;
774 }
775 return true;
776}
777
778void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
779 const Expr *E, uint64_t N) {
780 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000782 << static_cast<int>(N) << /*array*/ 0
783 << static_cast<unsigned>(MostDerivedArraySize);
784 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000786 << static_cast<int>(N) << /*non-array*/ 1;
787 setInvalid();
788}
789
Richard Smithf6f003a2011-12-16 19:06:07 +0000790CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
791 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000792 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000793 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000794 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000795 Info.CurrentCall = this;
796 ++Info.CallStackDepth;
797}
798
799CallStackFrame::~CallStackFrame() {
800 assert(Info.CurrentCall == this && "calls retired out of order");
801 --Info.CallStackDepth;
802 Info.CurrentCall = Caller;
803}
804
Richard Smith08d6a2c2013-07-24 07:11:57 +0000805APValue &CallStackFrame::createTemporary(const void *Key,
806 bool IsLifetimeExtended) {
807 APValue &Result = Temporaries[Key];
808 assert(Result.isUninit() && "temporary created multiple times");
809 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
810 return Result;
811}
812
Richard Smith84401042013-06-03 05:03:02 +0000813static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000814
815void EvalInfo::addCallStack(unsigned Limit) {
816 // Determine which calls to skip, if any.
817 unsigned ActiveCalls = CallStackDepth - 1;
818 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
819 if (Limit && Limit < ActiveCalls) {
820 SkipStart = Limit / 2 + Limit % 2;
821 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000822 }
823
Richard Smithf6f003a2011-12-16 19:06:07 +0000824 // Walk the call stack and add the diagnostics.
825 unsigned CallIdx = 0;
826 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
827 Frame = Frame->Caller, ++CallIdx) {
828 // Skip this call?
829 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
830 if (CallIdx == SkipStart) {
831 // Note that we're skipping calls.
832 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
833 << unsigned(ActiveCalls - Limit);
834 }
835 continue;
836 }
837
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000838 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000839 llvm::raw_svector_ostream Out(Buffer);
840 describeCall(Frame, Out);
841 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
842 }
843}
844
845namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000846 struct ComplexValue {
847 private:
848 bool IsInt;
849
850 public:
851 APSInt IntReal, IntImag;
852 APFloat FloatReal, FloatImag;
853
854 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
855
856 void makeComplexFloat() { IsInt = false; }
857 bool isComplexFloat() const { return !IsInt; }
858 APFloat &getComplexFloatReal() { return FloatReal; }
859 APFloat &getComplexFloatImag() { return FloatImag; }
860
861 void makeComplexInt() { IsInt = true; }
862 bool isComplexInt() const { return IsInt; }
863 APSInt &getComplexIntReal() { return IntReal; }
864 APSInt &getComplexIntImag() { return IntImag; }
865
Richard Smith2e312c82012-03-03 22:46:17 +0000866 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000867 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000868 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000869 else
Richard Smith2e312c82012-03-03 22:46:17 +0000870 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000871 }
Richard Smith2e312c82012-03-03 22:46:17 +0000872 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000873 assert(v.isComplexFloat() || v.isComplexInt());
874 if (v.isComplexFloat()) {
875 makeComplexFloat();
876 FloatReal = v.getComplexFloatReal();
877 FloatImag = v.getComplexFloatImag();
878 } else {
879 makeComplexInt();
880 IntReal = v.getComplexIntReal();
881 IntImag = v.getComplexIntImag();
882 }
883 }
John McCall93d91dc2010-05-07 17:22:02 +0000884 };
John McCall45d55e42010-05-07 21:00:08 +0000885
886 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000887 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000888 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000889 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000890 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000891
Richard Smithce40ad62011-11-12 22:28:03 +0000892 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000893 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000894 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000895 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000896 SubobjectDesignator &getLValueDesignator() { return Designator; }
897 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000898
Richard Smith2e312c82012-03-03 22:46:17 +0000899 void moveInto(APValue &V) const {
900 if (Designator.Invalid)
901 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
902 else
903 V = APValue(Base, Offset, Designator.Entries,
904 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000905 }
Richard Smith2e312c82012-03-03 22:46:17 +0000906 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000907 assert(V.isLValue());
908 Base = V.getLValueBase();
909 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000910 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000911 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000912 }
913
Richard Smithb228a862012-02-15 02:18:13 +0000914 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000915 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000916 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000917 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000918 Designator = SubobjectDesignator(getType(B));
919 }
920
921 // Check that this LValue is not based on a null pointer. If it is, produce
922 // a diagnostic and mark the designator as invalid.
923 bool checkNullPointer(EvalInfo &Info, const Expr *E,
924 CheckSubobjectKind CSK) {
925 if (Designator.Invalid)
926 return false;
927 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000928 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000929 << CSK;
930 Designator.setInvalid();
931 return false;
932 }
933 return true;
934 }
935
936 // Check this LValue refers to an object. If not, set the designator to be
937 // invalid and emit a diagnostic.
938 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000939 // Outside C++11, do not build a designator referring to a subobject of
940 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000941 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000942 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000943 return checkNullPointer(Info, E, CSK) &&
944 Designator.checkSubobject(Info, E, CSK);
945 }
946
947 void addDecl(EvalInfo &Info, const Expr *E,
948 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000949 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
950 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000951 }
952 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000953 if (checkSubobject(Info, E, CSK_ArrayToPointer))
954 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000955 }
Richard Smith66c96992012-02-18 22:04:06 +0000956 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000957 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
958 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000959 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000961 if (checkNullPointer(Info, E, CSK_ArrayIndex))
962 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000963 }
John McCall45d55e42010-05-07 21:00:08 +0000964 };
Richard Smith027bf112011-11-17 22:56:20 +0000965
966 struct MemberPtr {
967 MemberPtr() {}
968 explicit MemberPtr(const ValueDecl *Decl) :
969 DeclAndIsDerivedMember(Decl, false), Path() {}
970
971 /// The member or (direct or indirect) field referred to by this member
972 /// pointer, or 0 if this is a null member pointer.
973 const ValueDecl *getDecl() const {
974 return DeclAndIsDerivedMember.getPointer();
975 }
976 /// Is this actually a member of some type derived from the relevant class?
977 bool isDerivedMember() const {
978 return DeclAndIsDerivedMember.getInt();
979 }
980 /// Get the class which the declaration actually lives in.
981 const CXXRecordDecl *getContainingRecord() const {
982 return cast<CXXRecordDecl>(
983 DeclAndIsDerivedMember.getPointer()->getDeclContext());
984 }
985
Richard Smith2e312c82012-03-03 22:46:17 +0000986 void moveInto(APValue &V) const {
987 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000988 }
Richard Smith2e312c82012-03-03 22:46:17 +0000989 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000990 assert(V.isMemberPointer());
991 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
992 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
993 Path.clear();
994 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
995 Path.insert(Path.end(), P.begin(), P.end());
996 }
997
998 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
999 /// whether the member is a member of some class derived from the class type
1000 /// of the member pointer.
1001 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1002 /// Path - The path of base/derived classes from the member declaration's
1003 /// class (exclusive) to the class type of the member pointer (inclusive).
1004 SmallVector<const CXXRecordDecl*, 4> Path;
1005
1006 /// Perform a cast towards the class of the Decl (either up or down the
1007 /// hierarchy).
1008 bool castBack(const CXXRecordDecl *Class) {
1009 assert(!Path.empty());
1010 const CXXRecordDecl *Expected;
1011 if (Path.size() >= 2)
1012 Expected = Path[Path.size() - 2];
1013 else
1014 Expected = getContainingRecord();
1015 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1016 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1017 // if B does not contain the original member and is not a base or
1018 // derived class of the class containing the original member, the result
1019 // of the cast is undefined.
1020 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1021 // (D::*). We consider that to be a language defect.
1022 return false;
1023 }
1024 Path.pop_back();
1025 return true;
1026 }
1027 /// Perform a base-to-derived member pointer cast.
1028 bool castToDerived(const CXXRecordDecl *Derived) {
1029 if (!getDecl())
1030 return true;
1031 if (!isDerivedMember()) {
1032 Path.push_back(Derived);
1033 return true;
1034 }
1035 if (!castBack(Derived))
1036 return false;
1037 if (Path.empty())
1038 DeclAndIsDerivedMember.setInt(false);
1039 return true;
1040 }
1041 /// Perform a derived-to-base member pointer cast.
1042 bool castToBase(const CXXRecordDecl *Base) {
1043 if (!getDecl())
1044 return true;
1045 if (Path.empty())
1046 DeclAndIsDerivedMember.setInt(true);
1047 if (isDerivedMember()) {
1048 Path.push_back(Base);
1049 return true;
1050 }
1051 return castBack(Base);
1052 }
1053 };
Richard Smith357362d2011-12-13 06:39:58 +00001054
Richard Smith7bb00672012-02-01 01:42:44 +00001055 /// Compare two member pointers, which are assumed to be of the same type.
1056 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1057 if (!LHS.getDecl() || !RHS.getDecl())
1058 return !LHS.getDecl() && !RHS.getDecl();
1059 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1060 return false;
1061 return LHS.Path == RHS.Path;
1062 }
John McCall93d91dc2010-05-07 17:22:02 +00001063}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001064
Richard Smith2e312c82012-03-03 22:46:17 +00001065static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001066static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1067 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001068 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001069static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1070static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001071static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1072 EvalInfo &Info);
1073static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001074static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001075static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001076 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001077static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001078static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001079static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001080
1081//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001082// Misc utilities
1083//===----------------------------------------------------------------------===//
1084
Richard Smith84401042013-06-03 05:03:02 +00001085/// Produce a string describing the given constexpr call.
1086static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1087 unsigned ArgIndex = 0;
1088 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1089 !isa<CXXConstructorDecl>(Frame->Callee) &&
1090 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1091
1092 if (!IsMemberCall)
1093 Out << *Frame->Callee << '(';
1094
1095 if (Frame->This && IsMemberCall) {
1096 APValue Val;
1097 Frame->This->moveInto(Val);
1098 Val.printPretty(Out, Frame->Info.Ctx,
1099 Frame->This->Designator.MostDerivedType);
1100 // FIXME: Add parens around Val if needed.
1101 Out << "->" << *Frame->Callee << '(';
1102 IsMemberCall = false;
1103 }
1104
1105 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1106 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1107 if (ArgIndex > (unsigned)IsMemberCall)
1108 Out << ", ";
1109
1110 const ParmVarDecl *Param = *I;
1111 const APValue &Arg = Frame->Arguments[ArgIndex];
1112 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1113
1114 if (ArgIndex == 0 && IsMemberCall)
1115 Out << "->" << *Frame->Callee << '(';
1116 }
1117
1118 Out << ')';
1119}
1120
Richard Smithd9f663b2013-04-22 15:31:51 +00001121/// Evaluate an expression to see if it had side-effects, and discard its
1122/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001123/// \return \c true if the caller should keep evaluating.
1124static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +00001126 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001127 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +00001128 return Info.keepEvaluatingAfterFailure();
Richard Smith6d4c6582013-11-05 22:18:15 +00001129 // FIXME: return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001130 }
1131 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001132}
1133
Richard Smith861b5b52013-05-07 23:34:45 +00001134/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1135/// return its existing value.
1136static int64_t getExtValue(const APSInt &Value) {
1137 return Value.isSigned() ? Value.getSExtValue()
1138 : static_cast<int64_t>(Value.getZExtValue());
1139}
1140
Richard Smithd62306a2011-11-10 06:34:14 +00001141/// Should this call expression be treated as a string literal?
1142static bool IsStringLiteralCall(const CallExpr *E) {
1143 unsigned Builtin = E->isBuiltinCall();
1144 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1145 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1146}
1147
Richard Smithce40ad62011-11-12 22:28:03 +00001148static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001149 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1150 // constant expression of pointer type that evaluates to...
1151
1152 // ... a null pointer value, or a prvalue core constant expression of type
1153 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001154 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001155
Richard Smithce40ad62011-11-12 22:28:03 +00001156 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1157 // ... the address of an object with static storage duration,
1158 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1159 return VD->hasGlobalStorage();
1160 // ... the address of a function,
1161 return isa<FunctionDecl>(D);
1162 }
1163
1164 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001165 switch (E->getStmtClass()) {
1166 default:
1167 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001168 case Expr::CompoundLiteralExprClass: {
1169 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1170 return CLE->isFileScope() && CLE->isLValue();
1171 }
Richard Smithe6c01442013-06-05 00:46:14 +00001172 case Expr::MaterializeTemporaryExprClass:
1173 // A materialized temporary might have been lifetime-extended to static
1174 // storage duration.
1175 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001176 // A string literal has static storage duration.
1177 case Expr::StringLiteralClass:
1178 case Expr::PredefinedExprClass:
1179 case Expr::ObjCStringLiteralClass:
1180 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001181 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001182 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001183 return true;
1184 case Expr::CallExprClass:
1185 return IsStringLiteralCall(cast<CallExpr>(E));
1186 // For GCC compatibility, &&label has static storage duration.
1187 case Expr::AddrLabelExprClass:
1188 return true;
1189 // A Block literal expression may be used as the initialization value for
1190 // Block variables at global or local static scope.
1191 case Expr::BlockExprClass:
1192 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001193 case Expr::ImplicitValueInitExprClass:
1194 // FIXME:
1195 // We can never form an lvalue with an implicit value initialization as its
1196 // base through expression evaluation, so these only appear in one case: the
1197 // implicit variable declaration we invent when checking whether a constexpr
1198 // constructor can produce a constant expression. We must assume that such
1199 // an expression might be a global lvalue.
1200 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001201 }
John McCall95007602010-05-10 23:27:23 +00001202}
1203
Richard Smithb228a862012-02-15 02:18:13 +00001204static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1205 assert(Base && "no location for a null lvalue");
1206 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1207 if (VD)
1208 Info.Note(VD->getLocation(), diag::note_declared_at);
1209 else
Ted Kremenek28831752012-08-23 20:46:57 +00001210 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001211 diag::note_constexpr_temporary_here);
1212}
1213
Richard Smith80815602011-11-07 05:07:52 +00001214/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001215/// value for an address or reference constant expression. Return true if we
1216/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001217static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1218 QualType Type, const LValue &LVal) {
1219 bool IsReferenceType = Type->isReferenceType();
1220
Richard Smith357362d2011-12-13 06:39:58 +00001221 APValue::LValueBase Base = LVal.getLValueBase();
1222 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1223
Richard Smith0dea49e2012-02-18 04:58:18 +00001224 // Check that the object is a global. Note that the fake 'this' object we
1225 // manufacture when checking potential constant expressions is conservatively
1226 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001227 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001228 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001229 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001230 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1231 << IsReferenceType << !Designator.Entries.empty()
1232 << !!VD << VD;
1233 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001234 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001235 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001236 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001237 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001238 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001239 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001240 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001241 LVal.getLValueCallIndex() == 0) &&
1242 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001243
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001244 // Check if this is a thread-local variable.
1245 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1246 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001247 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001248 return false;
1249 }
1250 }
1251
Richard Smitha8105bc2012-01-06 16:39:00 +00001252 // Allow address constant expressions to be past-the-end pointers. This is
1253 // an extension: the standard requires them to point to an object.
1254 if (!IsReferenceType)
1255 return true;
1256
1257 // A reference constant expression must refer to an object.
1258 if (!Base) {
1259 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001260 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001261 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001262 }
1263
Richard Smith357362d2011-12-13 06:39:58 +00001264 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001265 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001266 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001267 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001268 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001269 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001270 }
1271
Richard Smith80815602011-11-07 05:07:52 +00001272 return true;
1273}
1274
Richard Smithfddd3842011-12-30 21:15:51 +00001275/// Check that this core constant expression is of literal type, and if not,
1276/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001277static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1278 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001279 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001280 return true;
1281
Richard Smith7525ff62013-05-09 07:14:00 +00001282 // C++1y: A constant initializer for an object o [...] may also invoke
1283 // constexpr constructors for o and its subobjects even if those objects
1284 // are of non-literal class types.
1285 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001286 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001287 return true;
1288
Richard Smithfddd3842011-12-30 21:15:51 +00001289 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001290 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001291 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001292 << E->getType();
1293 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001294 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001295 return false;
1296}
1297
Richard Smith0b0a0b62011-10-29 20:57:55 +00001298/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001299/// constant expression. If not, report an appropriate diagnostic. Does not
1300/// check that the expression is of literal type.
1301static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1302 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001303 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001304 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1305 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001306 return false;
1307 }
1308
Richard Smithb228a862012-02-15 02:18:13 +00001309 // Core issue 1454: For a literal constant expression of array or class type,
1310 // each subobject of its value shall have been initialized by a constant
1311 // expression.
1312 if (Value.isArray()) {
1313 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1314 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1315 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1316 Value.getArrayInitializedElt(I)))
1317 return false;
1318 }
1319 if (!Value.hasArrayFiller())
1320 return true;
1321 return CheckConstantExpression(Info, DiagLoc, EltTy,
1322 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001323 }
Richard Smithb228a862012-02-15 02:18:13 +00001324 if (Value.isUnion() && Value.getUnionField()) {
1325 return CheckConstantExpression(Info, DiagLoc,
1326 Value.getUnionField()->getType(),
1327 Value.getUnionValue());
1328 }
1329 if (Value.isStruct()) {
1330 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1331 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1332 unsigned BaseIndex = 0;
1333 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1334 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1335 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1336 Value.getStructBase(BaseIndex)))
1337 return false;
1338 }
1339 }
1340 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1341 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001342 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1343 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001344 return false;
1345 }
1346 }
1347
1348 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001349 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001350 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001351 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1352 }
1353
1354 // Everything else is fine.
1355 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001356}
1357
Richard Smith83c68212011-10-31 05:11:32 +00001358const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001359 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001360}
1361
1362static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001363 if (Value.CallIndex)
1364 return false;
1365 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1366 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001367}
1368
Richard Smithcecf1842011-11-01 21:06:14 +00001369static bool IsWeakLValue(const LValue &Value) {
1370 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001371 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001372}
1373
Richard Smith2e312c82012-03-03 22:46:17 +00001374static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001375 // A null base expression indicates a null pointer. These are always
1376 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001377 if (!Value.getLValueBase()) {
1378 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001379 return true;
1380 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001381
Richard Smith027bf112011-11-17 22:56:20 +00001382 // We have a non-null base. These are generally known to be true, but if it's
1383 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001384 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001385 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001386 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001387}
1388
Richard Smith2e312c82012-03-03 22:46:17 +00001389static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001390 switch (Val.getKind()) {
1391 case APValue::Uninitialized:
1392 return false;
1393 case APValue::Int:
1394 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001395 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001396 case APValue::Float:
1397 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001398 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001399 case APValue::ComplexInt:
1400 Result = Val.getComplexIntReal().getBoolValue() ||
1401 Val.getComplexIntImag().getBoolValue();
1402 return true;
1403 case APValue::ComplexFloat:
1404 Result = !Val.getComplexFloatReal().isZero() ||
1405 !Val.getComplexFloatImag().isZero();
1406 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001407 case APValue::LValue:
1408 return EvalPointerValueAsBool(Val, Result);
1409 case APValue::MemberPointer:
1410 Result = Val.getMemberPointerDecl();
1411 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001412 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001413 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001414 case APValue::Struct:
1415 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001416 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001417 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001418 }
1419
Richard Smith11562c52011-10-28 17:51:58 +00001420 llvm_unreachable("unknown APValue kind");
1421}
1422
1423static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1424 EvalInfo &Info) {
1425 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001426 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001427 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001428 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001429 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001430}
1431
Richard Smith357362d2011-12-13 06:39:58 +00001432template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001433static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001434 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001435 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001436 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001437}
1438
1439static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1440 QualType SrcType, const APFloat &Value,
1441 QualType DestType, APSInt &Result) {
1442 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001443 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001444 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001445
Richard Smith357362d2011-12-13 06:39:58 +00001446 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001447 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001448 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1449 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001450 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001451 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001452}
1453
Richard Smith357362d2011-12-13 06:39:58 +00001454static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1455 QualType SrcType, QualType DestType,
1456 APFloat &Result) {
1457 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001458 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001459 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1460 APFloat::rmNearestTiesToEven, &ignored)
1461 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001462 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001463 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001464}
1465
Richard Smith911e1422012-01-30 22:27:01 +00001466static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1467 QualType DestType, QualType SrcType,
1468 APSInt &Value) {
1469 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001470 APSInt Result = Value;
1471 // Figure out if this is a truncate, extend or noop cast.
1472 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001473 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001474 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001475 return Result;
1476}
1477
Richard Smith357362d2011-12-13 06:39:58 +00001478static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1479 QualType SrcType, const APSInt &Value,
1480 QualType DestType, APFloat &Result) {
1481 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1482 if (Result.convertFromAPInt(Value, Value.isSigned(),
1483 APFloat::rmNearestTiesToEven)
1484 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001485 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001486 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001487}
1488
Richard Smith49ca8aa2013-08-06 07:09:20 +00001489static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1490 APValue &Value, const FieldDecl *FD) {
1491 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1492
1493 if (!Value.isInt()) {
1494 // Trying to store a pointer-cast-to-integer into a bitfield.
1495 // FIXME: In this case, we should provide the diagnostic for casting
1496 // a pointer to an integer.
1497 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1498 Info.Diag(E);
1499 return false;
1500 }
1501
1502 APSInt &Int = Value.getInt();
1503 unsigned OldBitWidth = Int.getBitWidth();
1504 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1505 if (NewBitWidth < OldBitWidth)
1506 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1507 return true;
1508}
1509
Eli Friedman803acb32011-12-22 03:51:45 +00001510static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1511 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001512 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001513 if (!Evaluate(SVal, Info, E))
1514 return false;
1515 if (SVal.isInt()) {
1516 Res = SVal.getInt();
1517 return true;
1518 }
1519 if (SVal.isFloat()) {
1520 Res = SVal.getFloat().bitcastToAPInt();
1521 return true;
1522 }
1523 if (SVal.isVector()) {
1524 QualType VecTy = E->getType();
1525 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1526 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1527 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1528 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1529 Res = llvm::APInt::getNullValue(VecSize);
1530 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1531 APValue &Elt = SVal.getVectorElt(i);
1532 llvm::APInt EltAsInt;
1533 if (Elt.isInt()) {
1534 EltAsInt = Elt.getInt();
1535 } else if (Elt.isFloat()) {
1536 EltAsInt = Elt.getFloat().bitcastToAPInt();
1537 } else {
1538 // Don't try to handle vectors of anything other than int or float
1539 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001540 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001541 return false;
1542 }
1543 unsigned BaseEltSize = EltAsInt.getBitWidth();
1544 if (BigEndian)
1545 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1546 else
1547 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1548 }
1549 return true;
1550 }
1551 // Give up if the input isn't an int, float, or vector. For example, we
1552 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001553 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001554 return false;
1555}
1556
Richard Smith43e77732013-05-07 04:50:00 +00001557/// Perform the given integer operation, which is known to need at most BitWidth
1558/// bits, and check for overflow in the original type (if that type was not an
1559/// unsigned type).
1560template<typename Operation>
1561static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1562 const APSInt &LHS, const APSInt &RHS,
1563 unsigned BitWidth, Operation Op) {
1564 if (LHS.isUnsigned())
1565 return Op(LHS, RHS);
1566
1567 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1568 APSInt Result = Value.trunc(LHS.getBitWidth());
1569 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001570 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001571 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1572 diag::warn_integer_constant_overflow)
1573 << Result.toString(10) << E->getType();
1574 else
1575 HandleOverflow(Info, E, Value, E->getType());
1576 }
1577 return Result;
1578}
1579
1580/// Perform the given binary integer operation.
1581static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1582 BinaryOperatorKind Opcode, APSInt RHS,
1583 APSInt &Result) {
1584 switch (Opcode) {
1585 default:
1586 Info.Diag(E);
1587 return false;
1588 case BO_Mul:
1589 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1590 std::multiplies<APSInt>());
1591 return true;
1592 case BO_Add:
1593 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1594 std::plus<APSInt>());
1595 return true;
1596 case BO_Sub:
1597 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1598 std::minus<APSInt>());
1599 return true;
1600 case BO_And: Result = LHS & RHS; return true;
1601 case BO_Xor: Result = LHS ^ RHS; return true;
1602 case BO_Or: Result = LHS | RHS; return true;
1603 case BO_Div:
1604 case BO_Rem:
1605 if (RHS == 0) {
1606 Info.Diag(E, diag::note_expr_divide_by_zero);
1607 return false;
1608 }
1609 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1610 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1611 LHS.isSigned() && LHS.isMinSignedValue())
1612 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1613 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1614 return true;
1615 case BO_Shl: {
1616 if (Info.getLangOpts().OpenCL)
1617 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1618 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1619 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1620 RHS.isUnsigned());
1621 else if (RHS.isSigned() && RHS.isNegative()) {
1622 // During constant-folding, a negative shift is an opposite shift. Such
1623 // a shift is not a constant expression.
1624 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1625 RHS = -RHS;
1626 goto shift_right;
1627 }
1628 shift_left:
1629 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1630 // the shifted type.
1631 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1632 if (SA != RHS) {
1633 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1634 << RHS << E->getType() << LHS.getBitWidth();
1635 } else if (LHS.isSigned()) {
1636 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1637 // operand, and must not overflow the corresponding unsigned type.
1638 if (LHS.isNegative())
1639 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1640 else if (LHS.countLeadingZeros() < SA)
1641 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1642 }
1643 Result = LHS << SA;
1644 return true;
1645 }
1646 case BO_Shr: {
1647 if (Info.getLangOpts().OpenCL)
1648 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1649 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1650 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1651 RHS.isUnsigned());
1652 else if (RHS.isSigned() && RHS.isNegative()) {
1653 // During constant-folding, a negative shift is an opposite shift. Such a
1654 // shift is not a constant expression.
1655 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1656 RHS = -RHS;
1657 goto shift_left;
1658 }
1659 shift_right:
1660 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1661 // shifted type.
1662 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1663 if (SA != RHS)
1664 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1665 << RHS << E->getType() << LHS.getBitWidth();
1666 Result = LHS >> SA;
1667 return true;
1668 }
1669
1670 case BO_LT: Result = LHS < RHS; return true;
1671 case BO_GT: Result = LHS > RHS; return true;
1672 case BO_LE: Result = LHS <= RHS; return true;
1673 case BO_GE: Result = LHS >= RHS; return true;
1674 case BO_EQ: Result = LHS == RHS; return true;
1675 case BO_NE: Result = LHS != RHS; return true;
1676 }
1677}
1678
Richard Smith861b5b52013-05-07 23:34:45 +00001679/// Perform the given binary floating-point operation, in-place, on LHS.
1680static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1681 APFloat &LHS, BinaryOperatorKind Opcode,
1682 const APFloat &RHS) {
1683 switch (Opcode) {
1684 default:
1685 Info.Diag(E);
1686 return false;
1687 case BO_Mul:
1688 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1689 break;
1690 case BO_Add:
1691 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1692 break;
1693 case BO_Sub:
1694 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1695 break;
1696 case BO_Div:
1697 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1698 break;
1699 }
1700
1701 if (LHS.isInfinity() || LHS.isNaN())
1702 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1703 return true;
1704}
1705
Richard Smitha8105bc2012-01-06 16:39:00 +00001706/// Cast an lvalue referring to a base subobject to a derived class, by
1707/// truncating the lvalue's path to the given length.
1708static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1709 const RecordDecl *TruncatedType,
1710 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001711 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001712
1713 // Check we actually point to a derived class object.
1714 if (TruncatedElements == D.Entries.size())
1715 return true;
1716 assert(TruncatedElements >= D.MostDerivedPathLength &&
1717 "not casting to a derived class");
1718 if (!Result.checkSubobject(Info, E, CSK_Derived))
1719 return false;
1720
1721 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001722 const RecordDecl *RD = TruncatedType;
1723 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001724 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001725 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1726 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001727 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001728 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001729 else
Richard Smithd62306a2011-11-10 06:34:14 +00001730 Result.Offset -= Layout.getBaseClassOffset(Base);
1731 RD = Base;
1732 }
Richard Smith027bf112011-11-17 22:56:20 +00001733 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001734 return true;
1735}
1736
John McCalld7bca762012-05-01 00:38:49 +00001737static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001738 const CXXRecordDecl *Derived,
1739 const CXXRecordDecl *Base,
1740 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001741 if (!RL) {
1742 if (Derived->isInvalidDecl()) return false;
1743 RL = &Info.Ctx.getASTRecordLayout(Derived);
1744 }
1745
Richard Smithd62306a2011-11-10 06:34:14 +00001746 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001747 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001748 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001749}
1750
Richard Smitha8105bc2012-01-06 16:39:00 +00001751static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001752 const CXXRecordDecl *DerivedDecl,
1753 const CXXBaseSpecifier *Base) {
1754 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1755
John McCalld7bca762012-05-01 00:38:49 +00001756 if (!Base->isVirtual())
1757 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001758
Richard Smitha8105bc2012-01-06 16:39:00 +00001759 SubobjectDesignator &D = Obj.Designator;
1760 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001761 return false;
1762
Richard Smitha8105bc2012-01-06 16:39:00 +00001763 // Extract most-derived object and corresponding type.
1764 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1765 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1766 return false;
1767
1768 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001769 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001770 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1771 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001772 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001773 return true;
1774}
1775
Richard Smith84401042013-06-03 05:03:02 +00001776static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1777 QualType Type, LValue &Result) {
1778 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1779 PathE = E->path_end();
1780 PathI != PathE; ++PathI) {
1781 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1782 *PathI))
1783 return false;
1784 Type = (*PathI)->getType();
1785 }
1786 return true;
1787}
1788
Richard Smithd62306a2011-11-10 06:34:14 +00001789/// Update LVal to refer to the given field, which must be a member of the type
1790/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001791static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001792 const FieldDecl *FD,
1793 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001794 if (!RL) {
1795 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001796 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001797 }
Richard Smithd62306a2011-11-10 06:34:14 +00001798
1799 unsigned I = FD->getFieldIndex();
1800 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001801 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001802 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001803}
1804
Richard Smith1b78b3d2012-01-25 22:15:11 +00001805/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001806static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001807 LValue &LVal,
1808 const IndirectFieldDecl *IFD) {
1809 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1810 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001811 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1812 return false;
1813 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001814}
1815
Richard Smithd62306a2011-11-10 06:34:14 +00001816/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001817static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1818 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001819 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1820 // extension.
1821 if (Type->isVoidType() || Type->isFunctionType()) {
1822 Size = CharUnits::One();
1823 return true;
1824 }
1825
1826 if (!Type->isConstantSizeType()) {
1827 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001828 // FIXME: Better diagnostic.
1829 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001830 return false;
1831 }
1832
1833 Size = Info.Ctx.getTypeSizeInChars(Type);
1834 return true;
1835}
1836
1837/// Update a pointer value to model pointer arithmetic.
1838/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001839/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001840/// \param LVal - The pointer value to be updated.
1841/// \param EltTy - The pointee type represented by LVal.
1842/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001843static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1844 LValue &LVal, QualType EltTy,
1845 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001846 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001847 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001848 return false;
1849
1850 // Compute the new offset in the appropriate width.
1851 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001852 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001853 return true;
1854}
1855
Richard Smith66c96992012-02-18 22:04:06 +00001856/// Update an lvalue to refer to a component of a complex number.
1857/// \param Info - Information about the ongoing evaluation.
1858/// \param LVal - The lvalue to be updated.
1859/// \param EltTy - The complex number's component type.
1860/// \param Imag - False for the real component, true for the imaginary.
1861static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1862 LValue &LVal, QualType EltTy,
1863 bool Imag) {
1864 if (Imag) {
1865 CharUnits SizeOfComponent;
1866 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1867 return false;
1868 LVal.Offset += SizeOfComponent;
1869 }
1870 LVal.addComplex(Info, E, EltTy, Imag);
1871 return true;
1872}
1873
Richard Smith27908702011-10-24 17:54:18 +00001874/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001875///
1876/// \param Info Information about the ongoing evaluation.
1877/// \param E An expression to be used when printing diagnostics.
1878/// \param VD The variable whose initializer should be obtained.
1879/// \param Frame The frame in which the variable was created. Must be null
1880/// if this variable is not local to the evaluation.
1881/// \param Result Filled in with a pointer to the value of the variable.
1882static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1883 const VarDecl *VD, CallStackFrame *Frame,
1884 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001885 // If this is a parameter to an active constexpr function call, perform
1886 // argument substitution.
1887 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001888 // Assume arguments of a potential constant expression are unknown
1889 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001890 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001891 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001892 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001893 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001894 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001895 }
Richard Smith3229b742013-05-05 21:17:10 +00001896 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001897 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001898 }
Richard Smith27908702011-10-24 17:54:18 +00001899
Richard Smithd9f663b2013-04-22 15:31:51 +00001900 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001901 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001902 Result = Frame->getTemporary(VD);
1903 assert(Result && "missing value for local variable");
1904 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001905 }
1906
Richard Smithd0b4dd62011-12-19 06:19:21 +00001907 // Dig out the initializer, and use the declaration which it's attached to.
1908 const Expr *Init = VD->getAnyInitializer(VD);
1909 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001910 // If we're checking a potential constant expression, the variable could be
1911 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001912 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001913 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001914 return false;
1915 }
1916
Richard Smithd62306a2011-11-10 06:34:14 +00001917 // If we're currently evaluating the initializer of this declaration, use that
1918 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001919 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001920 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001921 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001922 }
1923
Richard Smithcecf1842011-11-01 21:06:14 +00001924 // Never evaluate the initializer of a weak variable. We can't be sure that
1925 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001926 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001927 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001928 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001929 }
Richard Smithcecf1842011-11-01 21:06:14 +00001930
Richard Smithd0b4dd62011-12-19 06:19:21 +00001931 // Check that we can fold the initializer. In C++, we will have already done
1932 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001933 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001934 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001935 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001936 Notes.size() + 1) << VD;
1937 Info.Note(VD->getLocation(), diag::note_declared_at);
1938 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001939 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001940 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001941 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001942 Notes.size() + 1) << VD;
1943 Info.Note(VD->getLocation(), diag::note_declared_at);
1944 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001945 }
Richard Smith27908702011-10-24 17:54:18 +00001946
Richard Smith3229b742013-05-05 21:17:10 +00001947 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001948 return true;
Richard Smith27908702011-10-24 17:54:18 +00001949}
1950
Richard Smith11562c52011-10-28 17:51:58 +00001951static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001952 Qualifiers Quals = T.getQualifiers();
1953 return Quals.hasConst() && !Quals.hasVolatile();
1954}
1955
Richard Smithe97cbd72011-11-11 04:05:33 +00001956/// Get the base index of the given base class within an APValue representing
1957/// the given derived class.
1958static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1959 const CXXRecordDecl *Base) {
1960 Base = Base->getCanonicalDecl();
1961 unsigned Index = 0;
1962 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1963 E = Derived->bases_end(); I != E; ++I, ++Index) {
1964 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1965 return Index;
1966 }
1967
1968 llvm_unreachable("base class missing from derived class's bases list");
1969}
1970
Richard Smith3da88fa2013-04-26 14:36:30 +00001971/// Extract the value of a character from a string literal.
1972static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1973 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001974 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001975 const StringLiteral *S = cast<StringLiteral>(Lit);
1976 const ConstantArrayType *CAT =
1977 Info.Ctx.getAsConstantArrayType(S->getType());
1978 assert(CAT && "string literal isn't an array");
1979 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001980 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001981
1982 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001983 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001984 if (Index < S->getLength())
1985 Value = S->getCodeUnit(Index);
1986 return Value;
1987}
1988
Richard Smith3da88fa2013-04-26 14:36:30 +00001989// Expand a string literal into an array of characters.
1990static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1991 APValue &Result) {
1992 const StringLiteral *S = cast<StringLiteral>(Lit);
1993 const ConstantArrayType *CAT =
1994 Info.Ctx.getAsConstantArrayType(S->getType());
1995 assert(CAT && "string literal isn't an array");
1996 QualType CharType = CAT->getElementType();
1997 assert(CharType->isIntegerType() && "unexpected character type");
1998
1999 unsigned Elts = CAT->getSize().getZExtValue();
2000 Result = APValue(APValue::UninitArray(),
2001 std::min(S->getLength(), Elts), Elts);
2002 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2003 CharType->isUnsignedIntegerType());
2004 if (Result.hasArrayFiller())
2005 Result.getArrayFiller() = APValue(Value);
2006 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2007 Value = S->getCodeUnit(I);
2008 Result.getArrayInitializedElt(I) = APValue(Value);
2009 }
2010}
2011
2012// Expand an array so that it has more than Index filled elements.
2013static void expandArray(APValue &Array, unsigned Index) {
2014 unsigned Size = Array.getArraySize();
2015 assert(Index < Size);
2016
2017 // Always at least double the number of elements for which we store a value.
2018 unsigned OldElts = Array.getArrayInitializedElts();
2019 unsigned NewElts = std::max(Index+1, OldElts * 2);
2020 NewElts = std::min(Size, std::max(NewElts, 8u));
2021
2022 // Copy the data across.
2023 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2024 for (unsigned I = 0; I != OldElts; ++I)
2025 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2026 for (unsigned I = OldElts; I != NewElts; ++I)
2027 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2028 if (NewValue.hasArrayFiller())
2029 NewValue.getArrayFiller() = Array.getArrayFiller();
2030 Array.swap(NewValue);
2031}
2032
Richard Smith861b5b52013-05-07 23:34:45 +00002033/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002034enum AccessKinds {
2035 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002036 AK_Assign,
2037 AK_Increment,
2038 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002039};
2040
Richard Smith3229b742013-05-05 21:17:10 +00002041/// A handle to a complete object (an object that is not a subobject of
2042/// another object).
2043struct CompleteObject {
2044 /// The value of the complete object.
2045 APValue *Value;
2046 /// The type of the complete object.
2047 QualType Type;
2048
2049 CompleteObject() : Value(0) {}
2050 CompleteObject(APValue *Value, QualType Type)
2051 : Value(Value), Type(Type) {
2052 assert(Value && "missing value for complete object");
2053 }
2054
David Blaikie7d170102013-05-15 07:37:26 +00002055 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002056};
2057
Richard Smith3da88fa2013-04-26 14:36:30 +00002058/// Find the designated sub-object of an rvalue.
2059template<typename SubobjectHandler>
2060typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002061findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002062 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002063 if (Sub.Invalid)
2064 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002065 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002066 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002067 if (Info.getLangOpts().CPlusPlus11)
2068 Info.Diag(E, diag::note_constexpr_access_past_end)
2069 << handler.AccessKind;
2070 else
2071 Info.Diag(E);
2072 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002073 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002074
Richard Smith3229b742013-05-05 21:17:10 +00002075 APValue *O = Obj.Value;
2076 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002077 const FieldDecl *LastField = 0;
2078
Richard Smithd62306a2011-11-10 06:34:14 +00002079 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002080 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2081 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002082 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002083 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2084 return handler.failed();
2085 }
2086
Richard Smith49ca8aa2013-08-06 07:09:20 +00002087 if (I == N) {
2088 if (!handler.found(*O, ObjType))
2089 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002090
Richard Smith49ca8aa2013-08-06 07:09:20 +00002091 // If we modified a bit-field, truncate it to the right width.
2092 if (handler.AccessKind != AK_Read &&
2093 LastField && LastField->isBitField() &&
2094 !truncateBitfieldValue(Info, E, *O, LastField))
2095 return false;
2096
2097 return true;
2098 }
2099
2100 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002101 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002102 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002103 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002104 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002105 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002106 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002107 // Note, it should not be possible to form a pointer with a valid
2108 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002109 if (Info.getLangOpts().CPlusPlus11)
2110 Info.Diag(E, diag::note_constexpr_access_past_end)
2111 << handler.AccessKind;
2112 else
2113 Info.Diag(E);
2114 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002115 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002116
2117 ObjType = CAT->getElementType();
2118
Richard Smith14a94132012-02-17 03:35:37 +00002119 // An array object is represented as either an Array APValue or as an
2120 // LValue which refers to a string literal.
2121 if (O->isLValue()) {
2122 assert(I == N - 1 && "extracting subobject of character?");
2123 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002124 if (handler.AccessKind != AK_Read)
2125 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2126 *O);
2127 else
2128 return handler.foundString(*O, ObjType, Index);
2129 }
2130
2131 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002132 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002133 else if (handler.AccessKind != AK_Read) {
2134 expandArray(*O, Index);
2135 O = &O->getArrayInitializedElt(Index);
2136 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002137 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002138 } else if (ObjType->isAnyComplexType()) {
2139 // Next subobject is a complex number.
2140 uint64_t Index = Sub.Entries[I].ArrayIndex;
2141 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002142 if (Info.getLangOpts().CPlusPlus11)
2143 Info.Diag(E, diag::note_constexpr_access_past_end)
2144 << handler.AccessKind;
2145 else
2146 Info.Diag(E);
2147 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002148 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002149
2150 bool WasConstQualified = ObjType.isConstQualified();
2151 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2152 if (WasConstQualified)
2153 ObjType.addConst();
2154
Richard Smith66c96992012-02-18 22:04:06 +00002155 assert(I == N - 1 && "extracting subobject of scalar?");
2156 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002157 return handler.found(Index ? O->getComplexIntImag()
2158 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002159 } else {
2160 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002161 return handler.found(Index ? O->getComplexFloatImag()
2162 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002163 }
Richard Smithd62306a2011-11-10 06:34:14 +00002164 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002165 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002166 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002167 << Field;
2168 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002169 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002170 }
2171
Richard Smithd62306a2011-11-10 06:34:14 +00002172 // Next subobject is a class, struct or union field.
2173 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2174 if (RD->isUnion()) {
2175 const FieldDecl *UnionField = O->getUnionField();
2176 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002177 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002178 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2179 << handler.AccessKind << Field << !UnionField << UnionField;
2180 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002181 }
Richard Smithd62306a2011-11-10 06:34:14 +00002182 O = &O->getUnionValue();
2183 } else
2184 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002185
2186 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002187 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002188 if (WasConstQualified && !Field->isMutable())
2189 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002190
2191 if (ObjType.isVolatileQualified()) {
2192 if (Info.getLangOpts().CPlusPlus) {
2193 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002194 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2195 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002196 Info.Note(Field->getLocation(), diag::note_declared_at);
2197 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002198 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002199 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002200 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002201 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002202
2203 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002204 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002205 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002206 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2207 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2208 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002209
2210 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002211 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002212 if (WasConstQualified)
2213 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002214 }
2215 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002216}
2217
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002218namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002219struct ExtractSubobjectHandler {
2220 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002221 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002222
2223 static const AccessKinds AccessKind = AK_Read;
2224
2225 typedef bool result_type;
2226 bool failed() { return false; }
2227 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002228 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002229 return true;
2230 }
2231 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002232 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002233 return true;
2234 }
2235 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002236 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002237 return true;
2238 }
2239 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002240 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002241 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2242 return true;
2243 }
2244};
Richard Smith3229b742013-05-05 21:17:10 +00002245} // end anonymous namespace
2246
Richard Smith3da88fa2013-04-26 14:36:30 +00002247const AccessKinds ExtractSubobjectHandler::AccessKind;
2248
2249/// Extract the designated sub-object of an rvalue.
2250static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002251 const CompleteObject &Obj,
2252 const SubobjectDesignator &Sub,
2253 APValue &Result) {
2254 ExtractSubobjectHandler Handler = { Info, Result };
2255 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002256}
2257
Richard Smith3229b742013-05-05 21:17:10 +00002258namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002259struct ModifySubobjectHandler {
2260 EvalInfo &Info;
2261 APValue &NewVal;
2262 const Expr *E;
2263
2264 typedef bool result_type;
2265 static const AccessKinds AccessKind = AK_Assign;
2266
2267 bool checkConst(QualType QT) {
2268 // Assigning to a const object has undefined behavior.
2269 if (QT.isConstQualified()) {
2270 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2271 return false;
2272 }
2273 return true;
2274 }
2275
2276 bool failed() { return false; }
2277 bool found(APValue &Subobj, QualType SubobjType) {
2278 if (!checkConst(SubobjType))
2279 return false;
2280 // We've been given ownership of NewVal, so just swap it in.
2281 Subobj.swap(NewVal);
2282 return true;
2283 }
2284 bool found(APSInt &Value, QualType SubobjType) {
2285 if (!checkConst(SubobjType))
2286 return false;
2287 if (!NewVal.isInt()) {
2288 // Maybe trying to write a cast pointer value into a complex?
2289 Info.Diag(E);
2290 return false;
2291 }
2292 Value = NewVal.getInt();
2293 return true;
2294 }
2295 bool found(APFloat &Value, QualType SubobjType) {
2296 if (!checkConst(SubobjType))
2297 return false;
2298 Value = NewVal.getFloat();
2299 return true;
2300 }
2301 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2302 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2303 }
2304};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002305} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002306
Richard Smith3229b742013-05-05 21:17:10 +00002307const AccessKinds ModifySubobjectHandler::AccessKind;
2308
Richard Smith3da88fa2013-04-26 14:36:30 +00002309/// Update the designated sub-object of an rvalue to the given value.
2310static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002311 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002312 const SubobjectDesignator &Sub,
2313 APValue &NewVal) {
2314 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002315 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002316}
2317
Richard Smith84f6dcf2012-02-02 01:16:57 +00002318/// Find the position where two subobject designators diverge, or equivalently
2319/// the length of the common initial subsequence.
2320static unsigned FindDesignatorMismatch(QualType ObjType,
2321 const SubobjectDesignator &A,
2322 const SubobjectDesignator &B,
2323 bool &WasArrayIndex) {
2324 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2325 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002326 if (!ObjType.isNull() &&
2327 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002328 // Next subobject is an array element.
2329 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2330 WasArrayIndex = true;
2331 return I;
2332 }
Richard Smith66c96992012-02-18 22:04:06 +00002333 if (ObjType->isAnyComplexType())
2334 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2335 else
2336 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002337 } else {
2338 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2339 WasArrayIndex = false;
2340 return I;
2341 }
2342 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2343 // Next subobject is a field.
2344 ObjType = FD->getType();
2345 else
2346 // Next subobject is a base class.
2347 ObjType = QualType();
2348 }
2349 }
2350 WasArrayIndex = false;
2351 return I;
2352}
2353
2354/// Determine whether the given subobject designators refer to elements of the
2355/// same array object.
2356static bool AreElementsOfSameArray(QualType ObjType,
2357 const SubobjectDesignator &A,
2358 const SubobjectDesignator &B) {
2359 if (A.Entries.size() != B.Entries.size())
2360 return false;
2361
2362 bool IsArray = A.MostDerivedArraySize != 0;
2363 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2364 // A is a subobject of the array element.
2365 return false;
2366
2367 // If A (and B) designates an array element, the last entry will be the array
2368 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2369 // of length 1' case, and the entire path must match.
2370 bool WasArrayIndex;
2371 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2372 return CommonLength >= A.Entries.size() - IsArray;
2373}
2374
Richard Smith3229b742013-05-05 21:17:10 +00002375/// Find the complete object to which an LValue refers.
2376CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2377 const LValue &LVal, QualType LValType) {
2378 if (!LVal.Base) {
2379 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2380 return CompleteObject();
2381 }
2382
2383 CallStackFrame *Frame = 0;
2384 if (LVal.CallIndex) {
2385 Frame = Info.getCallFrame(LVal.CallIndex);
2386 if (!Frame) {
2387 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2388 << AK << LVal.Base.is<const ValueDecl*>();
2389 NoteLValueLocation(Info, LVal.Base);
2390 return CompleteObject();
2391 }
Richard Smith3229b742013-05-05 21:17:10 +00002392 }
2393
2394 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2395 // is not a constant expression (even if the object is non-volatile). We also
2396 // apply this rule to C++98, in order to conform to the expected 'volatile'
2397 // semantics.
2398 if (LValType.isVolatileQualified()) {
2399 if (Info.getLangOpts().CPlusPlus)
2400 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2401 << AK << LValType;
2402 else
2403 Info.Diag(E);
2404 return CompleteObject();
2405 }
2406
2407 // Compute value storage location and type of base object.
2408 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002409 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002410
2411 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2412 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2413 // In C++11, constexpr, non-volatile variables initialized with constant
2414 // expressions are constant expressions too. Inside constexpr functions,
2415 // parameters are constant expressions even if they're non-const.
2416 // In C++1y, objects local to a constant expression (those with a Frame) are
2417 // both readable and writable inside constant expressions.
2418 // In C, such things can also be folded, although they are not ICEs.
2419 const VarDecl *VD = dyn_cast<VarDecl>(D);
2420 if (VD) {
2421 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2422 VD = VDef;
2423 }
2424 if (!VD || VD->isInvalidDecl()) {
2425 Info.Diag(E);
2426 return CompleteObject();
2427 }
2428
2429 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002430 if (BaseType.isVolatileQualified()) {
2431 if (Info.getLangOpts().CPlusPlus) {
2432 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2433 << AK << 1 << VD;
2434 Info.Note(VD->getLocation(), diag::note_declared_at);
2435 } else {
2436 Info.Diag(E);
2437 }
2438 return CompleteObject();
2439 }
2440
2441 // Unless we're looking at a local variable or argument in a constexpr call,
2442 // the variable we're reading must be const.
2443 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002444 if (Info.getLangOpts().CPlusPlus1y &&
2445 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2446 // OK, we can read and modify an object if we're in the process of
2447 // evaluating its initializer, because its lifetime began in this
2448 // evaluation.
2449 } else if (AK != AK_Read) {
2450 // All the remaining cases only permit reading.
2451 Info.Diag(E, diag::note_constexpr_modify_global);
2452 return CompleteObject();
2453 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002454 // OK, we can read this variable.
2455 } else if (BaseType->isIntegralOrEnumerationType()) {
2456 if (!BaseType.isConstQualified()) {
2457 if (Info.getLangOpts().CPlusPlus) {
2458 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2459 Info.Note(VD->getLocation(), diag::note_declared_at);
2460 } else {
2461 Info.Diag(E);
2462 }
2463 return CompleteObject();
2464 }
2465 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2466 // We support folding of const floating-point types, in order to make
2467 // static const data members of such types (supported as an extension)
2468 // more useful.
2469 if (Info.getLangOpts().CPlusPlus11) {
2470 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2471 Info.Note(VD->getLocation(), diag::note_declared_at);
2472 } else {
2473 Info.CCEDiag(E);
2474 }
2475 } else {
2476 // FIXME: Allow folding of values of any literal type in all languages.
2477 if (Info.getLangOpts().CPlusPlus11) {
2478 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2479 Info.Note(VD->getLocation(), diag::note_declared_at);
2480 } else {
2481 Info.Diag(E);
2482 }
2483 return CompleteObject();
2484 }
2485 }
2486
2487 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2488 return CompleteObject();
2489 } else {
2490 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2491
2492 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002493 if (const MaterializeTemporaryExpr *MTE =
2494 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2495 assert(MTE->getStorageDuration() == SD_Static &&
2496 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002497
Richard Smithe6c01442013-06-05 00:46:14 +00002498 // Per C++1y [expr.const]p2:
2499 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2500 // - a [...] glvalue of integral or enumeration type that refers to
2501 // a non-volatile const object [...]
2502 // [...]
2503 // - a [...] glvalue of literal type that refers to a non-volatile
2504 // object whose lifetime began within the evaluation of e.
2505 //
2506 // C++11 misses the 'began within the evaluation of e' check and
2507 // instead allows all temporaries, including things like:
2508 // int &&r = 1;
2509 // int x = ++r;
2510 // constexpr int k = r;
2511 // Therefore we use the C++1y rules in C++11 too.
2512 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2513 const ValueDecl *ED = MTE->getExtendingDecl();
2514 if (!(BaseType.isConstQualified() &&
2515 BaseType->isIntegralOrEnumerationType()) &&
2516 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2517 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2518 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2519 return CompleteObject();
2520 }
2521
2522 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2523 assert(BaseVal && "got reference to unevaluated temporary");
2524 } else {
2525 Info.Diag(E);
2526 return CompleteObject();
2527 }
2528 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002529 BaseVal = Frame->getTemporary(Base);
2530 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002531 }
Richard Smith3229b742013-05-05 21:17:10 +00002532
2533 // Volatile temporary objects cannot be accessed in constant expressions.
2534 if (BaseType.isVolatileQualified()) {
2535 if (Info.getLangOpts().CPlusPlus) {
2536 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2537 << AK << 0;
2538 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2539 } else {
2540 Info.Diag(E);
2541 }
2542 return CompleteObject();
2543 }
2544 }
2545
Richard Smith7525ff62013-05-09 07:14:00 +00002546 // During the construction of an object, it is not yet 'const'.
2547 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2548 // and this doesn't do quite the right thing for const subobjects of the
2549 // object under construction.
2550 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2551 BaseType = Info.Ctx.getCanonicalType(BaseType);
2552 BaseType.removeLocalConst();
2553 }
2554
Richard Smith6d4c6582013-11-05 22:18:15 +00002555 // In C++1y, we can't safely access any mutable state when we might be
2556 // evaluating after an unmodeled side effect or an evaluation failure.
2557 //
2558 // FIXME: Not all local state is mutable. Allow local constant subobjects
2559 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002560 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002561 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002562 return CompleteObject();
2563
2564 return CompleteObject(BaseVal, BaseType);
2565}
2566
Richard Smith243ef902013-05-05 23:31:59 +00002567/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2568/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2569/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002570///
2571/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002572/// \param Conv - The expression for which we are performing the conversion.
2573/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002574/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2575/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002576/// \param LVal - The glvalue on which we are attempting to perform this action.
2577/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002578static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002579 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002580 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002581 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002582 return false;
2583
Richard Smith3229b742013-05-05 21:17:10 +00002584 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002585 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002586 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2587 !Type.isVolatileQualified()) {
2588 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2589 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2590 // initializer until now for such expressions. Such an expression can't be
2591 // an ICE in C, so this only matters for fold.
2592 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2593 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002594 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002595 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002596 }
Richard Smith3229b742013-05-05 21:17:10 +00002597 APValue Lit;
2598 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2599 return false;
2600 CompleteObject LitObj(&Lit, Base->getType());
2601 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2602 } else if (isa<StringLiteral>(Base)) {
2603 // We represent a string literal array as an lvalue pointing at the
2604 // corresponding expression, rather than building an array of chars.
2605 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2606 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2607 CompleteObject StrObj(&Str, Base->getType());
2608 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002609 }
Richard Smith11562c52011-10-28 17:51:58 +00002610 }
2611
Richard Smith3229b742013-05-05 21:17:10 +00002612 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2613 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002614}
2615
2616/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002617static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002618 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002619 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002620 return false;
2621
Richard Smith3229b742013-05-05 21:17:10 +00002622 if (!Info.getLangOpts().CPlusPlus1y) {
2623 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002624 return false;
2625 }
2626
Richard Smith3229b742013-05-05 21:17:10 +00002627 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2628 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002629}
2630
Richard Smith243ef902013-05-05 23:31:59 +00002631static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2632 return T->isSignedIntegerType() &&
2633 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2634}
2635
2636namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002637struct CompoundAssignSubobjectHandler {
2638 EvalInfo &Info;
2639 const Expr *E;
2640 QualType PromotedLHSType;
2641 BinaryOperatorKind Opcode;
2642 const APValue &RHS;
2643
2644 static const AccessKinds AccessKind = AK_Assign;
2645
2646 typedef bool result_type;
2647
2648 bool checkConst(QualType QT) {
2649 // Assigning to a const object has undefined behavior.
2650 if (QT.isConstQualified()) {
2651 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2652 return false;
2653 }
2654 return true;
2655 }
2656
2657 bool failed() { return false; }
2658 bool found(APValue &Subobj, QualType SubobjType) {
2659 switch (Subobj.getKind()) {
2660 case APValue::Int:
2661 return found(Subobj.getInt(), SubobjType);
2662 case APValue::Float:
2663 return found(Subobj.getFloat(), SubobjType);
2664 case APValue::ComplexInt:
2665 case APValue::ComplexFloat:
2666 // FIXME: Implement complex compound assignment.
2667 Info.Diag(E);
2668 return false;
2669 case APValue::LValue:
2670 return foundPointer(Subobj, SubobjType);
2671 default:
2672 // FIXME: can this happen?
2673 Info.Diag(E);
2674 return false;
2675 }
2676 }
2677 bool found(APSInt &Value, QualType SubobjType) {
2678 if (!checkConst(SubobjType))
2679 return false;
2680
2681 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2682 // We don't support compound assignment on integer-cast-to-pointer
2683 // values.
2684 Info.Diag(E);
2685 return false;
2686 }
2687
2688 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2689 SubobjType, Value);
2690 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2691 return false;
2692 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2693 return true;
2694 }
2695 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002696 return checkConst(SubobjType) &&
2697 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2698 Value) &&
2699 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2700 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002701 }
2702 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2703 if (!checkConst(SubobjType))
2704 return false;
2705
2706 QualType PointeeType;
2707 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2708 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002709
2710 if (PointeeType.isNull() || !RHS.isInt() ||
2711 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002712 Info.Diag(E);
2713 return false;
2714 }
2715
Richard Smith861b5b52013-05-07 23:34:45 +00002716 int64_t Offset = getExtValue(RHS.getInt());
2717 if (Opcode == BO_Sub)
2718 Offset = -Offset;
2719
2720 LValue LVal;
2721 LVal.setFrom(Info.Ctx, Subobj);
2722 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2723 return false;
2724 LVal.moveInto(Subobj);
2725 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002726 }
2727 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2728 llvm_unreachable("shouldn't encounter string elements here");
2729 }
2730};
2731} // end anonymous namespace
2732
2733const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2734
2735/// Perform a compound assignment of LVal <op>= RVal.
2736static bool handleCompoundAssignment(
2737 EvalInfo &Info, const Expr *E,
2738 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2739 BinaryOperatorKind Opcode, const APValue &RVal) {
2740 if (LVal.Designator.Invalid)
2741 return false;
2742
2743 if (!Info.getLangOpts().CPlusPlus1y) {
2744 Info.Diag(E);
2745 return false;
2746 }
2747
2748 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2749 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2750 RVal };
2751 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2752}
2753
2754namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002755struct IncDecSubobjectHandler {
2756 EvalInfo &Info;
2757 const Expr *E;
2758 AccessKinds AccessKind;
2759 APValue *Old;
2760
2761 typedef bool result_type;
2762
2763 bool checkConst(QualType QT) {
2764 // Assigning to a const object has undefined behavior.
2765 if (QT.isConstQualified()) {
2766 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2767 return false;
2768 }
2769 return true;
2770 }
2771
2772 bool failed() { return false; }
2773 bool found(APValue &Subobj, QualType SubobjType) {
2774 // Stash the old value. Also clear Old, so we don't clobber it later
2775 // if we're post-incrementing a complex.
2776 if (Old) {
2777 *Old = Subobj;
2778 Old = 0;
2779 }
2780
2781 switch (Subobj.getKind()) {
2782 case APValue::Int:
2783 return found(Subobj.getInt(), SubobjType);
2784 case APValue::Float:
2785 return found(Subobj.getFloat(), SubobjType);
2786 case APValue::ComplexInt:
2787 return found(Subobj.getComplexIntReal(),
2788 SubobjType->castAs<ComplexType>()->getElementType()
2789 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2790 case APValue::ComplexFloat:
2791 return found(Subobj.getComplexFloatReal(),
2792 SubobjType->castAs<ComplexType>()->getElementType()
2793 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2794 case APValue::LValue:
2795 return foundPointer(Subobj, SubobjType);
2796 default:
2797 // FIXME: can this happen?
2798 Info.Diag(E);
2799 return false;
2800 }
2801 }
2802 bool found(APSInt &Value, QualType SubobjType) {
2803 if (!checkConst(SubobjType))
2804 return false;
2805
2806 if (!SubobjType->isIntegerType()) {
2807 // We don't support increment / decrement on integer-cast-to-pointer
2808 // values.
2809 Info.Diag(E);
2810 return false;
2811 }
2812
2813 if (Old) *Old = APValue(Value);
2814
2815 // bool arithmetic promotes to int, and the conversion back to bool
2816 // doesn't reduce mod 2^n, so special-case it.
2817 if (SubobjType->isBooleanType()) {
2818 if (AccessKind == AK_Increment)
2819 Value = 1;
2820 else
2821 Value = !Value;
2822 return true;
2823 }
2824
2825 bool WasNegative = Value.isNegative();
2826 if (AccessKind == AK_Increment) {
2827 ++Value;
2828
2829 if (!WasNegative && Value.isNegative() &&
2830 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2831 APSInt ActualValue(Value, /*IsUnsigned*/true);
2832 HandleOverflow(Info, E, ActualValue, SubobjType);
2833 }
2834 } else {
2835 --Value;
2836
2837 if (WasNegative && !Value.isNegative() &&
2838 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2839 unsigned BitWidth = Value.getBitWidth();
2840 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2841 ActualValue.setBit(BitWidth);
2842 HandleOverflow(Info, E, ActualValue, SubobjType);
2843 }
2844 }
2845 return true;
2846 }
2847 bool found(APFloat &Value, QualType SubobjType) {
2848 if (!checkConst(SubobjType))
2849 return false;
2850
2851 if (Old) *Old = APValue(Value);
2852
2853 APFloat One(Value.getSemantics(), 1);
2854 if (AccessKind == AK_Increment)
2855 Value.add(One, APFloat::rmNearestTiesToEven);
2856 else
2857 Value.subtract(One, APFloat::rmNearestTiesToEven);
2858 return true;
2859 }
2860 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2861 if (!checkConst(SubobjType))
2862 return false;
2863
2864 QualType PointeeType;
2865 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2866 PointeeType = PT->getPointeeType();
2867 else {
2868 Info.Diag(E);
2869 return false;
2870 }
2871
2872 LValue LVal;
2873 LVal.setFrom(Info.Ctx, Subobj);
2874 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2875 AccessKind == AK_Increment ? 1 : -1))
2876 return false;
2877 LVal.moveInto(Subobj);
2878 return true;
2879 }
2880 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2881 llvm_unreachable("shouldn't encounter string elements here");
2882 }
2883};
2884} // end anonymous namespace
2885
2886/// Perform an increment or decrement on LVal.
2887static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2888 QualType LValType, bool IsIncrement, APValue *Old) {
2889 if (LVal.Designator.Invalid)
2890 return false;
2891
2892 if (!Info.getLangOpts().CPlusPlus1y) {
2893 Info.Diag(E);
2894 return false;
2895 }
2896
2897 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2898 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2899 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2900 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2901}
2902
Richard Smithe97cbd72011-11-11 04:05:33 +00002903/// Build an lvalue for the object argument of a member function call.
2904static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2905 LValue &This) {
2906 if (Object->getType()->isPointerType())
2907 return EvaluatePointer(Object, This, Info);
2908
2909 if (Object->isGLValue())
2910 return EvaluateLValue(Object, This, Info);
2911
Richard Smithd9f663b2013-04-22 15:31:51 +00002912 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002913 return EvaluateTemporary(Object, This, Info);
2914
2915 return false;
2916}
2917
2918/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2919/// lvalue referring to the result.
2920///
2921/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002922/// \param LV - An lvalue referring to the base of the member pointer.
2923/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002924/// \param IncludeMember - Specifies whether the member itself is included in
2925/// the resulting LValue subobject designator. This is not possible when
2926/// creating a bound member function.
2927/// \return The field or method declaration to which the member pointer refers,
2928/// or 0 if evaluation fails.
2929static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002930 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002931 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002932 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002933 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002934 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002935 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002936 return 0;
2937
2938 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2939 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002940 if (!MemPtr.getDecl()) {
2941 // FIXME: Specific diagnostic.
2942 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002943 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002944 }
Richard Smith253c2a32012-01-27 01:14:48 +00002945
Richard Smith027bf112011-11-17 22:56:20 +00002946 if (MemPtr.isDerivedMember()) {
2947 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002948 // The end of the derived-to-base path for the base object must match the
2949 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002950 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002951 LV.Designator.Entries.size()) {
2952 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002953 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002954 }
Richard Smith027bf112011-11-17 22:56:20 +00002955 unsigned PathLengthToMember =
2956 LV.Designator.Entries.size() - MemPtr.Path.size();
2957 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2958 const CXXRecordDecl *LVDecl = getAsBaseClass(
2959 LV.Designator.Entries[PathLengthToMember + I]);
2960 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002961 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2962 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002963 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002964 }
Richard Smith027bf112011-11-17 22:56:20 +00002965 }
2966
2967 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002968 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002969 PathLengthToMember))
2970 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002971 } else if (!MemPtr.Path.empty()) {
2972 // Extend the LValue path with the member pointer's path.
2973 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2974 MemPtr.Path.size() + IncludeMember);
2975
2976 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002977 if (const PointerType *PT = LVType->getAs<PointerType>())
2978 LVType = PT->getPointeeType();
2979 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2980 assert(RD && "member pointer access on non-class-type expression");
2981 // The first class in the path is that of the lvalue.
2982 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2983 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002984 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002985 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002986 RD = Base;
2987 }
2988 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002989 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2990 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002991 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002992 }
2993
2994 // Add the member. Note that we cannot build bound member functions here.
2995 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002996 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002997 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002998 return 0;
2999 } else if (const IndirectFieldDecl *IFD =
3000 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003001 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00003002 return 0;
3003 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003004 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003005 }
Richard Smith027bf112011-11-17 22:56:20 +00003006 }
3007
3008 return MemPtr.getDecl();
3009}
3010
Richard Smith84401042013-06-03 05:03:02 +00003011static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3012 const BinaryOperator *BO,
3013 LValue &LV,
3014 bool IncludeMember = true) {
3015 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3016
3017 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3018 if (Info.keepEvaluatingAfterFailure()) {
3019 MemberPtr MemPtr;
3020 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3021 }
3022 return 0;
3023 }
3024
3025 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3026 BO->getRHS(), IncludeMember);
3027}
3028
Richard Smith027bf112011-11-17 22:56:20 +00003029/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3030/// the provided lvalue, which currently refers to the base object.
3031static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3032 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003033 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003034 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003035 return false;
3036
Richard Smitha8105bc2012-01-06 16:39:00 +00003037 QualType TargetQT = E->getType();
3038 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3039 TargetQT = PT->getPointeeType();
3040
3041 // Check this cast lands within the final derived-to-base subobject path.
3042 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003043 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003044 << D.MostDerivedType << TargetQT;
3045 return false;
3046 }
3047
Richard Smith027bf112011-11-17 22:56:20 +00003048 // Check the type of the final cast. We don't need to check the path,
3049 // since a cast can only be formed if the path is unique.
3050 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003051 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3052 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003053 if (NewEntriesSize == D.MostDerivedPathLength)
3054 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3055 else
Richard Smith027bf112011-11-17 22:56:20 +00003056 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003057 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003058 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003059 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003060 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003061 }
Richard Smith027bf112011-11-17 22:56:20 +00003062
3063 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003064 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003065}
3066
Mike Stump876387b2009-10-27 22:09:17 +00003067namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003068enum EvalStmtResult {
3069 /// Evaluation failed.
3070 ESR_Failed,
3071 /// Hit a 'return' statement.
3072 ESR_Returned,
3073 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003074 ESR_Succeeded,
3075 /// Hit a 'continue' statement.
3076 ESR_Continue,
3077 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003078 ESR_Break,
3079 /// Still scanning for 'case' or 'default' statement.
3080 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003081};
3082}
3083
Richard Smithd9f663b2013-04-22 15:31:51 +00003084static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3085 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3086 // We don't need to evaluate the initializer for a static local.
3087 if (!VD->hasLocalStorage())
3088 return true;
3089
3090 LValue Result;
3091 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003092 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003093
Richard Smith51f03172013-06-20 03:00:05 +00003094 if (!VD->getInit()) {
3095 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3096 << false << VD->getType();
3097 Val = APValue();
3098 return false;
3099 }
3100
Richard Smithd9f663b2013-04-22 15:31:51 +00003101 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3102 // Wipe out any partially-computed value, to allow tracking that this
3103 // evaluation failed.
3104 Val = APValue();
3105 return false;
3106 }
3107 }
3108
3109 return true;
3110}
3111
Richard Smith4e18ca52013-05-06 05:56:11 +00003112/// Evaluate a condition (either a variable declaration or an expression).
3113static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3114 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003115 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003116 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3117 return false;
3118 return EvaluateAsBooleanCondition(Cond, Result, Info);
3119}
3120
3121static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003122 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003123
3124/// Evaluate the body of a loop, and translate the result as appropriate.
3125static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003126 const Stmt *Body,
3127 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003128 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003129 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003130 case ESR_Break:
3131 return ESR_Succeeded;
3132 case ESR_Succeeded:
3133 case ESR_Continue:
3134 return ESR_Continue;
3135 case ESR_Failed:
3136 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003137 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003138 return ESR;
3139 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003140 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003141}
3142
Richard Smith496ddcf2013-05-12 17:32:42 +00003143/// Evaluate a switch statement.
3144static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3145 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003146 BlockScopeRAII Scope(Info);
3147
Richard Smith496ddcf2013-05-12 17:32:42 +00003148 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003149 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003150 {
3151 FullExpressionRAII Scope(Info);
3152 if (SS->getConditionVariable() &&
3153 !EvaluateDecl(Info, SS->getConditionVariable()))
3154 return ESR_Failed;
3155 if (!EvaluateInteger(SS->getCond(), Value, Info))
3156 return ESR_Failed;
3157 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003158
3159 // Find the switch case corresponding to the value of the condition.
3160 // FIXME: Cache this lookup.
3161 const SwitchCase *Found = 0;
3162 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3163 SC = SC->getNextSwitchCase()) {
3164 if (isa<DefaultStmt>(SC)) {
3165 Found = SC;
3166 continue;
3167 }
3168
3169 const CaseStmt *CS = cast<CaseStmt>(SC);
3170 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3171 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3172 : LHS;
3173 if (LHS <= Value && Value <= RHS) {
3174 Found = SC;
3175 break;
3176 }
3177 }
3178
3179 if (!Found)
3180 return ESR_Succeeded;
3181
3182 // Search the switch body for the switch case and evaluate it from there.
3183 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3184 case ESR_Break:
3185 return ESR_Succeeded;
3186 case ESR_Succeeded:
3187 case ESR_Continue:
3188 case ESR_Failed:
3189 case ESR_Returned:
3190 return ESR;
3191 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003192 // This can only happen if the switch case is nested within a statement
3193 // expression. We have no intention of supporting that.
3194 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3195 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003196 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003197 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003198}
3199
Richard Smith254a73d2011-10-28 22:34:42 +00003200// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003201static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003202 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003203 if (!Info.nextStep(S))
3204 return ESR_Failed;
3205
Richard Smith496ddcf2013-05-12 17:32:42 +00003206 // If we're hunting down a 'case' or 'default' label, recurse through
3207 // substatements until we hit the label.
3208 if (Case) {
3209 // FIXME: We don't start the lifetime of objects whose initialization we
3210 // jump over. However, such objects must be of class type with a trivial
3211 // default constructor that initialize all subobjects, so must be empty,
3212 // so this almost never matters.
3213 switch (S->getStmtClass()) {
3214 case Stmt::CompoundStmtClass:
3215 // FIXME: Precompute which substatement of a compound statement we
3216 // would jump to, and go straight there rather than performing a
3217 // linear scan each time.
3218 case Stmt::LabelStmtClass:
3219 case Stmt::AttributedStmtClass:
3220 case Stmt::DoStmtClass:
3221 break;
3222
3223 case Stmt::CaseStmtClass:
3224 case Stmt::DefaultStmtClass:
3225 if (Case == S)
3226 Case = 0;
3227 break;
3228
3229 case Stmt::IfStmtClass: {
3230 // FIXME: Precompute which side of an 'if' we would jump to, and go
3231 // straight there rather than scanning both sides.
3232 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003233
3234 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3235 // preceded by our switch label.
3236 BlockScopeRAII Scope(Info);
3237
Richard Smith496ddcf2013-05-12 17:32:42 +00003238 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3239 if (ESR != ESR_CaseNotFound || !IS->getElse())
3240 return ESR;
3241 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3242 }
3243
3244 case Stmt::WhileStmtClass: {
3245 EvalStmtResult ESR =
3246 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3247 if (ESR != ESR_Continue)
3248 return ESR;
3249 break;
3250 }
3251
3252 case Stmt::ForStmtClass: {
3253 const ForStmt *FS = cast<ForStmt>(S);
3254 EvalStmtResult ESR =
3255 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3256 if (ESR != ESR_Continue)
3257 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003258 if (FS->getInc()) {
3259 FullExpressionRAII IncScope(Info);
3260 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3261 return ESR_Failed;
3262 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003263 break;
3264 }
3265
3266 case Stmt::DeclStmtClass:
3267 // FIXME: If the variable has initialization that can't be jumped over,
3268 // bail out of any immediately-surrounding compound-statement too.
3269 default:
3270 return ESR_CaseNotFound;
3271 }
3272 }
3273
Richard Smith254a73d2011-10-28 22:34:42 +00003274 switch (S->getStmtClass()) {
3275 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003276 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003277 // Don't bother evaluating beyond an expression-statement which couldn't
3278 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003279 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003280 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003281 return ESR_Failed;
3282 return ESR_Succeeded;
3283 }
3284
3285 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003286 return ESR_Failed;
3287
3288 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003289 return ESR_Succeeded;
3290
Richard Smithd9f663b2013-04-22 15:31:51 +00003291 case Stmt::DeclStmtClass: {
3292 const DeclStmt *DS = cast<DeclStmt>(S);
3293 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003294 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3295 // Each declaration initialization is its own full-expression.
3296 // FIXME: This isn't quite right; if we're performing aggregate
3297 // initialization, each braced subexpression is its own full-expression.
3298 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003299 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3300 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003301 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003302 return ESR_Succeeded;
3303 }
3304
Richard Smith357362d2011-12-13 06:39:58 +00003305 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003306 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003307 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003308 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003309 return ESR_Failed;
3310 return ESR_Returned;
3311 }
Richard Smith254a73d2011-10-28 22:34:42 +00003312
3313 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003314 BlockScopeRAII Scope(Info);
3315
Richard Smith254a73d2011-10-28 22:34:42 +00003316 const CompoundStmt *CS = cast<CompoundStmt>(S);
3317 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3318 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003319 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3320 if (ESR == ESR_Succeeded)
3321 Case = 0;
3322 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003323 return ESR;
3324 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003325 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003326 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003327
3328 case Stmt::IfStmtClass: {
3329 const IfStmt *IS = cast<IfStmt>(S);
3330
3331 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003332 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003333 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003334 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003335 return ESR_Failed;
3336
3337 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3338 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3339 if (ESR != ESR_Succeeded)
3340 return ESR;
3341 }
3342 return ESR_Succeeded;
3343 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003344
3345 case Stmt::WhileStmtClass: {
3346 const WhileStmt *WS = cast<WhileStmt>(S);
3347 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003348 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003349 bool Continue;
3350 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3351 Continue))
3352 return ESR_Failed;
3353 if (!Continue)
3354 break;
3355
3356 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3357 if (ESR != ESR_Continue)
3358 return ESR;
3359 }
3360 return ESR_Succeeded;
3361 }
3362
3363 case Stmt::DoStmtClass: {
3364 const DoStmt *DS = cast<DoStmt>(S);
3365 bool Continue;
3366 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003367 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003368 if (ESR != ESR_Continue)
3369 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003370 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003371
Richard Smith08d6a2c2013-07-24 07:11:57 +00003372 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003373 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3374 return ESR_Failed;
3375 } while (Continue);
3376 return ESR_Succeeded;
3377 }
3378
3379 case Stmt::ForStmtClass: {
3380 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003381 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003382 if (FS->getInit()) {
3383 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3384 if (ESR != ESR_Succeeded)
3385 return ESR;
3386 }
3387 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003388 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003389 bool Continue = true;
3390 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3391 FS->getCond(), Continue))
3392 return ESR_Failed;
3393 if (!Continue)
3394 break;
3395
3396 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3397 if (ESR != ESR_Continue)
3398 return ESR;
3399
Richard Smith08d6a2c2013-07-24 07:11:57 +00003400 if (FS->getInc()) {
3401 FullExpressionRAII IncScope(Info);
3402 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3403 return ESR_Failed;
3404 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003405 }
3406 return ESR_Succeeded;
3407 }
3408
Richard Smith896e0d72013-05-06 06:51:17 +00003409 case Stmt::CXXForRangeStmtClass: {
3410 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003411 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003412
3413 // Initialize the __range variable.
3414 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3415 if (ESR != ESR_Succeeded)
3416 return ESR;
3417
3418 // Create the __begin and __end iterators.
3419 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3420 if (ESR != ESR_Succeeded)
3421 return ESR;
3422
3423 while (true) {
3424 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003425 {
3426 bool Continue = true;
3427 FullExpressionRAII CondExpr(Info);
3428 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3429 return ESR_Failed;
3430 if (!Continue)
3431 break;
3432 }
Richard Smith896e0d72013-05-06 06:51:17 +00003433
3434 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003435 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003436 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3437 if (ESR != ESR_Succeeded)
3438 return ESR;
3439
3440 // Loop body.
3441 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3442 if (ESR != ESR_Continue)
3443 return ESR;
3444
3445 // Increment: ++__begin
3446 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3447 return ESR_Failed;
3448 }
3449
3450 return ESR_Succeeded;
3451 }
3452
Richard Smith496ddcf2013-05-12 17:32:42 +00003453 case Stmt::SwitchStmtClass:
3454 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3455
Richard Smith4e18ca52013-05-06 05:56:11 +00003456 case Stmt::ContinueStmtClass:
3457 return ESR_Continue;
3458
3459 case Stmt::BreakStmtClass:
3460 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003461
3462 case Stmt::LabelStmtClass:
3463 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3464
3465 case Stmt::AttributedStmtClass:
3466 // As a general principle, C++11 attributes can be ignored without
3467 // any semantic impact.
3468 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3469 Case);
3470
3471 case Stmt::CaseStmtClass:
3472 case Stmt::DefaultStmtClass:
3473 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003474 }
3475}
3476
Richard Smithcc36f692011-12-22 02:22:31 +00003477/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3478/// default constructor. If so, we'll fold it whether or not it's marked as
3479/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3480/// so we need special handling.
3481static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003482 const CXXConstructorDecl *CD,
3483 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003484 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3485 return false;
3486
Richard Smith66e05fe2012-01-18 05:21:49 +00003487 // Value-initialization does not call a trivial default constructor, so such a
3488 // call is a core constant expression whether or not the constructor is
3489 // constexpr.
3490 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003491 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003492 // FIXME: If DiagDecl is an implicitly-declared special member function,
3493 // we should be much more explicit about why it's not constexpr.
3494 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3495 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3496 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003497 } else {
3498 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3499 }
3500 }
3501 return true;
3502}
3503
Richard Smith357362d2011-12-13 06:39:58 +00003504/// CheckConstexprFunction - Check that a function can be called in a constant
3505/// expression.
3506static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3507 const FunctionDecl *Declaration,
3508 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003509 // Potential constant expressions can contain calls to declared, but not yet
3510 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003511 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003512 Declaration->isConstexpr())
3513 return false;
3514
Richard Smith0838f3a2013-05-14 05:18:44 +00003515 // Bail out with no diagnostic if the function declaration itself is invalid.
3516 // We will have produced a relevant diagnostic while parsing it.
3517 if (Declaration->isInvalidDecl())
3518 return false;
3519
Richard Smith357362d2011-12-13 06:39:58 +00003520 // Can we evaluate this function call?
3521 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3522 return true;
3523
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003524 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003525 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003526 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3527 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003528 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3529 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3530 << DiagDecl;
3531 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3532 } else {
3533 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3534 }
3535 return false;
3536}
3537
Richard Smithd62306a2011-11-10 06:34:14 +00003538namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003539typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003540}
3541
3542/// EvaluateArgs - Evaluate the arguments to a function call.
3543static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3544 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003545 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003546 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003547 I != E; ++I) {
3548 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3549 // If we're checking for a potential constant expression, evaluate all
3550 // initializers even if some of them fail.
3551 if (!Info.keepEvaluatingAfterFailure())
3552 return false;
3553 Success = false;
3554 }
3555 }
3556 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003557}
3558
Richard Smith254a73d2011-10-28 22:34:42 +00003559/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003560static bool HandleFunctionCall(SourceLocation CallLoc,
3561 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003562 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003563 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003564 ArgVector ArgValues(Args.size());
3565 if (!EvaluateArgs(Args, ArgValues, Info))
3566 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003567
Richard Smith253c2a32012-01-27 01:14:48 +00003568 if (!Info.CheckCallLimit(CallLoc))
3569 return false;
3570
3571 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003572
3573 // For a trivial copy or move assignment, perform an APValue copy. This is
3574 // essential for unions, where the operations performed by the assignment
3575 // operator cannot be represented as statements.
3576 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3577 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3578 assert(This &&
3579 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3580 LValue RHS;
3581 RHS.setFrom(Info.Ctx, ArgValues[0]);
3582 APValue RHSValue;
3583 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3584 RHS, RHSValue))
3585 return false;
3586 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3587 RHSValue))
3588 return false;
3589 This->moveInto(Result);
3590 return true;
3591 }
3592
Richard Smithd9f663b2013-04-22 15:31:51 +00003593 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003594 if (ESR == ESR_Succeeded) {
3595 if (Callee->getResultType()->isVoidType())
3596 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003597 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003598 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003599 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003600}
3601
Richard Smithd62306a2011-11-10 06:34:14 +00003602/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003603static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003604 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003605 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003606 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003607 ArgVector ArgValues(Args.size());
3608 if (!EvaluateArgs(Args, ArgValues, Info))
3609 return false;
3610
Richard Smith253c2a32012-01-27 01:14:48 +00003611 if (!Info.CheckCallLimit(CallLoc))
3612 return false;
3613
Richard Smith3607ffe2012-02-13 03:54:03 +00003614 const CXXRecordDecl *RD = Definition->getParent();
3615 if (RD->getNumVBases()) {
3616 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3617 return false;
3618 }
3619
Richard Smith253c2a32012-01-27 01:14:48 +00003620 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003621
3622 // If it's a delegating constructor, just delegate.
3623 if (Definition->isDelegatingConstructor()) {
3624 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003625 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3626 return false;
3627 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003628 }
3629
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003630 // For a trivial copy or move constructor, perform an APValue copy. This is
3631 // essential for unions, where the operations performed by the constructor
3632 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003633 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003634 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3635 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003636 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003637 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003638 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003639 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003640 }
3641
3642 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003643 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003644 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3645 std::distance(RD->field_begin(), RD->field_end()));
3646
John McCalld7bca762012-05-01 00:38:49 +00003647 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003648 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3649
Richard Smith08d6a2c2013-07-24 07:11:57 +00003650 // A scope for temporaries lifetime-extended by reference members.
3651 BlockScopeRAII LifetimeExtendedScope(Info);
3652
Richard Smith253c2a32012-01-27 01:14:48 +00003653 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003654 unsigned BasesSeen = 0;
3655#ifndef NDEBUG
3656 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3657#endif
3658 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3659 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003660 LValue Subobject = This;
3661 APValue *Value = &Result;
3662
3663 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003664 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003665 if ((*I)->isBaseInitializer()) {
3666 QualType BaseType((*I)->getBaseClass(), 0);
3667#ifndef NDEBUG
3668 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003669 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003670 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3671 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3672 "base class initializers not in expected order");
3673 ++BaseIt;
3674#endif
John McCalld7bca762012-05-01 00:38:49 +00003675 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3676 BaseType->getAsCXXRecordDecl(), &Layout))
3677 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003678 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003679 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003680 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3681 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003682 if (RD->isUnion()) {
3683 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003684 Value = &Result.getUnionValue();
3685 } else {
3686 Value = &Result.getStructField(FD->getFieldIndex());
3687 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003688 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003689 // Walk the indirect field decl's chain to find the object to initialize,
3690 // and make sure we've initialized every step along it.
3691 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3692 CE = IFD->chain_end();
3693 C != CE; ++C) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003694 FD = cast<FieldDecl>(*C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003695 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3696 // Switch the union field if it differs. This happens if we had
3697 // preceding zero-initialization, and we're now initializing a union
3698 // subobject other than the first.
3699 // FIXME: In this case, the values of the other subobjects are
3700 // specified, since zero-initialization sets all padding bits to zero.
3701 if (Value->isUninit() ||
3702 (Value->isUnion() && Value->getUnionField() != FD)) {
3703 if (CD->isUnion())
3704 *Value = APValue(FD);
3705 else
3706 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3707 std::distance(CD->field_begin(), CD->field_end()));
3708 }
John McCalld7bca762012-05-01 00:38:49 +00003709 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3710 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003711 if (CD->isUnion())
3712 Value = &Value->getUnionValue();
3713 else
3714 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003715 }
Richard Smithd62306a2011-11-10 06:34:14 +00003716 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003717 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003718 }
Richard Smith253c2a32012-01-27 01:14:48 +00003719
Richard Smith08d6a2c2013-07-24 07:11:57 +00003720 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003721 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3722 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3723 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003724 // If we're checking for a potential constant expression, evaluate all
3725 // initializers even if some of them fail.
3726 if (!Info.keepEvaluatingAfterFailure())
3727 return false;
3728 Success = false;
3729 }
Richard Smithd62306a2011-11-10 06:34:14 +00003730 }
3731
Richard Smithd9f663b2013-04-22 15:31:51 +00003732 return Success &&
3733 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003734}
3735
Eli Friedman9a156e52008-11-12 09:44:48 +00003736//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003737// Generic Evaluation
3738//===----------------------------------------------------------------------===//
3739namespace {
3740
Richard Smithf57d8cb2011-12-09 22:58:01 +00003741// FIXME: RetTy is always bool. Remove it.
3742template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003743class ExprEvaluatorBase
3744 : public ConstStmtVisitor<Derived, RetTy> {
3745private:
Richard Smith2e312c82012-03-03 22:46:17 +00003746 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003747 return static_cast<Derived*>(this)->Success(V, E);
3748 }
Richard Smithfddd3842011-12-30 21:15:51 +00003749 RetTy DerivedZeroInitialization(const Expr *E) {
3750 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003751 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003752
Richard Smith17100ba2012-02-16 02:46:34 +00003753 // Check whether a conditional operator with a non-constant condition is a
3754 // potential constant expression. If neither arm is a potential constant
3755 // expression, then the conditional operator is not either.
3756 template<typename ConditionalOperator>
3757 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003758 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003759
3760 // Speculatively evaluate both arms.
3761 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003762 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003763 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3764
3765 StmtVisitorTy::Visit(E->getFalseExpr());
3766 if (Diag.empty())
3767 return;
3768
3769 Diag.clear();
3770 StmtVisitorTy::Visit(E->getTrueExpr());
3771 if (Diag.empty())
3772 return;
3773 }
3774
3775 Error(E, diag::note_constexpr_conditional_never_const);
3776 }
3777
3778
3779 template<typename ConditionalOperator>
3780 bool HandleConditionalOperator(const ConditionalOperator *E) {
3781 bool BoolResult;
3782 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003783 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003784 CheckPotentialConstantConditional(E);
3785 return false;
3786 }
3787
3788 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3789 return StmtVisitorTy::Visit(EvalExpr);
3790 }
3791
Peter Collingbournee9200682011-05-13 03:29:01 +00003792protected:
3793 EvalInfo &Info;
3794 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3795 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3796
Richard Smith92b1ce02011-12-12 09:28:41 +00003797 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003798 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003799 }
3800
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003801 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3802
3803public:
3804 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3805
3806 EvalInfo &getEvalInfo() { return Info; }
3807
Richard Smithf57d8cb2011-12-09 22:58:01 +00003808 /// Report an evaluation error. This should only be called when an error is
3809 /// first discovered. When propagating an error, just return false.
3810 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003811 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003812 return false;
3813 }
3814 bool Error(const Expr *E) {
3815 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3816 }
3817
Peter Collingbournee9200682011-05-13 03:29:01 +00003818 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003819 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003820 }
3821 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003823 }
3824
3825 RetTy VisitParenExpr(const ParenExpr *E)
3826 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3827 RetTy VisitUnaryExtension(const UnaryOperator *E)
3828 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3829 RetTy VisitUnaryPlus(const UnaryOperator *E)
3830 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3831 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003832 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003833 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3834 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003835 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3836 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003837 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3838 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith17e32462013-09-13 20:51:45 +00003839 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3840 // The initializer may not have been parsed yet, or might be erroneous.
3841 if (!E->getExpr())
3842 return Error(E);
3843 return StmtVisitorTy::Visit(E->getExpr());
3844 }
Richard Smith5894a912011-12-19 22:12:41 +00003845 // We cannot create any objects for which cleanups are required, so there is
3846 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3847 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3848 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003849
Richard Smith6d6ecc32011-12-12 12:46:16 +00003850 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3851 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3852 return static_cast<Derived*>(this)->VisitCastExpr(E);
3853 }
3854 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3855 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3856 return static_cast<Derived*>(this)->VisitCastExpr(E);
3857 }
3858
Richard Smith027bf112011-11-17 22:56:20 +00003859 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3860 switch (E->getOpcode()) {
3861 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003862 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003863
3864 case BO_Comma:
3865 VisitIgnoredValue(E->getLHS());
3866 return StmtVisitorTy::Visit(E->getRHS());
3867
3868 case BO_PtrMemD:
3869 case BO_PtrMemI: {
3870 LValue Obj;
3871 if (!HandleMemberPointerAccess(Info, E, Obj))
3872 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003873 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003874 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003875 return false;
3876 return DerivedSuccess(Result, E);
3877 }
3878 }
3879 }
3880
Peter Collingbournee9200682011-05-13 03:29:01 +00003881 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003882 // Evaluate and cache the common expression. We treat it as a temporary,
3883 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003884 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003885 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003886 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003887
Richard Smith17100ba2012-02-16 02:46:34 +00003888 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003889 }
3890
3891 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003892 bool IsBcpCall = false;
3893 // If the condition (ignoring parens) is a __builtin_constant_p call,
3894 // the result is a constant expression if it can be folded without
3895 // side-effects. This is an important GNU extension. See GCC PR38377
3896 // for discussion.
3897 if (const CallExpr *CallCE =
3898 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3899 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3900 IsBcpCall = true;
3901
3902 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3903 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003904 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003905 return false;
3906
Richard Smith6d4c6582013-11-05 22:18:15 +00003907 FoldConstant Fold(Info, IsBcpCall);
3908 if (!HandleConditionalOperator(E)) {
3909 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003910 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003911 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003912
3913 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003914 }
3915
3916 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003917 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3918 return DerivedSuccess(*Value, E);
3919
3920 const Expr *Source = E->getSourceExpr();
3921 if (!Source)
3922 return Error(E);
3923 if (Source == E) { // sanity checking.
3924 assert(0 && "OpaqueValueExpr recursively refers to itself");
3925 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003926 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003927 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003928 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003929
Richard Smith254a73d2011-10-28 22:34:42 +00003930 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003931 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003932 QualType CalleeType = Callee->getType();
3933
Richard Smith254a73d2011-10-28 22:34:42 +00003934 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003935 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003936 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003937 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003938
Richard Smithe97cbd72011-11-11 04:05:33 +00003939 // Extract function decl and 'this' pointer from the callee.
3940 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003941 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003942 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3943 // Explicit bound member calls, such as x.f() or p->g();
3944 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003945 return false;
3946 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003947 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003948 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003949 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3950 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003951 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3952 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003953 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003954 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003955 return Error(Callee);
3956
3957 FD = dyn_cast<FunctionDecl>(Member);
3958 if (!FD)
3959 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003960 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003961 LValue Call;
3962 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003963 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003964
Richard Smitha8105bc2012-01-06 16:39:00 +00003965 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003966 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003967 FD = dyn_cast_or_null<FunctionDecl>(
3968 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003969 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003970 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003971
3972 // Overloaded operator calls to member functions are represented as normal
3973 // calls with '*this' as the first argument.
3974 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3975 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003976 // FIXME: When selecting an implicit conversion for an overloaded
3977 // operator delete, we sometimes try to evaluate calls to conversion
3978 // operators without a 'this' parameter!
3979 if (Args.empty())
3980 return Error(E);
3981
Richard Smithe97cbd72011-11-11 04:05:33 +00003982 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3983 return false;
3984 This = &ThisVal;
3985 Args = Args.slice(1);
3986 }
3987
3988 // Don't call function pointers which have been cast to some other type.
3989 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003990 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003991 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003992 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003993
Richard Smith47b34932012-02-01 02:39:43 +00003994 if (This && !This->checkSubobject(Info, E, CSK_This))
3995 return false;
3996
Richard Smith3607ffe2012-02-13 03:54:03 +00003997 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3998 // calls to such functions in constant expressions.
3999 if (This && !HasQualifier &&
4000 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4001 return Error(E, diag::note_constexpr_virtual_call);
4002
Richard Smith357362d2011-12-13 06:39:58 +00004003 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004004 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004005 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004006
Richard Smith357362d2011-12-13 06:39:58 +00004007 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004008 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4009 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004010 return false;
4011
Richard Smithb228a862012-02-15 02:18:13 +00004012 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004013 }
4014
Richard Smith11562c52011-10-28 17:51:58 +00004015 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4016 return StmtVisitorTy::Visit(E->getInitializer());
4017 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004018 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004019 if (E->getNumInits() == 0)
4020 return DerivedZeroInitialization(E);
4021 if (E->getNumInits() == 1)
4022 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004023 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004024 }
4025 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004026 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004027 }
4028 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004029 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004030 }
Richard Smith027bf112011-11-17 22:56:20 +00004031 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004032 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004033 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004034
Richard Smithd62306a2011-11-10 06:34:14 +00004035 /// A member expression where the object is a prvalue is itself a prvalue.
4036 RetTy VisitMemberExpr(const MemberExpr *E) {
4037 assert(!E->isArrow() && "missing call to bound member function?");
4038
Richard Smith2e312c82012-03-03 22:46:17 +00004039 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004040 if (!Evaluate(Val, Info, E->getBase()))
4041 return false;
4042
4043 QualType BaseTy = E->getBase()->getType();
4044
4045 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004046 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004047 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004048 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004049 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4050
Richard Smith3229b742013-05-05 21:17:10 +00004051 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004052 SubobjectDesignator Designator(BaseTy);
4053 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004054
Richard Smith3229b742013-05-05 21:17:10 +00004055 APValue Result;
4056 return extractSubobject(Info, E, Obj, Designator, Result) &&
4057 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004058 }
4059
Richard Smith11562c52011-10-28 17:51:58 +00004060 RetTy VisitCastExpr(const CastExpr *E) {
4061 switch (E->getCastKind()) {
4062 default:
4063 break;
4064
Richard Smitha23ab512013-05-23 00:30:41 +00004065 case CK_AtomicToNonAtomic: {
4066 APValue AtomicVal;
4067 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4068 return false;
4069 return DerivedSuccess(AtomicVal, E);
4070 }
4071
Richard Smith11562c52011-10-28 17:51:58 +00004072 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004073 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004074 return StmtVisitorTy::Visit(E->getSubExpr());
4075
4076 case CK_LValueToRValue: {
4077 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004078 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4079 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004080 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004081 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004082 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004083 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004084 return false;
4085 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004086 }
4087 }
4088
Richard Smithf57d8cb2011-12-09 22:58:01 +00004089 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004090 }
4091
Richard Smith243ef902013-05-05 23:31:59 +00004092 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4093 return VisitUnaryPostIncDec(UO);
4094 }
4095 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4096 return VisitUnaryPostIncDec(UO);
4097 }
4098 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4099 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4100 return Error(UO);
4101
4102 LValue LVal;
4103 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4104 return false;
4105 APValue RVal;
4106 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4107 UO->isIncrementOp(), &RVal))
4108 return false;
4109 return DerivedSuccess(RVal, UO);
4110 }
4111
Richard Smith51f03172013-06-20 03:00:05 +00004112 RetTy VisitStmtExpr(const StmtExpr *E) {
4113 // We will have checked the full-expressions inside the statement expression
4114 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004115 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004116 return Error(E);
4117
Richard Smith08d6a2c2013-07-24 07:11:57 +00004118 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004119 const CompoundStmt *CS = E->getSubStmt();
4120 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4121 BE = CS->body_end();
4122 /**/; ++BI) {
4123 if (BI + 1 == BE) {
4124 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4125 if (!FinalExpr) {
4126 Info.Diag((*BI)->getLocStart(),
4127 diag::note_constexpr_stmt_expr_unsupported);
4128 return false;
4129 }
4130 return this->Visit(FinalExpr);
4131 }
4132
4133 APValue ReturnValue;
4134 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4135 if (ESR != ESR_Succeeded) {
4136 // FIXME: If the statement-expression terminated due to 'return',
4137 // 'break', or 'continue', it would be nice to propagate that to
4138 // the outer statement evaluation rather than bailing out.
4139 if (ESR != ESR_Failed)
4140 Info.Diag((*BI)->getLocStart(),
4141 diag::note_constexpr_stmt_expr_unsupported);
4142 return false;
4143 }
4144 }
4145 }
4146
Richard Smith4a678122011-10-24 18:44:57 +00004147 /// Visit a value which is evaluated, but whose value is ignored.
4148 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004149 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004150 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004151};
4152
4153}
4154
4155//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004156// Common base class for lvalue and temporary evaluation.
4157//===----------------------------------------------------------------------===//
4158namespace {
4159template<class Derived>
4160class LValueExprEvaluatorBase
4161 : public ExprEvaluatorBase<Derived, bool> {
4162protected:
4163 LValue &Result;
4164 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4165 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4166
4167 bool Success(APValue::LValueBase B) {
4168 Result.set(B);
4169 return true;
4170 }
4171
4172public:
4173 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4174 ExprEvaluatorBaseTy(Info), Result(Result) {}
4175
Richard Smith2e312c82012-03-03 22:46:17 +00004176 bool Success(const APValue &V, const Expr *E) {
4177 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004178 return true;
4179 }
Richard Smith027bf112011-11-17 22:56:20 +00004180
Richard Smith027bf112011-11-17 22:56:20 +00004181 bool VisitMemberExpr(const MemberExpr *E) {
4182 // Handle non-static data members.
4183 QualType BaseTy;
4184 if (E->isArrow()) {
4185 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4186 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004187 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004188 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004189 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004190 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4191 return false;
4192 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004193 } else {
4194 if (!this->Visit(E->getBase()))
4195 return false;
4196 BaseTy = E->getBase()->getType();
4197 }
Richard Smith027bf112011-11-17 22:56:20 +00004198
Richard Smith1b78b3d2012-01-25 22:15:11 +00004199 const ValueDecl *MD = E->getMemberDecl();
4200 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4201 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4202 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4203 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004204 if (!HandleLValueMember(this->Info, E, Result, FD))
4205 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004206 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004207 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4208 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004209 } else
4210 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004211
Richard Smith1b78b3d2012-01-25 22:15:11 +00004212 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004213 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004214 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004215 RefValue))
4216 return false;
4217 return Success(RefValue, E);
4218 }
4219 return true;
4220 }
4221
4222 bool VisitBinaryOperator(const BinaryOperator *E) {
4223 switch (E->getOpcode()) {
4224 default:
4225 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4226
4227 case BO_PtrMemD:
4228 case BO_PtrMemI:
4229 return HandleMemberPointerAccess(this->Info, E, Result);
4230 }
4231 }
4232
4233 bool VisitCastExpr(const CastExpr *E) {
4234 switch (E->getCastKind()) {
4235 default:
4236 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4237
4238 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004239 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004240 if (!this->Visit(E->getSubExpr()))
4241 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004242
4243 // Now figure out the necessary offset to add to the base LV to get from
4244 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004245 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4246 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004247 }
4248 }
4249};
4250}
4251
4252//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004253// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004254//
4255// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4256// function designators (in C), decl references to void objects (in C), and
4257// temporaries (if building with -Wno-address-of-temporary).
4258//
4259// LValue evaluation produces values comprising a base expression of one of the
4260// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004261// - Declarations
4262// * VarDecl
4263// * FunctionDecl
4264// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004265// * CompoundLiteralExpr in C
4266// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004267// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004268// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004269// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004270// * ObjCEncodeExpr
4271// * AddrLabelExpr
4272// * BlockExpr
4273// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004274// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004275// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004276// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004277// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4278// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004279// * A MaterializeTemporaryExpr that has static storage duration, with no
4280// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004281// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004282//===----------------------------------------------------------------------===//
4283namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004284class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004285 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004286public:
Richard Smith027bf112011-11-17 22:56:20 +00004287 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4288 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004289
Richard Smith11562c52011-10-28 17:51:58 +00004290 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004291 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004292
Peter Collingbournee9200682011-05-13 03:29:01 +00004293 bool VisitDeclRefExpr(const DeclRefExpr *E);
4294 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004295 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004296 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4297 bool VisitMemberExpr(const MemberExpr *E);
4298 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4299 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004300 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004301 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004302 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4303 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004304 bool VisitUnaryReal(const UnaryOperator *E);
4305 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004306 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4307 return VisitUnaryPreIncDec(UO);
4308 }
4309 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4310 return VisitUnaryPreIncDec(UO);
4311 }
Richard Smith3229b742013-05-05 21:17:10 +00004312 bool VisitBinAssign(const BinaryOperator *BO);
4313 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004314
Peter Collingbournee9200682011-05-13 03:29:01 +00004315 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004316 switch (E->getCastKind()) {
4317 default:
Richard Smith027bf112011-11-17 22:56:20 +00004318 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004319
Eli Friedmance3e02a2011-10-11 00:13:24 +00004320 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004321 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004322 if (!Visit(E->getSubExpr()))
4323 return false;
4324 Result.Designator.setInvalid();
4325 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004326
Richard Smith027bf112011-11-17 22:56:20 +00004327 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004328 if (!Visit(E->getSubExpr()))
4329 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004330 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004331 }
4332 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004333};
4334} // end anonymous namespace
4335
Richard Smith11562c52011-10-28 17:51:58 +00004336/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004337/// expressions which are not glvalues, in two cases:
4338/// * function designators in C, and
4339/// * "extern void" objects
4340static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4341 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4342 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004343 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004344}
4345
Peter Collingbournee9200682011-05-13 03:29:01 +00004346bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004347 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4348 return Success(FD);
4349 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004350 return VisitVarDecl(E, VD);
4351 return Error(E);
4352}
Richard Smith733237d2011-10-24 23:14:33 +00004353
Richard Smith11562c52011-10-28 17:51:58 +00004354bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004355 CallStackFrame *Frame = 0;
4356 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4357 Frame = Info.CurrentCall;
4358
Richard Smithfec09922011-11-01 16:57:24 +00004359 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004360 if (Frame) {
4361 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004362 return true;
4363 }
Richard Smithce40ad62011-11-12 22:28:03 +00004364 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004365 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004366
Richard Smith3229b742013-05-05 21:17:10 +00004367 APValue *V;
4368 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004369 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004370 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004371 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004372 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4373 return false;
4374 }
Richard Smith3229b742013-05-05 21:17:10 +00004375 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004376}
4377
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004378bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4379 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004380 // Walk through the expression to find the materialized temporary itself.
4381 SmallVector<const Expr *, 2> CommaLHSs;
4382 SmallVector<SubobjectAdjustment, 2> Adjustments;
4383 const Expr *Inner = E->GetTemporaryExpr()->
4384 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004385
Richard Smith84401042013-06-03 05:03:02 +00004386 // If we passed any comma operators, evaluate their LHSs.
4387 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4388 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4389 return false;
4390
Richard Smithe6c01442013-06-05 00:46:14 +00004391 // A materialized temporary with static storage duration can appear within the
4392 // result of a constant expression evaluation, so we need to preserve its
4393 // value for use outside this evaluation.
4394 APValue *Value;
4395 if (E->getStorageDuration() == SD_Static) {
4396 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004397 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004398 Result.set(E);
4399 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004400 Value = &Info.CurrentCall->
4401 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004402 Result.set(E, Info.CurrentCall->Index);
4403 }
4404
Richard Smithea4ad5d2013-06-06 08:19:16 +00004405 QualType Type = Inner->getType();
4406
Richard Smith84401042013-06-03 05:03:02 +00004407 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004408 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4409 (E->getStorageDuration() == SD_Static &&
4410 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4411 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004412 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004413 }
Richard Smith84401042013-06-03 05:03:02 +00004414
4415 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004416 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4417 --I;
4418 switch (Adjustments[I].Kind) {
4419 case SubobjectAdjustment::DerivedToBaseAdjustment:
4420 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4421 Type, Result))
4422 return false;
4423 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4424 break;
4425
4426 case SubobjectAdjustment::FieldAdjustment:
4427 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4428 return false;
4429 Type = Adjustments[I].Field->getType();
4430 break;
4431
4432 case SubobjectAdjustment::MemberPointerAdjustment:
4433 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4434 Adjustments[I].Ptr.RHS))
4435 return false;
4436 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4437 break;
4438 }
4439 }
4440
4441 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004442}
4443
Peter Collingbournee9200682011-05-13 03:29:01 +00004444bool
4445LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004446 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4447 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4448 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004449 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004450}
4451
Richard Smith6e525142011-12-27 12:18:28 +00004452bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004453 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004454 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004455
4456 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4457 << E->getExprOperand()->getType()
4458 << E->getExprOperand()->getSourceRange();
4459 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004460}
4461
Francois Pichet0066db92012-04-16 04:08:35 +00004462bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4463 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004464}
Francois Pichet0066db92012-04-16 04:08:35 +00004465
Peter Collingbournee9200682011-05-13 03:29:01 +00004466bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004467 // Handle static data members.
4468 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4469 VisitIgnoredValue(E->getBase());
4470 return VisitVarDecl(E, VD);
4471 }
4472
Richard Smith254a73d2011-10-28 22:34:42 +00004473 // Handle static member functions.
4474 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4475 if (MD->isStatic()) {
4476 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004477 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004478 }
4479 }
4480
Richard Smithd62306a2011-11-10 06:34:14 +00004481 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004482 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004483}
4484
Peter Collingbournee9200682011-05-13 03:29:01 +00004485bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004486 // FIXME: Deal with vectors as array subscript bases.
4487 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004488 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004489
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004490 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004491 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004492
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004493 APSInt Index;
4494 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004495 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004496
Richard Smith861b5b52013-05-07 23:34:45 +00004497 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4498 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004499}
Eli Friedman9a156e52008-11-12 09:44:48 +00004500
Peter Collingbournee9200682011-05-13 03:29:01 +00004501bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004502 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004503}
4504
Richard Smith66c96992012-02-18 22:04:06 +00004505bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4506 if (!Visit(E->getSubExpr()))
4507 return false;
4508 // __real is a no-op on scalar lvalues.
4509 if (E->getSubExpr()->getType()->isAnyComplexType())
4510 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4511 return true;
4512}
4513
4514bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4515 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4516 "lvalue __imag__ on scalar?");
4517 if (!Visit(E->getSubExpr()))
4518 return false;
4519 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4520 return true;
4521}
4522
Richard Smith243ef902013-05-05 23:31:59 +00004523bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4524 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004525 return Error(UO);
4526
4527 if (!this->Visit(UO->getSubExpr()))
4528 return false;
4529
Richard Smith243ef902013-05-05 23:31:59 +00004530 return handleIncDec(
4531 this->Info, UO, Result, UO->getSubExpr()->getType(),
4532 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004533}
4534
4535bool LValueExprEvaluator::VisitCompoundAssignOperator(
4536 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004537 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004538 return Error(CAO);
4539
Richard Smith3229b742013-05-05 21:17:10 +00004540 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004541
4542 // The overall lvalue result is the result of evaluating the LHS.
4543 if (!this->Visit(CAO->getLHS())) {
4544 if (Info.keepEvaluatingAfterFailure())
4545 Evaluate(RHS, this->Info, CAO->getRHS());
4546 return false;
4547 }
4548
Richard Smith3229b742013-05-05 21:17:10 +00004549 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4550 return false;
4551
Richard Smith43e77732013-05-07 04:50:00 +00004552 return handleCompoundAssignment(
4553 this->Info, CAO,
4554 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4555 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004556}
4557
4558bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004559 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4560 return Error(E);
4561
Richard Smith3229b742013-05-05 21:17:10 +00004562 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004563
4564 if (!this->Visit(E->getLHS())) {
4565 if (Info.keepEvaluatingAfterFailure())
4566 Evaluate(NewVal, this->Info, E->getRHS());
4567 return false;
4568 }
4569
Richard Smith3229b742013-05-05 21:17:10 +00004570 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4571 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004572
4573 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004574 NewVal);
4575}
4576
Eli Friedman9a156e52008-11-12 09:44:48 +00004577//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004578// Pointer Evaluation
4579//===----------------------------------------------------------------------===//
4580
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004581namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004582class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004583 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004584 LValue &Result;
4585
Peter Collingbournee9200682011-05-13 03:29:01 +00004586 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004587 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004588 return true;
4589 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004590public:
Mike Stump11289f42009-09-09 15:08:12 +00004591
John McCall45d55e42010-05-07 21:00:08 +00004592 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004594
Richard Smith2e312c82012-03-03 22:46:17 +00004595 bool Success(const APValue &V, const Expr *E) {
4596 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004597 return true;
4598 }
Richard Smithfddd3842011-12-30 21:15:51 +00004599 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004600 return Success((Expr*)0);
4601 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004602
John McCall45d55e42010-05-07 21:00:08 +00004603 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004604 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004605 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004606 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004607 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004608 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004609 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004610 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004611 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004612 bool VisitCallExpr(const CallExpr *E);
4613 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004614 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004615 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004616 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004617 }
Richard Smithd62306a2011-11-10 06:34:14 +00004618 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004619 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004620 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004621 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004622 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004623 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004624 Result = *Info.CurrentCall->This;
4625 return true;
4626 }
John McCallc07a0c72011-02-17 10:25:35 +00004627
Eli Friedman449fe542009-03-23 04:56:01 +00004628 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004629};
Chris Lattner05706e882008-07-11 18:11:29 +00004630} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004631
John McCall45d55e42010-05-07 21:00:08 +00004632static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004633 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004634 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004635}
4636
John McCall45d55e42010-05-07 21:00:08 +00004637bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004638 if (E->getOpcode() != BO_Add &&
4639 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004640 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004641
Chris Lattner05706e882008-07-11 18:11:29 +00004642 const Expr *PExp = E->getLHS();
4643 const Expr *IExp = E->getRHS();
4644 if (IExp->getType()->isPointerType())
4645 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004646
Richard Smith253c2a32012-01-27 01:14:48 +00004647 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4648 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004649 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004650
John McCall45d55e42010-05-07 21:00:08 +00004651 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004652 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004653 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004654
4655 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004656 if (E->getOpcode() == BO_Sub)
4657 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004658
Ted Kremenek28831752012-08-23 20:46:57 +00004659 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004660 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4661 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004662}
Eli Friedman9a156e52008-11-12 09:44:48 +00004663
John McCall45d55e42010-05-07 21:00:08 +00004664bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4665 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004666}
Mike Stump11289f42009-09-09 15:08:12 +00004667
Peter Collingbournee9200682011-05-13 03:29:01 +00004668bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4669 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004670
Eli Friedman847a2bc2009-12-27 05:43:15 +00004671 switch (E->getCastKind()) {
4672 default:
4673 break;
4674
John McCalle3027922010-08-25 11:45:40 +00004675 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004676 case CK_CPointerToObjCPointerCast:
4677 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004678 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004679 if (!Visit(SubExpr))
4680 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004681 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4682 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4683 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004684 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004685 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004686 if (SubExpr->getType()->isVoidPointerType())
4687 CCEDiag(E, diag::note_constexpr_invalid_cast)
4688 << 3 << SubExpr->getType();
4689 else
4690 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4691 }
Richard Smith96e0c102011-11-04 02:25:55 +00004692 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004693
Anders Carlsson18275092010-10-31 20:41:46 +00004694 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004695 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004696 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004697 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004698 if (!Result.Base && Result.Offset.isZero())
4699 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004700
Richard Smithd62306a2011-11-10 06:34:14 +00004701 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004702 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004703 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4704 castAs<PointerType>()->getPointeeType(),
4705 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004706
Richard Smith027bf112011-11-17 22:56:20 +00004707 case CK_BaseToDerived:
4708 if (!Visit(E->getSubExpr()))
4709 return false;
4710 if (!Result.Base && Result.Offset.isZero())
4711 return true;
4712 return HandleBaseToDerivedCast(Info, E, Result);
4713
Richard Smith0b0a0b62011-10-29 20:57:55 +00004714 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004715 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004716 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004717
John McCalle3027922010-08-25 11:45:40 +00004718 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4720
Richard Smith2e312c82012-03-03 22:46:17 +00004721 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004722 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004723 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004724
John McCall45d55e42010-05-07 21:00:08 +00004725 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004726 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4727 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004728 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004729 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004730 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004731 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004732 return true;
4733 } else {
4734 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004735 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004736 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004737 }
4738 }
John McCalle3027922010-08-25 11:45:40 +00004739 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004740 if (SubExpr->isGLValue()) {
4741 if (!EvaluateLValue(SubExpr, Result, Info))
4742 return false;
4743 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004744 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004745 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004746 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004747 return false;
4748 }
Richard Smith96e0c102011-11-04 02:25:55 +00004749 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004750 if (const ConstantArrayType *CAT
4751 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4752 Result.addArray(Info, E, CAT);
4753 else
4754 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004755 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004756
John McCalle3027922010-08-25 11:45:40 +00004757 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004758 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004759 }
4760
Richard Smith11562c52011-10-28 17:51:58 +00004761 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004762}
Chris Lattner05706e882008-07-11 18:11:29 +00004763
Peter Collingbournee9200682011-05-13 03:29:01 +00004764bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004765 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004766 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004767
Richard Smith6cbd65d2013-07-11 02:27:57 +00004768 switch (E->isBuiltinCall()) {
4769 case Builtin::BI__builtin_addressof:
4770 return EvaluateLValue(E->getArg(0), Result, Info);
4771
4772 default:
4773 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4774 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004775}
Chris Lattner05706e882008-07-11 18:11:29 +00004776
4777//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004778// Member Pointer Evaluation
4779//===----------------------------------------------------------------------===//
4780
4781namespace {
4782class MemberPointerExprEvaluator
4783 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4784 MemberPtr &Result;
4785
4786 bool Success(const ValueDecl *D) {
4787 Result = MemberPtr(D);
4788 return true;
4789 }
4790public:
4791
4792 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4793 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4794
Richard Smith2e312c82012-03-03 22:46:17 +00004795 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004796 Result.setFrom(V);
4797 return true;
4798 }
Richard Smithfddd3842011-12-30 21:15:51 +00004799 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004800 return Success((const ValueDecl*)0);
4801 }
4802
4803 bool VisitCastExpr(const CastExpr *E);
4804 bool VisitUnaryAddrOf(const UnaryOperator *E);
4805};
4806} // end anonymous namespace
4807
4808static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4809 EvalInfo &Info) {
4810 assert(E->isRValue() && E->getType()->isMemberPointerType());
4811 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4812}
4813
4814bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4815 switch (E->getCastKind()) {
4816 default:
4817 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4818
4819 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004820 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004821 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004822
4823 case CK_BaseToDerivedMemberPointer: {
4824 if (!Visit(E->getSubExpr()))
4825 return false;
4826 if (E->path_empty())
4827 return true;
4828 // Base-to-derived member pointer casts store the path in derived-to-base
4829 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4830 // the wrong end of the derived->base arc, so stagger the path by one class.
4831 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4832 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4833 PathI != PathE; ++PathI) {
4834 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4835 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4836 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004837 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004838 }
4839 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4840 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004841 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004842 return true;
4843 }
4844
4845 case CK_DerivedToBaseMemberPointer:
4846 if (!Visit(E->getSubExpr()))
4847 return false;
4848 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4849 PathE = E->path_end(); PathI != PathE; ++PathI) {
4850 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4851 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4852 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004853 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004854 }
4855 return true;
4856 }
4857}
4858
4859bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4860 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4861 // member can be formed.
4862 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4863}
4864
4865//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004866// Record Evaluation
4867//===----------------------------------------------------------------------===//
4868
4869namespace {
4870 class RecordExprEvaluator
4871 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4872 const LValue &This;
4873 APValue &Result;
4874 public:
4875
4876 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4877 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4878
Richard Smith2e312c82012-03-03 22:46:17 +00004879 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004880 Result = V;
4881 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004882 }
Richard Smithfddd3842011-12-30 21:15:51 +00004883 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004884
Richard Smithe97cbd72011-11-11 04:05:33 +00004885 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004886 bool VisitInitListExpr(const InitListExpr *E);
4887 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004888 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004889 };
4890}
4891
Richard Smithfddd3842011-12-30 21:15:51 +00004892/// Perform zero-initialization on an object of non-union class type.
4893/// C++11 [dcl.init]p5:
4894/// To zero-initialize an object or reference of type T means:
4895/// [...]
4896/// -- if T is a (possibly cv-qualified) non-union class type,
4897/// each non-static data member and each base-class subobject is
4898/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004899static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4900 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004901 const LValue &This, APValue &Result) {
4902 assert(!RD->isUnion() && "Expected non-union class type");
4903 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4904 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4905 std::distance(RD->field_begin(), RD->field_end()));
4906
John McCalld7bca762012-05-01 00:38:49 +00004907 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004908 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4909
4910 if (CD) {
4911 unsigned Index = 0;
4912 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004913 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004914 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4915 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004916 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4917 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004918 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004919 Result.getStructBase(Index)))
4920 return false;
4921 }
4922 }
4923
Richard Smitha8105bc2012-01-06 16:39:00 +00004924 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4925 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004926 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004927 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004928 continue;
4929
4930 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004931 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004932 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004933
David Blaikie2d7c57e2012-04-30 02:36:29 +00004934 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004935 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004936 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004937 return false;
4938 }
4939
4940 return true;
4941}
4942
4943bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4944 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004945 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004946 if (RD->isUnion()) {
4947 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4948 // object's first non-static named data member is zero-initialized
4949 RecordDecl::field_iterator I = RD->field_begin();
4950 if (I == RD->field_end()) {
4951 Result = APValue((const FieldDecl*)0);
4952 return true;
4953 }
4954
4955 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004956 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004957 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004958 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004959 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004960 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004961 }
4962
Richard Smith5d108602012-02-17 00:44:16 +00004963 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004964 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004965 return false;
4966 }
4967
Richard Smitha8105bc2012-01-06 16:39:00 +00004968 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004969}
4970
Richard Smithe97cbd72011-11-11 04:05:33 +00004971bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4972 switch (E->getCastKind()) {
4973 default:
4974 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4975
4976 case CK_ConstructorConversion:
4977 return Visit(E->getSubExpr());
4978
4979 case CK_DerivedToBase:
4980 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004981 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004982 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004983 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004984 if (!DerivedObject.isStruct())
4985 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004986
4987 // Derived-to-base rvalue conversion: just slice off the derived part.
4988 APValue *Value = &DerivedObject;
4989 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4990 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4991 PathE = E->path_end(); PathI != PathE; ++PathI) {
4992 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4993 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4994 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4995 RD = Base;
4996 }
4997 Result = *Value;
4998 return true;
4999 }
5000 }
5001}
5002
Richard Smithd62306a2011-11-10 06:34:14 +00005003bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5004 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005005 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005006 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5007
5008 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005009 const FieldDecl *Field = E->getInitializedFieldInUnion();
5010 Result = APValue(Field);
5011 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005012 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005013
5014 // If the initializer list for a union does not contain any elements, the
5015 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005016 // FIXME: The element should be initialized from an initializer list.
5017 // Is this difference ever observable for initializer lists which
5018 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005019 ImplicitValueInitExpr VIE(Field->getType());
5020 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5021
Richard Smithd62306a2011-11-10 06:34:14 +00005022 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005023 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5024 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005025
5026 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5027 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5028 isa<CXXDefaultInitExpr>(InitExpr));
5029
Richard Smithb228a862012-02-15 02:18:13 +00005030 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005031 }
5032
5033 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5034 "initializer list for class with base classes");
5035 Result = APValue(APValue::UninitStruct(), 0,
5036 std::distance(RD->field_begin(), RD->field_end()));
5037 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005038 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005039 for (RecordDecl::field_iterator Field = RD->field_begin(),
5040 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5041 // Anonymous bit-fields are not considered members of the class for
5042 // purposes of aggregate initialization.
5043 if (Field->isUnnamedBitfield())
5044 continue;
5045
5046 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005047
Richard Smith253c2a32012-01-27 01:14:48 +00005048 bool HaveInit = ElementNo < E->getNumInits();
5049
5050 // FIXME: Diagnostics here should point to the end of the initializer
5051 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005052 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00005053 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005054 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005055
5056 // Perform an implicit value-initialization for members beyond the end of
5057 // the initializer list.
5058 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005059 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005060
Richard Smith852c9db2013-04-20 22:23:05 +00005061 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5062 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5063 isa<CXXDefaultInitExpr>(Init));
5064
Richard Smith49ca8aa2013-08-06 07:09:20 +00005065 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5066 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5067 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5068 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005069 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005070 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005071 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005072 }
5073 }
5074
Richard Smith253c2a32012-01-27 01:14:48 +00005075 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005076}
5077
5078bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5079 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005080 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5081
Richard Smithfddd3842011-12-30 21:15:51 +00005082 bool ZeroInit = E->requiresZeroInitialization();
5083 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005084 // If we've already performed zero-initialization, we're already done.
5085 if (!Result.isUninit())
5086 return true;
5087
Richard Smithfddd3842011-12-30 21:15:51 +00005088 if (ZeroInit)
5089 return ZeroInitialization(E);
5090
Richard Smithcc36f692011-12-22 02:22:31 +00005091 const CXXRecordDecl *RD = FD->getParent();
5092 if (RD->isUnion())
5093 Result = APValue((FieldDecl*)0);
5094 else
5095 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5096 std::distance(RD->field_begin(), RD->field_end()));
5097 return true;
5098 }
5099
Richard Smithd62306a2011-11-10 06:34:14 +00005100 const FunctionDecl *Definition = 0;
5101 FD->getBody(Definition);
5102
Richard Smith357362d2011-12-13 06:39:58 +00005103 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5104 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005105
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005106 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005107 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005108 if (const MaterializeTemporaryExpr *ME
5109 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5110 return Visit(ME->GetTemporaryExpr());
5111
Richard Smithfddd3842011-12-30 21:15:51 +00005112 if (ZeroInit && !ZeroInitialization(E))
5113 return false;
5114
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005115 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005116 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005117 cast<CXXConstructorDecl>(Definition), Info,
5118 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005119}
5120
Richard Smithcc1b96d2013-06-12 22:31:48 +00005121bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5122 const CXXStdInitializerListExpr *E) {
5123 const ConstantArrayType *ArrayType =
5124 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5125
5126 LValue Array;
5127 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5128 return false;
5129
5130 // Get a pointer to the first element of the array.
5131 Array.addArray(Info, E, ArrayType);
5132
5133 // FIXME: Perform the checks on the field types in SemaInit.
5134 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5135 RecordDecl::field_iterator Field = Record->field_begin();
5136 if (Field == Record->field_end())
5137 return Error(E);
5138
5139 // Start pointer.
5140 if (!Field->getType()->isPointerType() ||
5141 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5142 ArrayType->getElementType()))
5143 return Error(E);
5144
5145 // FIXME: What if the initializer_list type has base classes, etc?
5146 Result = APValue(APValue::UninitStruct(), 0, 2);
5147 Array.moveInto(Result.getStructField(0));
5148
5149 if (++Field == Record->field_end())
5150 return Error(E);
5151
5152 if (Field->getType()->isPointerType() &&
5153 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5154 ArrayType->getElementType())) {
5155 // End pointer.
5156 if (!HandleLValueArrayAdjustment(Info, E, Array,
5157 ArrayType->getElementType(),
5158 ArrayType->getSize().getZExtValue()))
5159 return false;
5160 Array.moveInto(Result.getStructField(1));
5161 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5162 // Length.
5163 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5164 else
5165 return Error(E);
5166
5167 if (++Field != Record->field_end())
5168 return Error(E);
5169
5170 return true;
5171}
5172
Richard Smithd62306a2011-11-10 06:34:14 +00005173static bool EvaluateRecord(const Expr *E, const LValue &This,
5174 APValue &Result, EvalInfo &Info) {
5175 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005176 "can't evaluate expression as a record rvalue");
5177 return RecordExprEvaluator(Info, This, Result).Visit(E);
5178}
5179
5180//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005181// Temporary Evaluation
5182//
5183// Temporaries are represented in the AST as rvalues, but generally behave like
5184// lvalues. The full-object of which the temporary is a subobject is implicitly
5185// materialized so that a reference can bind to it.
5186//===----------------------------------------------------------------------===//
5187namespace {
5188class TemporaryExprEvaluator
5189 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5190public:
5191 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5192 LValueExprEvaluatorBaseTy(Info, Result) {}
5193
5194 /// Visit an expression which constructs the value of this temporary.
5195 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005196 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005197 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5198 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005199 }
5200
5201 bool VisitCastExpr(const CastExpr *E) {
5202 switch (E->getCastKind()) {
5203 default:
5204 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5205
5206 case CK_ConstructorConversion:
5207 return VisitConstructExpr(E->getSubExpr());
5208 }
5209 }
5210 bool VisitInitListExpr(const InitListExpr *E) {
5211 return VisitConstructExpr(E);
5212 }
5213 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5214 return VisitConstructExpr(E);
5215 }
5216 bool VisitCallExpr(const CallExpr *E) {
5217 return VisitConstructExpr(E);
5218 }
5219};
5220} // end anonymous namespace
5221
5222/// Evaluate an expression of record type as a temporary.
5223static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005224 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005225 return TemporaryExprEvaluator(Info, Result).Visit(E);
5226}
5227
5228//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005229// Vector Evaluation
5230//===----------------------------------------------------------------------===//
5231
5232namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005233 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005234 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5235 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005236 public:
Mike Stump11289f42009-09-09 15:08:12 +00005237
Richard Smith2d406342011-10-22 21:10:00 +00005238 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5239 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005240
Richard Smith2d406342011-10-22 21:10:00 +00005241 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5242 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5243 // FIXME: remove this APValue copy.
5244 Result = APValue(V.data(), V.size());
5245 return true;
5246 }
Richard Smith2e312c82012-03-03 22:46:17 +00005247 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005248 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005249 Result = V;
5250 return true;
5251 }
Richard Smithfddd3842011-12-30 21:15:51 +00005252 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005253
Richard Smith2d406342011-10-22 21:10:00 +00005254 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005255 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005256 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005257 bool VisitInitListExpr(const InitListExpr *E);
5258 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005259 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005260 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005261 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005262 };
5263} // end anonymous namespace
5264
5265static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005266 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005267 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005268}
5269
Richard Smith2d406342011-10-22 21:10:00 +00005270bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5271 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005272 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005273
Richard Smith161f09a2011-12-06 22:44:34 +00005274 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005275 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005276
Eli Friedmanc757de22011-03-25 00:43:55 +00005277 switch (E->getCastKind()) {
5278 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005279 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005280 if (SETy->isIntegerType()) {
5281 APSInt IntResult;
5282 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005283 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005284 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005285 } else if (SETy->isRealFloatingType()) {
5286 APFloat F(0.0);
5287 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005288 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005289 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005290 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005291 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005292 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005293
5294 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005295 SmallVector<APValue, 4> Elts(NElts, Val);
5296 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005297 }
Eli Friedman803acb32011-12-22 03:51:45 +00005298 case CK_BitCast: {
5299 // Evaluate the operand into an APInt we can extract from.
5300 llvm::APInt SValInt;
5301 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5302 return false;
5303 // Extract the elements
5304 QualType EltTy = VTy->getElementType();
5305 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5306 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5307 SmallVector<APValue, 4> Elts;
5308 if (EltTy->isRealFloatingType()) {
5309 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005310 unsigned FloatEltSize = EltSize;
5311 if (&Sem == &APFloat::x87DoubleExtended)
5312 FloatEltSize = 80;
5313 for (unsigned i = 0; i < NElts; i++) {
5314 llvm::APInt Elt;
5315 if (BigEndian)
5316 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5317 else
5318 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005319 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005320 }
5321 } else if (EltTy->isIntegerType()) {
5322 for (unsigned i = 0; i < NElts; i++) {
5323 llvm::APInt Elt;
5324 if (BigEndian)
5325 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5326 else
5327 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5328 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5329 }
5330 } else {
5331 return Error(E);
5332 }
5333 return Success(Elts, E);
5334 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005335 default:
Richard Smith11562c52011-10-28 17:51:58 +00005336 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005337 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005338}
5339
Richard Smith2d406342011-10-22 21:10:00 +00005340bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005341VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005342 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005343 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005344 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005345
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005346 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005347 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005348
Eli Friedmanb9c71292012-01-03 23:24:20 +00005349 // The number of initializers can be less than the number of
5350 // vector elements. For OpenCL, this can be due to nested vector
5351 // initialization. For GCC compatibility, missing trailing elements
5352 // should be initialized with zeroes.
5353 unsigned CountInits = 0, CountElts = 0;
5354 while (CountElts < NumElements) {
5355 // Handle nested vector initialization.
5356 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005357 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005358 APValue v;
5359 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5360 return Error(E);
5361 unsigned vlen = v.getVectorLength();
5362 for (unsigned j = 0; j < vlen; j++)
5363 Elements.push_back(v.getVectorElt(j));
5364 CountElts += vlen;
5365 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005366 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005367 if (CountInits < NumInits) {
5368 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005369 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005370 } else // trailing integer zero.
5371 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5372 Elements.push_back(APValue(sInt));
5373 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005374 } else {
5375 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005376 if (CountInits < NumInits) {
5377 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005378 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005379 } else // trailing float zero.
5380 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5381 Elements.push_back(APValue(f));
5382 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005383 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005384 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005385 }
Richard Smith2d406342011-10-22 21:10:00 +00005386 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005387}
5388
Richard Smith2d406342011-10-22 21:10:00 +00005389bool
Richard Smithfddd3842011-12-30 21:15:51 +00005390VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005391 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005392 QualType EltTy = VT->getElementType();
5393 APValue ZeroElement;
5394 if (EltTy->isIntegerType())
5395 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5396 else
5397 ZeroElement =
5398 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5399
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005400 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005401 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005402}
5403
Richard Smith2d406342011-10-22 21:10:00 +00005404bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005405 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005406 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005407}
5408
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005409//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005410// Array Evaluation
5411//===----------------------------------------------------------------------===//
5412
5413namespace {
5414 class ArrayExprEvaluator
5415 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005416 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005417 APValue &Result;
5418 public:
5419
Richard Smithd62306a2011-11-10 06:34:14 +00005420 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5421 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005422
5423 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005424 assert((V.isArray() || V.isLValue()) &&
5425 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005426 Result = V;
5427 return true;
5428 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005429
Richard Smithfddd3842011-12-30 21:15:51 +00005430 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005431 const ConstantArrayType *CAT =
5432 Info.Ctx.getAsConstantArrayType(E->getType());
5433 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005434 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005435
5436 Result = APValue(APValue::UninitArray(), 0,
5437 CAT->getSize().getZExtValue());
5438 if (!Result.hasArrayFiller()) return true;
5439
Richard Smithfddd3842011-12-30 21:15:51 +00005440 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005441 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005442 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005443 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005444 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005445 }
5446
Richard Smithf3e9e432011-11-07 09:22:26 +00005447 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005448 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005449 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5450 const LValue &Subobject,
5451 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005452 };
5453} // end anonymous namespace
5454
Richard Smithd62306a2011-11-10 06:34:14 +00005455static bool EvaluateArray(const Expr *E, const LValue &This,
5456 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005457 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005458 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005459}
5460
5461bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5462 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5463 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005464 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005465
Richard Smithca2cfbf2011-12-22 01:07:19 +00005466 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5467 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005468 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005469 LValue LV;
5470 if (!EvaluateLValue(E->getInit(0), LV, Info))
5471 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005472 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005473 LV.moveInto(Val);
5474 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005475 }
5476
Richard Smith253c2a32012-01-27 01:14:48 +00005477 bool Success = true;
5478
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005479 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5480 "zero-initialized array shouldn't have any initialized elts");
5481 APValue Filler;
5482 if (Result.isArray() && Result.hasArrayFiller())
5483 Filler = Result.getArrayFiller();
5484
Richard Smith9543c5e2013-04-22 14:44:29 +00005485 unsigned NumEltsToInit = E->getNumInits();
5486 unsigned NumElts = CAT->getSize().getZExtValue();
5487 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5488
5489 // If the initializer might depend on the array index, run it for each
5490 // array element. For now, just whitelist non-class value-initialization.
5491 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5492 NumEltsToInit = NumElts;
5493
5494 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005495
5496 // If the array was previously zero-initialized, preserve the
5497 // zero-initialized values.
5498 if (!Filler.isUninit()) {
5499 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5500 Result.getArrayInitializedElt(I) = Filler;
5501 if (Result.hasArrayFiller())
5502 Result.getArrayFiller() = Filler;
5503 }
5504
Richard Smithd62306a2011-11-10 06:34:14 +00005505 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005506 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005507 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5508 const Expr *Init =
5509 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005510 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005511 Info, Subobject, Init) ||
5512 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005513 CAT->getElementType(), 1)) {
5514 if (!Info.keepEvaluatingAfterFailure())
5515 return false;
5516 Success = false;
5517 }
Richard Smithd62306a2011-11-10 06:34:14 +00005518 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005519
Richard Smith9543c5e2013-04-22 14:44:29 +00005520 if (!Result.hasArrayFiller())
5521 return Success;
5522
5523 // If we get here, we have a trivial filler, which we can just evaluate
5524 // once and splat over the rest of the array elements.
5525 assert(FillerExpr && "no array filler for incomplete init list");
5526 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5527 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005528}
5529
Richard Smith027bf112011-11-17 22:56:20 +00005530bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005531 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5532}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005533
Richard Smith9543c5e2013-04-22 14:44:29 +00005534bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5535 const LValue &Subobject,
5536 APValue *Value,
5537 QualType Type) {
5538 bool HadZeroInit = !Value->isUninit();
5539
5540 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5541 unsigned N = CAT->getSize().getZExtValue();
5542
5543 // Preserve the array filler if we had prior zero-initialization.
5544 APValue Filler =
5545 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5546 : APValue();
5547
5548 *Value = APValue(APValue::UninitArray(), N, N);
5549
5550 if (HadZeroInit)
5551 for (unsigned I = 0; I != N; ++I)
5552 Value->getArrayInitializedElt(I) = Filler;
5553
5554 // Initialize the elements.
5555 LValue ArrayElt = Subobject;
5556 ArrayElt.addArray(Info, E, CAT);
5557 for (unsigned I = 0; I != N; ++I)
5558 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5559 CAT->getElementType()) ||
5560 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5561 CAT->getElementType(), 1))
5562 return false;
5563
5564 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005565 }
Richard Smith027bf112011-11-17 22:56:20 +00005566
Richard Smith9543c5e2013-04-22 14:44:29 +00005567 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005568 return Error(E);
5569
Richard Smith027bf112011-11-17 22:56:20 +00005570 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005571
Richard Smithfddd3842011-12-30 21:15:51 +00005572 bool ZeroInit = E->requiresZeroInitialization();
5573 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005574 if (HadZeroInit)
5575 return true;
5576
Richard Smithfddd3842011-12-30 21:15:51 +00005577 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005578 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005579 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005580 }
5581
Richard Smithcc36f692011-12-22 02:22:31 +00005582 const CXXRecordDecl *RD = FD->getParent();
5583 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005584 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005585 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005586 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005587 APValue(APValue::UninitStruct(), RD->getNumBases(),
5588 std::distance(RD->field_begin(), RD->field_end()));
5589 return true;
5590 }
5591
Richard Smith027bf112011-11-17 22:56:20 +00005592 const FunctionDecl *Definition = 0;
5593 FD->getBody(Definition);
5594
Richard Smith357362d2011-12-13 06:39:58 +00005595 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5596 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005597
Richard Smith9eae7232012-01-12 18:54:33 +00005598 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005599 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005600 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005601 return false;
5602 }
5603
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005604 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005605 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005606 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005607 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005608}
5609
Richard Smithf3e9e432011-11-07 09:22:26 +00005610//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005611// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005612//
5613// As a GNU extension, we support casting pointers to sufficiently-wide integer
5614// types and back in constant folding. Integer values are thus represented
5615// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005616//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005617
5618namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005619class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005620 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005621 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005622public:
Richard Smith2e312c82012-03-03 22:46:17 +00005623 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005624 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005625
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005626 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005627 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005628 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005629 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005630 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005631 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005632 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005633 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005634 return true;
5635 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005636 bool Success(const llvm::APSInt &SI, const Expr *E) {
5637 return Success(SI, E, Result);
5638 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005639
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005640 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005641 assert(E->getType()->isIntegralOrEnumerationType() &&
5642 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005643 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005644 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005645 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005646 Result.getInt().setIsUnsigned(
5647 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005648 return true;
5649 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005650 bool Success(const llvm::APInt &I, const Expr *E) {
5651 return Success(I, E, Result);
5652 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005653
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005654 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005655 assert(E->getType()->isIntegralOrEnumerationType() &&
5656 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005657 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005658 return true;
5659 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005660 bool Success(uint64_t Value, const Expr *E) {
5661 return Success(Value, E, Result);
5662 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005663
Ken Dyckdbc01912011-03-11 02:13:43 +00005664 bool Success(CharUnits Size, const Expr *E) {
5665 return Success(Size.getQuantity(), E);
5666 }
5667
Richard Smith2e312c82012-03-03 22:46:17 +00005668 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005669 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005670 Result = V;
5671 return true;
5672 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005673 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005674 }
Mike Stump11289f42009-09-09 15:08:12 +00005675
Richard Smithfddd3842011-12-30 21:15:51 +00005676 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005677
Peter Collingbournee9200682011-05-13 03:29:01 +00005678 //===--------------------------------------------------------------------===//
5679 // Visitor Methods
5680 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005681
Chris Lattner7174bf32008-07-12 00:38:25 +00005682 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005683 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005684 }
5685 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005686 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005687 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005688
5689 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5690 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005691 if (CheckReferencedDecl(E, E->getDecl()))
5692 return true;
5693
5694 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005695 }
5696 bool VisitMemberExpr(const MemberExpr *E) {
5697 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005698 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005699 return true;
5700 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005701
5702 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005703 }
5704
Peter Collingbournee9200682011-05-13 03:29:01 +00005705 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005706 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005707 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005708 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005709
Peter Collingbournee9200682011-05-13 03:29:01 +00005710 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005711 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005712
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005713 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005714 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005715 }
Mike Stump11289f42009-09-09 15:08:12 +00005716
Ted Kremeneke65b0862012-03-06 20:05:56 +00005717 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5718 return Success(E->getValue(), E);
5719 }
5720
Richard Smith4ce706a2011-10-11 21:43:33 +00005721 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005722 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005723 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005724 }
5725
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005726 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005727 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005728 }
5729
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005730 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5731 return Success(E->getValue(), E);
5732 }
5733
Douglas Gregor29c42f22012-02-24 07:38:34 +00005734 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5735 return Success(E->getValue(), E);
5736 }
5737
John Wiegley6242b6a2011-04-28 00:16:57 +00005738 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5739 return Success(E->getValue(), E);
5740 }
5741
John Wiegleyf9f65842011-04-25 06:54:41 +00005742 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5743 return Success(E->getValue(), E);
5744 }
5745
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005746 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005747 bool VisitUnaryImag(const UnaryOperator *E);
5748
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005749 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005750 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005751
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005752private:
Ken Dyck160146e2010-01-27 17:10:57 +00005753 CharUnits GetAlignOfExpr(const Expr *E);
5754 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005755 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005756 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005757 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005758};
Chris Lattner05706e882008-07-11 18:11:29 +00005759} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005760
Richard Smith11562c52011-10-28 17:51:58 +00005761/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5762/// produce either the integer value or a pointer.
5763///
5764/// GCC has a heinous extension which folds casts between pointer types and
5765/// pointer-sized integral types. We support this by allowing the evaluation of
5766/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5767/// Some simple arithmetic on such values is supported (they are treated much
5768/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005769static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005770 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005771 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005772 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005773}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005774
Richard Smithf57d8cb2011-12-09 22:58:01 +00005775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005776 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005777 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005778 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005779 if (!Val.isInt()) {
5780 // FIXME: It would be better to produce the diagnostic for casting
5781 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005782 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005783 return false;
5784 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005785 Result = Val.getInt();
5786 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005787}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005788
Richard Smithf57d8cb2011-12-09 22:58:01 +00005789/// Check whether the given declaration can be directly converted to an integral
5790/// rvalue. If not, no diagnostic is produced; there are other things we can
5791/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005792bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005793 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005794 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005795 // Check for signedness/width mismatches between E type and ECD value.
5796 bool SameSign = (ECD->getInitVal().isSigned()
5797 == E->getType()->isSignedIntegerOrEnumerationType());
5798 bool SameWidth = (ECD->getInitVal().getBitWidth()
5799 == Info.Ctx.getIntWidth(E->getType()));
5800 if (SameSign && SameWidth)
5801 return Success(ECD->getInitVal(), E);
5802 else {
5803 // Get rid of mismatch (otherwise Success assertions will fail)
5804 // by computing a new value matching the type of E.
5805 llvm::APSInt Val = ECD->getInitVal();
5806 if (!SameSign)
5807 Val.setIsSigned(!ECD->getInitVal().isSigned());
5808 if (!SameWidth)
5809 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5810 return Success(Val, E);
5811 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005812 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005813 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005814}
5815
Chris Lattner86ee2862008-10-06 06:40:35 +00005816/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5817/// as GCC.
5818static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5819 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005820 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005821 enum gcc_type_class {
5822 no_type_class = -1,
5823 void_type_class, integer_type_class, char_type_class,
5824 enumeral_type_class, boolean_type_class,
5825 pointer_type_class, reference_type_class, offset_type_class,
5826 real_type_class, complex_type_class,
5827 function_type_class, method_type_class,
5828 record_type_class, union_type_class,
5829 array_type_class, string_type_class,
5830 lang_type_class
5831 };
Mike Stump11289f42009-09-09 15:08:12 +00005832
5833 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005834 // ideal, however it is what gcc does.
5835 if (E->getNumArgs() == 0)
5836 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005837
Chris Lattner86ee2862008-10-06 06:40:35 +00005838 QualType ArgTy = E->getArg(0)->getType();
5839 if (ArgTy->isVoidType())
5840 return void_type_class;
5841 else if (ArgTy->isEnumeralType())
5842 return enumeral_type_class;
5843 else if (ArgTy->isBooleanType())
5844 return boolean_type_class;
5845 else if (ArgTy->isCharType())
5846 return string_type_class; // gcc doesn't appear to use char_type_class
5847 else if (ArgTy->isIntegerType())
5848 return integer_type_class;
5849 else if (ArgTy->isPointerType())
5850 return pointer_type_class;
5851 else if (ArgTy->isReferenceType())
5852 return reference_type_class;
5853 else if (ArgTy->isRealType())
5854 return real_type_class;
5855 else if (ArgTy->isComplexType())
5856 return complex_type_class;
5857 else if (ArgTy->isFunctionType())
5858 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005859 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005860 return record_type_class;
5861 else if (ArgTy->isUnionType())
5862 return union_type_class;
5863 else if (ArgTy->isArrayType())
5864 return array_type_class;
5865 else if (ArgTy->isUnionType())
5866 return union_type_class;
5867 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005868 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005869}
5870
Richard Smith5fab0c92011-12-28 19:48:30 +00005871/// EvaluateBuiltinConstantPForLValue - Determine the result of
5872/// __builtin_constant_p when applied to the given lvalue.
5873///
5874/// An lvalue is only "constant" if it is a pointer or reference to the first
5875/// character of a string literal.
5876template<typename LValue>
5877static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005878 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005879 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5880}
5881
5882/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5883/// GCC as we can manage.
5884static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5885 QualType ArgType = Arg->getType();
5886
5887 // __builtin_constant_p always has one operand. The rules which gcc follows
5888 // are not precisely documented, but are as follows:
5889 //
5890 // - If the operand is of integral, floating, complex or enumeration type,
5891 // and can be folded to a known value of that type, it returns 1.
5892 // - If the operand and can be folded to a pointer to the first character
5893 // of a string literal (or such a pointer cast to an integral type), it
5894 // returns 1.
5895 //
5896 // Otherwise, it returns 0.
5897 //
5898 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5899 // its support for this does not currently work.
5900 if (ArgType->isIntegralOrEnumerationType()) {
5901 Expr::EvalResult Result;
5902 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5903 return false;
5904
5905 APValue &V = Result.Val;
5906 if (V.getKind() == APValue::Int)
5907 return true;
5908
5909 return EvaluateBuiltinConstantPForLValue(V);
5910 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5911 return Arg->isEvaluatable(Ctx);
5912 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5913 LValue LV;
5914 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005915 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005916 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5917 : EvaluatePointer(Arg, LV, Info)) &&
5918 !Status.HasSideEffects)
5919 return EvaluateBuiltinConstantPForLValue(LV);
5920 }
5921
5922 // Anything else isn't considered to be sufficiently constant.
5923 return false;
5924}
5925
John McCall95007602010-05-10 23:27:23 +00005926/// Retrieves the "underlying object type" of the given expression,
5927/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005928QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5929 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5930 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005931 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005932 } else if (const Expr *E = B.get<const Expr*>()) {
5933 if (isa<CompoundLiteralExpr>(E))
5934 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005935 }
5936
5937 return QualType();
5938}
5939
Peter Collingbournee9200682011-05-13 03:29:01 +00005940bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005941 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005942
5943 {
5944 // The operand of __builtin_object_size is never evaluated for side-effects.
5945 // If there are any, but we can determine the pointed-to object anyway, then
5946 // ignore the side-effects.
5947 SpeculativeEvaluationRAII SpeculativeEval(Info);
5948 if (!EvaluatePointer(E->getArg(0), Base, Info))
5949 return false;
5950 }
John McCall95007602010-05-10 23:27:23 +00005951
5952 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005953 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005954
Richard Smithce40ad62011-11-12 22:28:03 +00005955 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005956 if (T.isNull() ||
5957 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005958 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005959 T->isVariablyModifiedType() ||
5960 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005961 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005962
5963 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5964 CharUnits Offset = Base.getLValueOffset();
5965
5966 if (!Offset.isNegative() && Offset <= Size)
5967 Size -= Offset;
5968 else
5969 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005970 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005971}
5972
Peter Collingbournee9200682011-05-13 03:29:01 +00005973bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005974 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005975 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005976 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005977
5978 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005979 if (TryEvaluateBuiltinObjectSize(E))
5980 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005981
Richard Smith0421ce72012-08-07 04:16:51 +00005982 // If evaluating the argument has side-effects, we can't determine the size
5983 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5984 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005985 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005986 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005987 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005988 return Success(0, E);
5989 }
Mike Stump876387b2009-10-27 22:09:17 +00005990
Richard Smith01ade172012-05-23 04:13:20 +00005991 // Expression had no side effects, but we couldn't statically determine the
5992 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005993 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005994 }
5995
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005996 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005997 case Builtin::BI__builtin_bswap32:
5998 case Builtin::BI__builtin_bswap64: {
5999 APSInt Val;
6000 if (!EvaluateInteger(E->getArg(0), Val, Info))
6001 return false;
6002
6003 return Success(Val.byteSwap(), E);
6004 }
6005
Richard Smith8889a3d2013-06-13 06:26:32 +00006006 case Builtin::BI__builtin_classify_type:
6007 return Success(EvaluateBuiltinClassifyType(E), E);
6008
6009 // FIXME: BI__builtin_clrsb
6010 // FIXME: BI__builtin_clrsbl
6011 // FIXME: BI__builtin_clrsbll
6012
Richard Smith80b3c8e2013-06-13 05:04:16 +00006013 case Builtin::BI__builtin_clz:
6014 case Builtin::BI__builtin_clzl:
6015 case Builtin::BI__builtin_clzll: {
6016 APSInt Val;
6017 if (!EvaluateInteger(E->getArg(0), Val, Info))
6018 return false;
6019 if (!Val)
6020 return Error(E);
6021
6022 return Success(Val.countLeadingZeros(), E);
6023 }
6024
Richard Smith8889a3d2013-06-13 06:26:32 +00006025 case Builtin::BI__builtin_constant_p:
6026 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6027
Richard Smith80b3c8e2013-06-13 05:04:16 +00006028 case Builtin::BI__builtin_ctz:
6029 case Builtin::BI__builtin_ctzl:
6030 case Builtin::BI__builtin_ctzll: {
6031 APSInt Val;
6032 if (!EvaluateInteger(E->getArg(0), Val, Info))
6033 return false;
6034 if (!Val)
6035 return Error(E);
6036
6037 return Success(Val.countTrailingZeros(), E);
6038 }
6039
Richard Smith8889a3d2013-06-13 06:26:32 +00006040 case Builtin::BI__builtin_eh_return_data_regno: {
6041 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6042 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6043 return Success(Operand, E);
6044 }
6045
6046 case Builtin::BI__builtin_expect:
6047 return Visit(E->getArg(0));
6048
6049 case Builtin::BI__builtin_ffs:
6050 case Builtin::BI__builtin_ffsl:
6051 case Builtin::BI__builtin_ffsll: {
6052 APSInt Val;
6053 if (!EvaluateInteger(E->getArg(0), Val, Info))
6054 return false;
6055
6056 unsigned N = Val.countTrailingZeros();
6057 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6058 }
6059
6060 case Builtin::BI__builtin_fpclassify: {
6061 APFloat Val(0.0);
6062 if (!EvaluateFloat(E->getArg(5), Val, Info))
6063 return false;
6064 unsigned Arg;
6065 switch (Val.getCategory()) {
6066 case APFloat::fcNaN: Arg = 0; break;
6067 case APFloat::fcInfinity: Arg = 1; break;
6068 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6069 case APFloat::fcZero: Arg = 4; break;
6070 }
6071 return Visit(E->getArg(Arg));
6072 }
6073
6074 case Builtin::BI__builtin_isinf_sign: {
6075 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006076 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006077 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6078 }
6079
Richard Smithea3019d2013-10-15 19:07:14 +00006080 case Builtin::BI__builtin_isinf: {
6081 APFloat Val(0.0);
6082 return EvaluateFloat(E->getArg(0), Val, Info) &&
6083 Success(Val.isInfinity() ? 1 : 0, E);
6084 }
6085
6086 case Builtin::BI__builtin_isfinite: {
6087 APFloat Val(0.0);
6088 return EvaluateFloat(E->getArg(0), Val, Info) &&
6089 Success(Val.isFinite() ? 1 : 0, E);
6090 }
6091
6092 case Builtin::BI__builtin_isnan: {
6093 APFloat Val(0.0);
6094 return EvaluateFloat(E->getArg(0), Val, Info) &&
6095 Success(Val.isNaN() ? 1 : 0, E);
6096 }
6097
6098 case Builtin::BI__builtin_isnormal: {
6099 APFloat Val(0.0);
6100 return EvaluateFloat(E->getArg(0), Val, Info) &&
6101 Success(Val.isNormal() ? 1 : 0, E);
6102 }
6103
Richard Smith8889a3d2013-06-13 06:26:32 +00006104 case Builtin::BI__builtin_parity:
6105 case Builtin::BI__builtin_parityl:
6106 case Builtin::BI__builtin_parityll: {
6107 APSInt Val;
6108 if (!EvaluateInteger(E->getArg(0), Val, Info))
6109 return false;
6110
6111 return Success(Val.countPopulation() % 2, E);
6112 }
6113
Richard Smith80b3c8e2013-06-13 05:04:16 +00006114 case Builtin::BI__builtin_popcount:
6115 case Builtin::BI__builtin_popcountl:
6116 case Builtin::BI__builtin_popcountll: {
6117 APSInt Val;
6118 if (!EvaluateInteger(E->getArg(0), Val, Info))
6119 return false;
6120
6121 return Success(Val.countPopulation(), E);
6122 }
6123
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006124 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006125 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006126 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006127 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006128 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6129 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006130 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006131 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006132 case Builtin::BI__builtin_strlen:
6133 // As an extension, we support strlen() and __builtin_strlen() as constant
6134 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00006135 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006136 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6137 // The string literal may have embedded null characters. Find the first
6138 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006139 StringRef Str = S->getString();
6140 StringRef::size_type Pos = Str.find(0);
6141 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006142 Str = Str.substr(0, Pos);
6143
6144 return Success(Str.size(), E);
6145 }
6146
Richard Smithf57d8cb2011-12-09 22:58:01 +00006147 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006148
Richard Smith01ba47d2012-04-13 00:45:38 +00006149 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006150 case Builtin::BI__atomic_is_lock_free:
6151 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006152 APSInt SizeVal;
6153 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6154 return false;
6155
6156 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6157 // of two less than the maximum inline atomic width, we know it is
6158 // lock-free. If the size isn't a power of two, or greater than the
6159 // maximum alignment where we promote atomics, we know it is not lock-free
6160 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6161 // the answer can only be determined at runtime; for example, 16-byte
6162 // atomics have lock-free implementations on some, but not all,
6163 // x86-64 processors.
6164
6165 // Check power-of-two.
6166 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006167 if (Size.isPowerOfTwo()) {
6168 // Check against inlining width.
6169 unsigned InlineWidthBits =
6170 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6171 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6172 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6173 Size == CharUnits::One() ||
6174 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6175 Expr::NPC_NeverValueDependent))
6176 // OK, we will inline appropriately-aligned operations of this size,
6177 // and _Atomic(T) is appropriately-aligned.
6178 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006179
Richard Smith01ba47d2012-04-13 00:45:38 +00006180 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6181 castAs<PointerType>()->getPointeeType();
6182 if (!PointeeType->isIncompleteType() &&
6183 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6184 // OK, we will inline operations on this object.
6185 return Success(1, E);
6186 }
6187 }
6188 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006189
Richard Smith01ba47d2012-04-13 00:45:38 +00006190 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6191 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006192 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006193 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006194}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006195
Richard Smith8b3497e2011-10-31 01:37:14 +00006196static bool HasSameBase(const LValue &A, const LValue &B) {
6197 if (!A.getLValueBase())
6198 return !B.getLValueBase();
6199 if (!B.getLValueBase())
6200 return false;
6201
Richard Smithce40ad62011-11-12 22:28:03 +00006202 if (A.getLValueBase().getOpaqueValue() !=
6203 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006204 const Decl *ADecl = GetLValueBaseDecl(A);
6205 if (!ADecl)
6206 return false;
6207 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006208 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006209 return false;
6210 }
6211
6212 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006213 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006214}
6215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006216namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006217
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006218/// \brief Data recursive integer evaluator of certain binary operators.
6219///
6220/// We use a data recursive algorithm for binary operators so that we are able
6221/// to handle extreme cases of chained binary operators without causing stack
6222/// overflow.
6223class DataRecursiveIntBinOpEvaluator {
6224 struct EvalResult {
6225 APValue Val;
6226 bool Failed;
6227
6228 EvalResult() : Failed(false) { }
6229
6230 void swap(EvalResult &RHS) {
6231 Val.swap(RHS.Val);
6232 Failed = RHS.Failed;
6233 RHS.Failed = false;
6234 }
6235 };
6236
6237 struct Job {
6238 const Expr *E;
6239 EvalResult LHSResult; // meaningful only for binary operator expression.
6240 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6241
6242 Job() : StoredInfo(0) { }
6243 void startSpeculativeEval(EvalInfo &Info) {
6244 OldEvalStatus = Info.EvalStatus;
6245 Info.EvalStatus.Diag = 0;
6246 StoredInfo = &Info;
6247 }
6248 ~Job() {
6249 if (StoredInfo) {
6250 StoredInfo->EvalStatus = OldEvalStatus;
6251 }
6252 }
6253 private:
6254 EvalInfo *StoredInfo; // non-null if status changed.
6255 Expr::EvalStatus OldEvalStatus;
6256 };
6257
6258 SmallVector<Job, 16> Queue;
6259
6260 IntExprEvaluator &IntEval;
6261 EvalInfo &Info;
6262 APValue &FinalResult;
6263
6264public:
6265 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6266 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6267
6268 /// \brief True if \param E is a binary operator that we are going to handle
6269 /// data recursively.
6270 /// We handle binary operators that are comma, logical, or that have operands
6271 /// with integral or enumeration type.
6272 static bool shouldEnqueue(const BinaryOperator *E) {
6273 return E->getOpcode() == BO_Comma ||
6274 E->isLogicalOp() ||
6275 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6276 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006277 }
6278
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006279 bool Traverse(const BinaryOperator *E) {
6280 enqueue(E);
6281 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006282 while (!Queue.empty())
6283 process(PrevResult);
6284
6285 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006286
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006287 FinalResult.swap(PrevResult.Val);
6288 return true;
6289 }
6290
6291private:
6292 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6293 return IntEval.Success(Value, E, Result);
6294 }
6295 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6296 return IntEval.Success(Value, E, Result);
6297 }
6298 bool Error(const Expr *E) {
6299 return IntEval.Error(E);
6300 }
6301 bool Error(const Expr *E, diag::kind D) {
6302 return IntEval.Error(E, D);
6303 }
6304
6305 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6306 return Info.CCEDiag(E, D);
6307 }
6308
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006309 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6310 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006311 bool &SuppressRHSDiags);
6312
6313 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6314 const BinaryOperator *E, APValue &Result);
6315
6316 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6317 Result.Failed = !Evaluate(Result.Val, Info, E);
6318 if (Result.Failed)
6319 Result.Val = APValue();
6320 }
6321
Richard Trieuba4d0872012-03-21 23:30:30 +00006322 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006323
6324 void enqueue(const Expr *E) {
6325 E = E->IgnoreParens();
6326 Queue.resize(Queue.size()+1);
6327 Queue.back().E = E;
6328 Queue.back().Kind = Job::AnyExprKind;
6329 }
6330};
6331
6332}
6333
6334bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006335 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006336 bool &SuppressRHSDiags) {
6337 if (E->getOpcode() == BO_Comma) {
6338 // Ignore LHS but note if we could not evaluate it.
6339 if (LHSResult.Failed)
6340 Info.EvalStatus.HasSideEffects = true;
6341 return true;
6342 }
6343
6344 if (E->isLogicalOp()) {
6345 bool lhsResult;
6346 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006347 // We were able to evaluate the LHS, see if we can get away with not
6348 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006349 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006350 Success(lhsResult, E, LHSResult.Val);
6351 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006352 }
6353 } else {
6354 // Since we weren't able to evaluate the left hand side, it
6355 // must have had side effects.
6356 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006357
6358 // We can't evaluate the LHS; however, sometimes the result
6359 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6360 // Don't ignore RHS and suppress diagnostics from this arm.
6361 SuppressRHSDiags = true;
6362 }
6363
6364 return true;
6365 }
6366
6367 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6368 E->getRHS()->getType()->isIntegralOrEnumerationType());
6369
6370 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006371 return false; // Ignore RHS;
6372
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006373 return true;
6374}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006375
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006376bool DataRecursiveIntBinOpEvaluator::
6377 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6378 const BinaryOperator *E, APValue &Result) {
6379 if (E->getOpcode() == BO_Comma) {
6380 if (RHSResult.Failed)
6381 return false;
6382 Result = RHSResult.Val;
6383 return true;
6384 }
6385
6386 if (E->isLogicalOp()) {
6387 bool lhsResult, rhsResult;
6388 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6389 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6390
6391 if (LHSIsOK) {
6392 if (RHSIsOK) {
6393 if (E->getOpcode() == BO_LOr)
6394 return Success(lhsResult || rhsResult, E, Result);
6395 else
6396 return Success(lhsResult && rhsResult, E, Result);
6397 }
6398 } else {
6399 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006400 // We can't evaluate the LHS; however, sometimes the result
6401 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6402 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006403 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006404 }
6405 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006406
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006407 return false;
6408 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006409
6410 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6411 E->getRHS()->getType()->isIntegralOrEnumerationType());
6412
6413 if (LHSResult.Failed || RHSResult.Failed)
6414 return false;
6415
6416 const APValue &LHSVal = LHSResult.Val;
6417 const APValue &RHSVal = RHSResult.Val;
6418
6419 // Handle cases like (unsigned long)&a + 4.
6420 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6421 Result = LHSVal;
6422 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6423 RHSVal.getInt().getZExtValue());
6424 if (E->getOpcode() == BO_Add)
6425 Result.getLValueOffset() += AdditionalOffset;
6426 else
6427 Result.getLValueOffset() -= AdditionalOffset;
6428 return true;
6429 }
6430
6431 // Handle cases like 4 + (unsigned long)&a
6432 if (E->getOpcode() == BO_Add &&
6433 RHSVal.isLValue() && LHSVal.isInt()) {
6434 Result = RHSVal;
6435 Result.getLValueOffset() += CharUnits::fromQuantity(
6436 LHSVal.getInt().getZExtValue());
6437 return true;
6438 }
6439
6440 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6441 // Handle (intptr_t)&&A - (intptr_t)&&B.
6442 if (!LHSVal.getLValueOffset().isZero() ||
6443 !RHSVal.getLValueOffset().isZero())
6444 return false;
6445 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6446 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6447 if (!LHSExpr || !RHSExpr)
6448 return false;
6449 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6450 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6451 if (!LHSAddrExpr || !RHSAddrExpr)
6452 return false;
6453 // Make sure both labels come from the same function.
6454 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6455 RHSAddrExpr->getLabel()->getDeclContext())
6456 return false;
6457 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6458 return true;
6459 }
Richard Smith43e77732013-05-07 04:50:00 +00006460
6461 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006462 if (!LHSVal.isInt() || !RHSVal.isInt())
6463 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006464
6465 // Set up the width and signedness manually, in case it can't be deduced
6466 // from the operation we're performing.
6467 // FIXME: Don't do this in the cases where we can deduce it.
6468 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6469 E->getType()->isUnsignedIntegerOrEnumerationType());
6470 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6471 RHSVal.getInt(), Value))
6472 return false;
6473 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006474}
6475
Richard Trieuba4d0872012-03-21 23:30:30 +00006476void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006477 Job &job = Queue.back();
6478
6479 switch (job.Kind) {
6480 case Job::AnyExprKind: {
6481 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6482 if (shouldEnqueue(Bop)) {
6483 job.Kind = Job::BinOpKind;
6484 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006485 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006486 }
6487 }
6488
6489 EvaluateExpr(job.E, Result);
6490 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006491 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006492 }
6493
6494 case Job::BinOpKind: {
6495 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006496 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006497 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006498 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006499 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006500 }
6501 if (SuppressRHSDiags)
6502 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006503 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006504 job.Kind = Job::BinOpVisitedLHSKind;
6505 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006506 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006507 }
6508
6509 case Job::BinOpVisitedLHSKind: {
6510 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6511 EvalResult RHS;
6512 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006513 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006514 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006515 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006516 }
6517 }
6518
6519 llvm_unreachable("Invalid Job::Kind!");
6520}
6521
6522bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6523 if (E->isAssignmentOp())
6524 return Error(E);
6525
6526 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6527 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006528
Anders Carlssonacc79812008-11-16 07:17:21 +00006529 QualType LHSTy = E->getLHS()->getType();
6530 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006531
6532 if (LHSTy->isAnyComplexType()) {
6533 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006534 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006535
Richard Smith253c2a32012-01-27 01:14:48 +00006536 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6537 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006538 return false;
6539
Richard Smith253c2a32012-01-27 01:14:48 +00006540 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006541 return false;
6542
6543 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006544 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006545 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006546 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006547 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6548
John McCalle3027922010-08-25 11:45:40 +00006549 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006550 return Success((CR_r == APFloat::cmpEqual &&
6551 CR_i == APFloat::cmpEqual), E);
6552 else {
John McCalle3027922010-08-25 11:45:40 +00006553 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006554 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006555 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006556 CR_r == APFloat::cmpLessThan ||
6557 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006558 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006559 CR_i == APFloat::cmpLessThan ||
6560 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006561 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006562 } else {
John McCalle3027922010-08-25 11:45:40 +00006563 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006564 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6565 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6566 else {
John McCalle3027922010-08-25 11:45:40 +00006567 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006568 "Invalid compex comparison.");
6569 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6570 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6571 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006572 }
6573 }
Mike Stump11289f42009-09-09 15:08:12 +00006574
Anders Carlssonacc79812008-11-16 07:17:21 +00006575 if (LHSTy->isRealFloatingType() &&
6576 RHSTy->isRealFloatingType()) {
6577 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006578
Richard Smith253c2a32012-01-27 01:14:48 +00006579 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6580 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006581 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006582
Richard Smith253c2a32012-01-27 01:14:48 +00006583 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006584 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006585
Anders Carlssonacc79812008-11-16 07:17:21 +00006586 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006587
Anders Carlssonacc79812008-11-16 07:17:21 +00006588 switch (E->getOpcode()) {
6589 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006590 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006591 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006592 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006593 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006594 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006595 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006596 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006597 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006598 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006599 E);
John McCalle3027922010-08-25 11:45:40 +00006600 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006601 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006602 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006603 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006604 || CR == APFloat::cmpLessThan
6605 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006606 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006607 }
Mike Stump11289f42009-09-09 15:08:12 +00006608
Eli Friedmana38da572009-04-28 19:17:36 +00006609 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006610 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006611 LValue LHSValue, RHSValue;
6612
6613 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6614 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006615 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006616
Richard Smith253c2a32012-01-27 01:14:48 +00006617 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006618 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006619
Richard Smith8b3497e2011-10-31 01:37:14 +00006620 // Reject differing bases from the normal codepath; we special-case
6621 // comparisons to null.
6622 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006623 if (E->getOpcode() == BO_Sub) {
6624 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006625 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6626 return false;
6627 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006628 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006629 if (!LHSExpr || !RHSExpr)
6630 return false;
6631 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6632 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6633 if (!LHSAddrExpr || !RHSAddrExpr)
6634 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006635 // Make sure both labels come from the same function.
6636 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6637 RHSAddrExpr->getLabel()->getDeclContext())
6638 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006639 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006640 return true;
6641 }
Richard Smith83c68212011-10-31 05:11:32 +00006642 // Inequalities and subtractions between unrelated pointers have
6643 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006644 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006645 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006646 // A constant address may compare equal to the address of a symbol.
6647 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006648 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006649 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6650 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006651 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006652 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006653 // distinct addresses. In clang, the result of such a comparison is
6654 // unspecified, so it is not a constant expression. However, we do know
6655 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006656 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6657 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006658 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006659 // We can't tell whether weak symbols will end up pointing to the same
6660 // object.
6661 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006662 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006663 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006664 // (Note that clang defaults to -fmerge-all-constants, which can
6665 // lead to inconsistent results for comparisons involving the address
6666 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006667 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006668 }
Eli Friedman64004332009-03-23 04:38:34 +00006669
Richard Smith1b470412012-02-01 08:10:20 +00006670 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6671 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6672
Richard Smith84f6dcf2012-02-02 01:16:57 +00006673 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6674 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6675
John McCalle3027922010-08-25 11:45:40 +00006676 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006677 // C++11 [expr.add]p6:
6678 // Unless both pointers point to elements of the same array object, or
6679 // one past the last element of the array object, the behavior is
6680 // undefined.
6681 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6682 !AreElementsOfSameArray(getType(LHSValue.Base),
6683 LHSDesignator, RHSDesignator))
6684 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6685
Chris Lattner882bdf22010-04-20 17:13:14 +00006686 QualType Type = E->getLHS()->getType();
6687 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006688
Richard Smithd62306a2011-11-10 06:34:14 +00006689 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006690 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006691 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006692
Richard Smith84c6b3d2013-09-10 21:34:14 +00006693 // As an extension, a type may have zero size (empty struct or union in
6694 // C, array of zero length). Pointer subtraction in such cases has
6695 // undefined behavior, so is not constant.
6696 if (ElementSize.isZero()) {
6697 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6698 << ElementType;
6699 return false;
6700 }
6701
Richard Smith1b470412012-02-01 08:10:20 +00006702 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6703 // and produce incorrect results when it overflows. Such behavior
6704 // appears to be non-conforming, but is common, so perhaps we should
6705 // assume the standard intended for such cases to be undefined behavior
6706 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006707
Richard Smith1b470412012-02-01 08:10:20 +00006708 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6709 // overflow in the final conversion to ptrdiff_t.
6710 APSInt LHS(
6711 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6712 APSInt RHS(
6713 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6714 APSInt ElemSize(
6715 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6716 APSInt TrueResult = (LHS - RHS) / ElemSize;
6717 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6718
6719 if (Result.extend(65) != TrueResult)
6720 HandleOverflow(Info, E, TrueResult, E->getType());
6721 return Success(Result, E);
6722 }
Richard Smithde21b242012-01-31 06:41:30 +00006723
6724 // C++11 [expr.rel]p3:
6725 // Pointers to void (after pointer conversions) can be compared, with a
6726 // result defined as follows: If both pointers represent the same
6727 // address or are both the null pointer value, the result is true if the
6728 // operator is <= or >= and false otherwise; otherwise the result is
6729 // unspecified.
6730 // We interpret this as applying to pointers to *cv* void.
6731 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006732 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006733 CCEDiag(E, diag::note_constexpr_void_comparison);
6734
Richard Smith84f6dcf2012-02-02 01:16:57 +00006735 // C++11 [expr.rel]p2:
6736 // - If two pointers point to non-static data members of the same object,
6737 // or to subobjects or array elements fo such members, recursively, the
6738 // pointer to the later declared member compares greater provided the
6739 // two members have the same access control and provided their class is
6740 // not a union.
6741 // [...]
6742 // - Otherwise pointer comparisons are unspecified.
6743 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6744 E->isRelationalOp()) {
6745 bool WasArrayIndex;
6746 unsigned Mismatch =
6747 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6748 RHSDesignator, WasArrayIndex);
6749 // At the point where the designators diverge, the comparison has a
6750 // specified value if:
6751 // - we are comparing array indices
6752 // - we are comparing fields of a union, or fields with the same access
6753 // Otherwise, the result is unspecified and thus the comparison is not a
6754 // constant expression.
6755 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6756 Mismatch < RHSDesignator.Entries.size()) {
6757 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6758 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6759 if (!LF && !RF)
6760 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6761 else if (!LF)
6762 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6763 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6764 << RF->getParent() << RF;
6765 else if (!RF)
6766 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6767 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6768 << LF->getParent() << LF;
6769 else if (!LF->getParent()->isUnion() &&
6770 LF->getAccess() != RF->getAccess())
6771 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6772 << LF << LF->getAccess() << RF << RF->getAccess()
6773 << LF->getParent();
6774 }
6775 }
6776
Eli Friedman6c31cb42012-04-16 04:30:08 +00006777 // The comparison here must be unsigned, and performed with the same
6778 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006779 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6780 uint64_t CompareLHS = LHSOffset.getQuantity();
6781 uint64_t CompareRHS = RHSOffset.getQuantity();
6782 assert(PtrSize <= 64 && "Unexpected pointer width");
6783 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6784 CompareLHS &= Mask;
6785 CompareRHS &= Mask;
6786
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006787 // If there is a base and this is a relational operator, we can only
6788 // compare pointers within the object in question; otherwise, the result
6789 // depends on where the object is located in memory.
6790 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6791 QualType BaseTy = getType(LHSValue.Base);
6792 if (BaseTy->isIncompleteType())
6793 return Error(E);
6794 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6795 uint64_t OffsetLimit = Size.getQuantity();
6796 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6797 return Error(E);
6798 }
6799
Richard Smith8b3497e2011-10-31 01:37:14 +00006800 switch (E->getOpcode()) {
6801 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006802 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6803 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6804 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6805 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6806 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6807 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006808 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006809 }
6810 }
Richard Smith7bb00672012-02-01 01:42:44 +00006811
6812 if (LHSTy->isMemberPointerType()) {
6813 assert(E->isEqualityOp() && "unexpected member pointer operation");
6814 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6815
6816 MemberPtr LHSValue, RHSValue;
6817
6818 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6819 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6820 return false;
6821
6822 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6823 return false;
6824
6825 // C++11 [expr.eq]p2:
6826 // If both operands are null, they compare equal. Otherwise if only one is
6827 // null, they compare unequal.
6828 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6829 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6830 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6831 }
6832
6833 // Otherwise if either is a pointer to a virtual member function, the
6834 // result is unspecified.
6835 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6836 if (MD->isVirtual())
6837 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6838 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6839 if (MD->isVirtual())
6840 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6841
6842 // Otherwise they compare equal if and only if they would refer to the
6843 // same member of the same most derived object or the same subobject if
6844 // they were dereferenced with a hypothetical object of the associated
6845 // class type.
6846 bool Equal = LHSValue == RHSValue;
6847 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6848 }
6849
Richard Smithab44d9b2012-02-14 22:35:28 +00006850 if (LHSTy->isNullPtrType()) {
6851 assert(E->isComparisonOp() && "unexpected nullptr operation");
6852 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6853 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6854 // are compared, the result is true of the operator is <=, >= or ==, and
6855 // false otherwise.
6856 BinaryOperator::Opcode Opcode = E->getOpcode();
6857 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6858 }
6859
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006860 assert((!LHSTy->isIntegralOrEnumerationType() ||
6861 !RHSTy->isIntegralOrEnumerationType()) &&
6862 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6863 // We can't continue from here for non-integral types.
6864 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006865}
6866
Ken Dyck160146e2010-01-27 17:10:57 +00006867CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006868 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6869 // result shall be the alignment of the referenced type."
6870 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6871 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006872
6873 // __alignof is defined to return the preferred alignment.
6874 return Info.Ctx.toCharUnitsFromBits(
6875 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006876}
6877
Ken Dyck160146e2010-01-27 17:10:57 +00006878CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006879 E = E->IgnoreParens();
6880
John McCall768439e2013-05-06 07:40:34 +00006881 // The kinds of expressions that we have special-case logic here for
6882 // should be kept up to date with the special checks for those
6883 // expressions in Sema.
6884
Chris Lattner68061312009-01-24 21:53:27 +00006885 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006886 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006887 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006888 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6889 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006890
Chris Lattner68061312009-01-24 21:53:27 +00006891 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006892 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6893 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006894
Chris Lattner24aeeab2009-01-24 21:09:06 +00006895 return GetAlignOfType(E->getType());
6896}
6897
6898
Peter Collingbournee190dee2011-03-11 19:24:49 +00006899/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6900/// a result as the expression's type.
6901bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6902 const UnaryExprOrTypeTraitExpr *E) {
6903 switch(E->getKind()) {
6904 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006905 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006906 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006907 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006908 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006909 }
Eli Friedman64004332009-03-23 04:38:34 +00006910
Peter Collingbournee190dee2011-03-11 19:24:49 +00006911 case UETT_VecStep: {
6912 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006913
Peter Collingbournee190dee2011-03-11 19:24:49 +00006914 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006915 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006916
Peter Collingbournee190dee2011-03-11 19:24:49 +00006917 // The vec_step built-in functions that take a 3-component
6918 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6919 if (n == 3)
6920 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006921
Peter Collingbournee190dee2011-03-11 19:24:49 +00006922 return Success(n, E);
6923 } else
6924 return Success(1, E);
6925 }
6926
6927 case UETT_SizeOf: {
6928 QualType SrcTy = E->getTypeOfArgument();
6929 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6930 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006931 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6932 SrcTy = Ref->getPointeeType();
6933
Richard Smithd62306a2011-11-10 06:34:14 +00006934 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006935 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006936 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006937 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006938 }
6939 }
6940
6941 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006942}
6943
Peter Collingbournee9200682011-05-13 03:29:01 +00006944bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006945 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006946 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006947 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006948 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006949 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006950 for (unsigned i = 0; i != n; ++i) {
6951 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6952 switch (ON.getKind()) {
6953 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006954 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006955 APSInt IdxResult;
6956 if (!EvaluateInteger(Idx, IdxResult, Info))
6957 return false;
6958 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6959 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006960 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006961 CurrentType = AT->getElementType();
6962 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6963 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006964 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006965 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006966
Douglas Gregor882211c2010-04-28 22:16:22 +00006967 case OffsetOfExpr::OffsetOfNode::Field: {
6968 FieldDecl *MemberDecl = ON.getField();
6969 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006970 if (!RT)
6971 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006972 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006973 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006974 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006975 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006976 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006977 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006978 CurrentType = MemberDecl->getType().getNonReferenceType();
6979 break;
6980 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006981
Douglas Gregor882211c2010-04-28 22:16:22 +00006982 case OffsetOfExpr::OffsetOfNode::Identifier:
6983 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006984
Douglas Gregord1702062010-04-29 00:18:15 +00006985 case OffsetOfExpr::OffsetOfNode::Base: {
6986 CXXBaseSpecifier *BaseSpec = ON.getBase();
6987 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006988 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006989
6990 // Find the layout of the class whose base we are looking into.
6991 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006992 if (!RT)
6993 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006994 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006995 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006996 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6997
6998 // Find the base class itself.
6999 CurrentType = BaseSpec->getType();
7000 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7001 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007002 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007003
7004 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007005 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007006 break;
7007 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007008 }
7009 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007010 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007011}
7012
Chris Lattnere13042c2008-07-11 19:10:17 +00007013bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007014 switch (E->getOpcode()) {
7015 default:
7016 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7017 // See C99 6.6p3.
7018 return Error(E);
7019 case UO_Extension:
7020 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7021 // If so, we could clear the diagnostic ID.
7022 return Visit(E->getSubExpr());
7023 case UO_Plus:
7024 // The result is just the value.
7025 return Visit(E->getSubExpr());
7026 case UO_Minus: {
7027 if (!Visit(E->getSubExpr()))
7028 return false;
7029 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007030 const APSInt &Value = Result.getInt();
7031 if (Value.isSigned() && Value.isMinSignedValue())
7032 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7033 E->getType());
7034 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007035 }
7036 case UO_Not: {
7037 if (!Visit(E->getSubExpr()))
7038 return false;
7039 if (!Result.isInt()) return Error(E);
7040 return Success(~Result.getInt(), E);
7041 }
7042 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007043 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007044 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007045 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007046 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007047 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007048 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007049}
Mike Stump11289f42009-09-09 15:08:12 +00007050
Chris Lattner477c4be2008-07-12 01:15:53 +00007051/// HandleCast - This is used to evaluate implicit or explicit casts where the
7052/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007053bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7054 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007055 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007056 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007057
Eli Friedmanc757de22011-03-25 00:43:55 +00007058 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007059 case CK_BaseToDerived:
7060 case CK_DerivedToBase:
7061 case CK_UncheckedDerivedToBase:
7062 case CK_Dynamic:
7063 case CK_ToUnion:
7064 case CK_ArrayToPointerDecay:
7065 case CK_FunctionToPointerDecay:
7066 case CK_NullToPointer:
7067 case CK_NullToMemberPointer:
7068 case CK_BaseToDerivedMemberPointer:
7069 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007070 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007071 case CK_ConstructorConversion:
7072 case CK_IntegralToPointer:
7073 case CK_ToVoid:
7074 case CK_VectorSplat:
7075 case CK_IntegralToFloating:
7076 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007077 case CK_CPointerToObjCPointerCast:
7078 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007079 case CK_AnyPointerToBlockPointerCast:
7080 case CK_ObjCObjectLValueCast:
7081 case CK_FloatingRealToComplex:
7082 case CK_FloatingComplexToReal:
7083 case CK_FloatingComplexCast:
7084 case CK_FloatingComplexToIntegralComplex:
7085 case CK_IntegralRealToComplex:
7086 case CK_IntegralComplexCast:
7087 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007088 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007089 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007090 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007091 llvm_unreachable("invalid cast kind for integral value");
7092
Eli Friedman9faf2f92011-03-25 19:07:11 +00007093 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007094 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007095 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007096 case CK_ARCProduceObject:
7097 case CK_ARCConsumeObject:
7098 case CK_ARCReclaimReturnedObject:
7099 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007100 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007101 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007102
Richard Smith4ef685b2012-01-17 21:17:26 +00007103 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007104 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007105 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007106 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007107 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007108
7109 case CK_MemberPointerToBoolean:
7110 case CK_PointerToBoolean:
7111 case CK_IntegralToBoolean:
7112 case CK_FloatingToBoolean:
7113 case CK_FloatingComplexToBoolean:
7114 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007115 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007116 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007117 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007118 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007119 }
7120
Eli Friedmanc757de22011-03-25 00:43:55 +00007121 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007122 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007123 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007124
Eli Friedman742421e2009-02-20 01:15:07 +00007125 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007126 // Allow casts of address-of-label differences if they are no-ops
7127 // or narrowing. (The narrowing case isn't actually guaranteed to
7128 // be constant-evaluatable except in some narrow cases which are hard
7129 // to detect here. We let it through on the assumption the user knows
7130 // what they are doing.)
7131 if (Result.isAddrLabelDiff())
7132 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007133 // Only allow casts of lvalues if they are lossless.
7134 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7135 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007136
Richard Smith911e1422012-01-30 22:27:01 +00007137 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7138 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007139 }
Mike Stump11289f42009-09-09 15:08:12 +00007140
Eli Friedmanc757de22011-03-25 00:43:55 +00007141 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007142 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7143
John McCall45d55e42010-05-07 21:00:08 +00007144 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007145 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007146 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007147
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007148 if (LV.getLValueBase()) {
7149 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007150 // FIXME: Allow a larger integer size than the pointer size, and allow
7151 // narrowing back down to pointer width in subsequent integral casts.
7152 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007153 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007154 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007155
Richard Smithcf74da72011-11-16 07:18:12 +00007156 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007157 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007158 return true;
7159 }
7160
Ken Dyck02990832010-01-15 12:37:54 +00007161 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7162 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007163 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007164 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007165
Eli Friedmanc757de22011-03-25 00:43:55 +00007166 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007167 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007168 if (!EvaluateComplex(SubExpr, C, Info))
7169 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007170 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007171 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007172
Eli Friedmanc757de22011-03-25 00:43:55 +00007173 case CK_FloatingToIntegral: {
7174 APFloat F(0.0);
7175 if (!EvaluateFloat(SubExpr, F, Info))
7176 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007177
Richard Smith357362d2011-12-13 06:39:58 +00007178 APSInt Value;
7179 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7180 return false;
7181 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007182 }
7183 }
Mike Stump11289f42009-09-09 15:08:12 +00007184
Eli Friedmanc757de22011-03-25 00:43:55 +00007185 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007186}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007187
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007188bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7189 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007190 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007191 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7192 return false;
7193 if (!LV.isComplexInt())
7194 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007195 return Success(LV.getComplexIntReal(), E);
7196 }
7197
7198 return Visit(E->getSubExpr());
7199}
7200
Eli Friedman4e7a2412009-02-27 04:45:43 +00007201bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007202 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007203 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007204 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7205 return false;
7206 if (!LV.isComplexInt())
7207 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007208 return Success(LV.getComplexIntImag(), E);
7209 }
7210
Richard Smith4a678122011-10-24 18:44:57 +00007211 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007212 return Success(0, E);
7213}
7214
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007215bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7216 return Success(E->getPackLength(), E);
7217}
7218
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007219bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7220 return Success(E->getValue(), E);
7221}
7222
Chris Lattner05706e882008-07-11 18:11:29 +00007223//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007224// Float Evaluation
7225//===----------------------------------------------------------------------===//
7226
7227namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007228class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007229 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007230 APFloat &Result;
7231public:
7232 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007233 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007234
Richard Smith2e312c82012-03-03 22:46:17 +00007235 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007236 Result = V.getFloat();
7237 return true;
7238 }
Eli Friedman24c01542008-08-22 00:06:13 +00007239
Richard Smithfddd3842011-12-30 21:15:51 +00007240 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007241 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7242 return true;
7243 }
7244
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007245 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007246
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007247 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007248 bool VisitBinaryOperator(const BinaryOperator *E);
7249 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007250 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007251
John McCallb1fb0d32010-05-07 22:08:54 +00007252 bool VisitUnaryReal(const UnaryOperator *E);
7253 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007254
Richard Smithfddd3842011-12-30 21:15:51 +00007255 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007256};
7257} // end anonymous namespace
7258
7259static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007260 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007261 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007262}
7263
Jay Foad39c79802011-01-12 09:06:06 +00007264static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007265 QualType ResultTy,
7266 const Expr *Arg,
7267 bool SNaN,
7268 llvm::APFloat &Result) {
7269 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7270 if (!S) return false;
7271
7272 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7273
7274 llvm::APInt fill;
7275
7276 // Treat empty strings as if they were zero.
7277 if (S->getString().empty())
7278 fill = llvm::APInt(32, 0);
7279 else if (S->getString().getAsInteger(0, fill))
7280 return false;
7281
7282 if (SNaN)
7283 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7284 else
7285 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7286 return true;
7287}
7288
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007289bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007290 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007291 default:
7292 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7293
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007294 case Builtin::BI__builtin_huge_val:
7295 case Builtin::BI__builtin_huge_valf:
7296 case Builtin::BI__builtin_huge_vall:
7297 case Builtin::BI__builtin_inf:
7298 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007299 case Builtin::BI__builtin_infl: {
7300 const llvm::fltSemantics &Sem =
7301 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007302 Result = llvm::APFloat::getInf(Sem);
7303 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007304 }
Mike Stump11289f42009-09-09 15:08:12 +00007305
John McCall16291492010-02-28 13:00:19 +00007306 case Builtin::BI__builtin_nans:
7307 case Builtin::BI__builtin_nansf:
7308 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007309 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7310 true, Result))
7311 return Error(E);
7312 return true;
John McCall16291492010-02-28 13:00:19 +00007313
Chris Lattner0b7282e2008-10-06 06:31:58 +00007314 case Builtin::BI__builtin_nan:
7315 case Builtin::BI__builtin_nanf:
7316 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007317 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007318 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007319 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7320 false, Result))
7321 return Error(E);
7322 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007323
7324 case Builtin::BI__builtin_fabs:
7325 case Builtin::BI__builtin_fabsf:
7326 case Builtin::BI__builtin_fabsl:
7327 if (!EvaluateFloat(E->getArg(0), Result, Info))
7328 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007329
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007330 if (Result.isNegative())
7331 Result.changeSign();
7332 return true;
7333
Richard Smith8889a3d2013-06-13 06:26:32 +00007334 // FIXME: Builtin::BI__builtin_powi
7335 // FIXME: Builtin::BI__builtin_powif
7336 // FIXME: Builtin::BI__builtin_powil
7337
Mike Stump11289f42009-09-09 15:08:12 +00007338 case Builtin::BI__builtin_copysign:
7339 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007340 case Builtin::BI__builtin_copysignl: {
7341 APFloat RHS(0.);
7342 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7343 !EvaluateFloat(E->getArg(1), RHS, Info))
7344 return false;
7345 Result.copySign(RHS);
7346 return true;
7347 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007348 }
7349}
7350
John McCallb1fb0d32010-05-07 22:08:54 +00007351bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007352 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7353 ComplexValue CV;
7354 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7355 return false;
7356 Result = CV.FloatReal;
7357 return true;
7358 }
7359
7360 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007361}
7362
7363bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007364 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7365 ComplexValue CV;
7366 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7367 return false;
7368 Result = CV.FloatImag;
7369 return true;
7370 }
7371
Richard Smith4a678122011-10-24 18:44:57 +00007372 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007373 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7374 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007375 return true;
7376}
7377
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007378bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007379 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007380 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007381 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007382 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007383 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007384 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7385 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007386 Result.changeSign();
7387 return true;
7388 }
7389}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007390
Eli Friedman24c01542008-08-22 00:06:13 +00007391bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007392 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7393 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007394
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007395 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007396 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7397 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007398 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007399 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7400 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007401}
7402
7403bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7404 Result = E->getValue();
7405 return true;
7406}
7407
Peter Collingbournee9200682011-05-13 03:29:01 +00007408bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7409 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007410
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007411 switch (E->getCastKind()) {
7412 default:
Richard Smith11562c52011-10-28 17:51:58 +00007413 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007414
7415 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007416 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007417 return EvaluateInteger(SubExpr, IntResult, Info) &&
7418 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7419 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007420 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007421
7422 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007423 if (!Visit(SubExpr))
7424 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007425 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7426 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007427 }
John McCalld7646252010-11-14 08:17:51 +00007428
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007429 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007430 ComplexValue V;
7431 if (!EvaluateComplex(SubExpr, V, Info))
7432 return false;
7433 Result = V.getComplexFloatReal();
7434 return true;
7435 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007436 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007437}
7438
Eli Friedman24c01542008-08-22 00:06:13 +00007439//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007440// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007441//===----------------------------------------------------------------------===//
7442
7443namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007444class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007445 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007446 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007447
Anders Carlsson537969c2008-11-16 20:27:53 +00007448public:
John McCall93d91dc2010-05-07 17:22:02 +00007449 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007450 : ExprEvaluatorBaseTy(info), Result(Result) {}
7451
Richard Smith2e312c82012-03-03 22:46:17 +00007452 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007453 Result.setFrom(V);
7454 return true;
7455 }
Mike Stump11289f42009-09-09 15:08:12 +00007456
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007457 bool ZeroInitialization(const Expr *E);
7458
Anders Carlsson537969c2008-11-16 20:27:53 +00007459 //===--------------------------------------------------------------------===//
7460 // Visitor Methods
7461 //===--------------------------------------------------------------------===//
7462
Peter Collingbournee9200682011-05-13 03:29:01 +00007463 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007464 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007465 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007466 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007467 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007468};
7469} // end anonymous namespace
7470
John McCall93d91dc2010-05-07 17:22:02 +00007471static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7472 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007473 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007474 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007475}
7476
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007477bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007478 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007479 if (ElemTy->isRealFloatingType()) {
7480 Result.makeComplexFloat();
7481 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7482 Result.FloatReal = Zero;
7483 Result.FloatImag = Zero;
7484 } else {
7485 Result.makeComplexInt();
7486 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7487 Result.IntReal = Zero;
7488 Result.IntImag = Zero;
7489 }
7490 return true;
7491}
7492
Peter Collingbournee9200682011-05-13 03:29:01 +00007493bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7494 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007495
7496 if (SubExpr->getType()->isRealFloatingType()) {
7497 Result.makeComplexFloat();
7498 APFloat &Imag = Result.FloatImag;
7499 if (!EvaluateFloat(SubExpr, Imag, Info))
7500 return false;
7501
7502 Result.FloatReal = APFloat(Imag.getSemantics());
7503 return true;
7504 } else {
7505 assert(SubExpr->getType()->isIntegerType() &&
7506 "Unexpected imaginary literal.");
7507
7508 Result.makeComplexInt();
7509 APSInt &Imag = Result.IntImag;
7510 if (!EvaluateInteger(SubExpr, Imag, Info))
7511 return false;
7512
7513 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7514 return true;
7515 }
7516}
7517
Peter Collingbournee9200682011-05-13 03:29:01 +00007518bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007519
John McCallfcef3cf2010-12-14 17:51:41 +00007520 switch (E->getCastKind()) {
7521 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007522 case CK_BaseToDerived:
7523 case CK_DerivedToBase:
7524 case CK_UncheckedDerivedToBase:
7525 case CK_Dynamic:
7526 case CK_ToUnion:
7527 case CK_ArrayToPointerDecay:
7528 case CK_FunctionToPointerDecay:
7529 case CK_NullToPointer:
7530 case CK_NullToMemberPointer:
7531 case CK_BaseToDerivedMemberPointer:
7532 case CK_DerivedToBaseMemberPointer:
7533 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007534 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007535 case CK_ConstructorConversion:
7536 case CK_IntegralToPointer:
7537 case CK_PointerToIntegral:
7538 case CK_PointerToBoolean:
7539 case CK_ToVoid:
7540 case CK_VectorSplat:
7541 case CK_IntegralCast:
7542 case CK_IntegralToBoolean:
7543 case CK_IntegralToFloating:
7544 case CK_FloatingToIntegral:
7545 case CK_FloatingToBoolean:
7546 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007547 case CK_CPointerToObjCPointerCast:
7548 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007549 case CK_AnyPointerToBlockPointerCast:
7550 case CK_ObjCObjectLValueCast:
7551 case CK_FloatingComplexToReal:
7552 case CK_FloatingComplexToBoolean:
7553 case CK_IntegralComplexToReal:
7554 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007555 case CK_ARCProduceObject:
7556 case CK_ARCConsumeObject:
7557 case CK_ARCReclaimReturnedObject:
7558 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007559 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007560 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007561 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007562 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007563 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007564
John McCallfcef3cf2010-12-14 17:51:41 +00007565 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007566 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007567 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007568 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007569
7570 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007571 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007572 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007573 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007574
7575 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007576 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007577 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007578 return false;
7579
John McCallfcef3cf2010-12-14 17:51:41 +00007580 Result.makeComplexFloat();
7581 Result.FloatImag = APFloat(Real.getSemantics());
7582 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007583 }
7584
John McCallfcef3cf2010-12-14 17:51:41 +00007585 case CK_FloatingComplexCast: {
7586 if (!Visit(E->getSubExpr()))
7587 return false;
7588
7589 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7590 QualType From
7591 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7592
Richard Smith357362d2011-12-13 06:39:58 +00007593 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7594 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007595 }
7596
7597 case CK_FloatingComplexToIntegralComplex: {
7598 if (!Visit(E->getSubExpr()))
7599 return false;
7600
7601 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7602 QualType From
7603 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7604 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007605 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7606 To, Result.IntReal) &&
7607 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7608 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007609 }
7610
7611 case CK_IntegralRealToComplex: {
7612 APSInt &Real = Result.IntReal;
7613 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7614 return false;
7615
7616 Result.makeComplexInt();
7617 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7618 return true;
7619 }
7620
7621 case CK_IntegralComplexCast: {
7622 if (!Visit(E->getSubExpr()))
7623 return false;
7624
7625 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7626 QualType From
7627 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7628
Richard Smith911e1422012-01-30 22:27:01 +00007629 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7630 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007631 return true;
7632 }
7633
7634 case CK_IntegralComplexToFloatingComplex: {
7635 if (!Visit(E->getSubExpr()))
7636 return false;
7637
Ted Kremenek28831752012-08-23 20:46:57 +00007638 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007639 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007640 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007641 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007642 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7643 To, Result.FloatReal) &&
7644 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7645 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007646 }
7647 }
7648
7649 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007650}
7651
John McCall93d91dc2010-05-07 17:22:02 +00007652bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007653 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007654 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7655
Richard Smith253c2a32012-01-27 01:14:48 +00007656 bool LHSOK = Visit(E->getLHS());
7657 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007658 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007659
John McCall93d91dc2010-05-07 17:22:02 +00007660 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007661 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007662 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007663
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007664 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7665 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007666 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007667 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007668 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007669 if (Result.isComplexFloat()) {
7670 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7671 APFloat::rmNearestTiesToEven);
7672 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7673 APFloat::rmNearestTiesToEven);
7674 } else {
7675 Result.getComplexIntReal() += RHS.getComplexIntReal();
7676 Result.getComplexIntImag() += RHS.getComplexIntImag();
7677 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007678 break;
John McCalle3027922010-08-25 11:45:40 +00007679 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007680 if (Result.isComplexFloat()) {
7681 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7682 APFloat::rmNearestTiesToEven);
7683 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7684 APFloat::rmNearestTiesToEven);
7685 } else {
7686 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7687 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7688 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007689 break;
John McCalle3027922010-08-25 11:45:40 +00007690 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007691 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007692 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007693 APFloat &LHS_r = LHS.getComplexFloatReal();
7694 APFloat &LHS_i = LHS.getComplexFloatImag();
7695 APFloat &RHS_r = RHS.getComplexFloatReal();
7696 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007697
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007698 APFloat Tmp = LHS_r;
7699 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7700 Result.getComplexFloatReal() = Tmp;
7701 Tmp = LHS_i;
7702 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7703 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7704
7705 Tmp = LHS_r;
7706 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7707 Result.getComplexFloatImag() = Tmp;
7708 Tmp = LHS_i;
7709 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7710 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7711 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007712 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007713 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007714 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7715 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007716 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007717 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7718 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7719 }
7720 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007721 case BO_Div:
7722 if (Result.isComplexFloat()) {
7723 ComplexValue LHS = Result;
7724 APFloat &LHS_r = LHS.getComplexFloatReal();
7725 APFloat &LHS_i = LHS.getComplexFloatImag();
7726 APFloat &RHS_r = RHS.getComplexFloatReal();
7727 APFloat &RHS_i = RHS.getComplexFloatImag();
7728 APFloat &Res_r = Result.getComplexFloatReal();
7729 APFloat &Res_i = Result.getComplexFloatImag();
7730
7731 APFloat Den = RHS_r;
7732 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7733 APFloat Tmp = RHS_i;
7734 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7735 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7736
7737 Res_r = LHS_r;
7738 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7739 Tmp = LHS_i;
7740 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7741 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7742 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7743
7744 Res_i = LHS_i;
7745 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7746 Tmp = LHS_r;
7747 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7748 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7749 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7750 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007751 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7752 return Error(E, diag::note_expr_divide_by_zero);
7753
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007754 ComplexValue LHS = Result;
7755 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7756 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7757 Result.getComplexIntReal() =
7758 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7759 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7760 Result.getComplexIntImag() =
7761 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7762 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7763 }
7764 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007765 }
7766
John McCall93d91dc2010-05-07 17:22:02 +00007767 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007768}
7769
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007770bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7771 // Get the operand value into 'Result'.
7772 if (!Visit(E->getSubExpr()))
7773 return false;
7774
7775 switch (E->getOpcode()) {
7776 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007777 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007778 case UO_Extension:
7779 return true;
7780 case UO_Plus:
7781 // The result is always just the subexpr.
7782 return true;
7783 case UO_Minus:
7784 if (Result.isComplexFloat()) {
7785 Result.getComplexFloatReal().changeSign();
7786 Result.getComplexFloatImag().changeSign();
7787 }
7788 else {
7789 Result.getComplexIntReal() = -Result.getComplexIntReal();
7790 Result.getComplexIntImag() = -Result.getComplexIntImag();
7791 }
7792 return true;
7793 case UO_Not:
7794 if (Result.isComplexFloat())
7795 Result.getComplexFloatImag().changeSign();
7796 else
7797 Result.getComplexIntImag() = -Result.getComplexIntImag();
7798 return true;
7799 }
7800}
7801
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007802bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7803 if (E->getNumInits() == 2) {
7804 if (E->getType()->isComplexType()) {
7805 Result.makeComplexFloat();
7806 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7807 return false;
7808 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7809 return false;
7810 } else {
7811 Result.makeComplexInt();
7812 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7813 return false;
7814 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7815 return false;
7816 }
7817 return true;
7818 }
7819 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7820}
7821
Anders Carlsson537969c2008-11-16 20:27:53 +00007822//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007823// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7824// implicit conversion.
7825//===----------------------------------------------------------------------===//
7826
7827namespace {
7828class AtomicExprEvaluator :
7829 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7830 APValue &Result;
7831public:
7832 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7833 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7834
7835 bool Success(const APValue &V, const Expr *E) {
7836 Result = V;
7837 return true;
7838 }
7839
7840 bool ZeroInitialization(const Expr *E) {
7841 ImplicitValueInitExpr VIE(
7842 E->getType()->castAs<AtomicType>()->getValueType());
7843 return Evaluate(Result, Info, &VIE);
7844 }
7845
7846 bool VisitCastExpr(const CastExpr *E) {
7847 switch (E->getCastKind()) {
7848 default:
7849 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7850 case CK_NonAtomicToAtomic:
7851 return Evaluate(Result, Info, E->getSubExpr());
7852 }
7853 }
7854};
7855} // end anonymous namespace
7856
7857static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7858 assert(E->isRValue() && E->getType()->isAtomicType());
7859 return AtomicExprEvaluator(Info, Result).Visit(E);
7860}
7861
7862//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007863// Void expression evaluation, primarily for a cast to void on the LHS of a
7864// comma operator
7865//===----------------------------------------------------------------------===//
7866
7867namespace {
7868class VoidExprEvaluator
7869 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7870public:
7871 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7872
Richard Smith2e312c82012-03-03 22:46:17 +00007873 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007874
7875 bool VisitCastExpr(const CastExpr *E) {
7876 switch (E->getCastKind()) {
7877 default:
7878 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7879 case CK_ToVoid:
7880 VisitIgnoredValue(E->getSubExpr());
7881 return true;
7882 }
7883 }
7884};
7885} // end anonymous namespace
7886
7887static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7888 assert(E->isRValue() && E->getType()->isVoidType());
7889 return VoidExprEvaluator(Info).Visit(E);
7890}
7891
7892//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007893// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007894//===----------------------------------------------------------------------===//
7895
Richard Smith2e312c82012-03-03 22:46:17 +00007896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007897 // In C, function designators are not lvalues, but we evaluate them as if they
7898 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007899 QualType T = E->getType();
7900 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007901 LValue LV;
7902 if (!EvaluateLValue(E, LV, Info))
7903 return false;
7904 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007905 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007906 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007907 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007908 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007909 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007910 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007911 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007912 LValue LV;
7913 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007914 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007915 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007916 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007917 llvm::APFloat F(0.0);
7918 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007919 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007920 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007921 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007922 ComplexValue C;
7923 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007924 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007925 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007926 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007927 MemberPtr P;
7928 if (!EvaluateMemberPointer(E, P, Info))
7929 return false;
7930 P.moveInto(Result);
7931 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007932 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007933 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007934 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007935 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7936 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007937 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007938 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007939 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007940 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007941 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007942 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7943 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007944 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007945 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007946 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007947 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007948 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007949 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007950 if (!EvaluateVoid(E, Info))
7951 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007952 } else if (T->isAtomicType()) {
7953 if (!EvaluateAtomic(E, Result, Info))
7954 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007955 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007956 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007957 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007958 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007959 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007960 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007961 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007962
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007963 return true;
7964}
7965
Richard Smithb228a862012-02-15 02:18:13 +00007966/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7967/// cases, the in-place evaluation is essential, since later initializers for
7968/// an object can indirectly refer to subobjects which were initialized earlier.
7969static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007970 const Expr *E, bool AllowNonLiteralTypes) {
7971 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007972 return false;
7973
7974 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007975 // Evaluate arrays and record types in-place, so that later initializers can
7976 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007977 if (E->getType()->isArrayType())
7978 return EvaluateArray(E, This, Result, Info);
7979 else if (E->getType()->isRecordType())
7980 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007981 }
7982
7983 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007984 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007985}
7986
Richard Smithf57d8cb2011-12-09 22:58:01 +00007987/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7988/// lvalue-to-rvalue cast if it is an lvalue.
7989static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007990 if (!CheckLiteralType(Info, E))
7991 return false;
7992
Richard Smith2e312c82012-03-03 22:46:17 +00007993 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007994 return false;
7995
7996 if (E->isGLValue()) {
7997 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007998 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007999 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008000 return false;
8001 }
8002
Richard Smith2e312c82012-03-03 22:46:17 +00008003 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008004 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008005}
Richard Smith11562c52011-10-28 17:51:58 +00008006
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008007static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8008 const ASTContext &Ctx, bool &IsConst) {
8009 // Fast-path evaluations of integer literals, since we sometimes see files
8010 // containing vast quantities of these.
8011 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8012 Result.Val = APValue(APSInt(L->getValue(),
8013 L->getType()->isUnsignedIntegerType()));
8014 IsConst = true;
8015 return true;
8016 }
8017
8018 // FIXME: Evaluating values of large array and record types can cause
8019 // performance problems. Only do so in C++11 for now.
8020 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8021 Exp->getType()->isRecordType()) &&
8022 !Ctx.getLangOpts().CPlusPlus11) {
8023 IsConst = false;
8024 return true;
8025 }
8026 return false;
8027}
8028
8029
Richard Smith7b553f12011-10-29 00:50:52 +00008030/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008031/// any crazy technique (that has nothing to do with language standards) that
8032/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008033/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8034/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008035bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008036 bool IsConst;
8037 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8038 return IsConst;
8039
Richard Smith6d4c6582013-11-05 22:18:15 +00008040 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008041 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008042}
8043
Jay Foad39c79802011-01-12 09:06:06 +00008044bool Expr::EvaluateAsBooleanCondition(bool &Result,
8045 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008046 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008047 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008048 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008049}
8050
Richard Smith5fab0c92011-12-28 19:48:30 +00008051bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8052 SideEffectsKind AllowSideEffects) const {
8053 if (!getType()->isIntegralOrEnumerationType())
8054 return false;
8055
Richard Smith11562c52011-10-28 17:51:58 +00008056 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008057 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8058 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008059 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008060
Richard Smith11562c52011-10-28 17:51:58 +00008061 Result = ExprResult.Val.getInt();
8062 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008063}
8064
Jay Foad39c79802011-01-12 09:06:06 +00008065bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008066 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008067
John McCall45d55e42010-05-07 21:00:08 +00008068 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008069 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8070 !CheckLValueConstantExpression(Info, getExprLoc(),
8071 Ctx.getLValueReferenceType(getType()), LV))
8072 return false;
8073
Richard Smith2e312c82012-03-03 22:46:17 +00008074 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008075 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008076}
8077
Richard Smithd0b4dd62011-12-19 06:19:21 +00008078bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8079 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008080 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008081 // FIXME: Evaluating initializers for large array and record types can cause
8082 // performance problems. Only do so in C++11 for now.
8083 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008084 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008085 return false;
8086
Richard Smithd0b4dd62011-12-19 06:19:21 +00008087 Expr::EvalStatus EStatus;
8088 EStatus.Diag = &Notes;
8089
Richard Smith6d4c6582013-11-05 22:18:15 +00008090 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008091 InitInfo.setEvaluatingDecl(VD, Value);
8092
8093 LValue LVal;
8094 LVal.set(VD);
8095
Richard Smithfddd3842011-12-30 21:15:51 +00008096 // C++11 [basic.start.init]p2:
8097 // Variables with static storage duration or thread storage duration shall be
8098 // zero-initialized before any other initialization takes place.
8099 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008100 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008101 !VD->getType()->isReferenceType()) {
8102 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008103 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008104 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008105 return false;
8106 }
8107
Richard Smith7525ff62013-05-09 07:14:00 +00008108 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8109 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008110 EStatus.HasSideEffects)
8111 return false;
8112
8113 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8114 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008115}
8116
Richard Smith7b553f12011-10-29 00:50:52 +00008117/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8118/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008119bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008120 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008121 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008122}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008123
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008124APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008125 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008126 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008127 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008128 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008129 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008130 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008131 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008132
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008133 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008134}
John McCall864e3962010-05-07 05:32:02 +00008135
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008136void Expr::EvaluateForOverflow(const ASTContext &Ctx,
8137 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
8138 bool IsConst;
8139 EvalResult EvalResult;
8140 EvalResult.Diag = Diags;
8141 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008142 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008143 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8144 }
8145}
8146
Richard Smithe6c01442013-06-05 00:46:14 +00008147bool Expr::EvalResult::isGlobalLValue() const {
8148 assert(Val.isLValue());
8149 return IsGlobalLValue(Val.getLValueBase());
8150}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008151
8152
John McCall864e3962010-05-07 05:32:02 +00008153/// isIntegerConstantExpr - this recursive routine will test if an expression is
8154/// an integer constant expression.
8155
8156/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8157/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008158
8159// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008160// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8161// and a (possibly null) SourceLocation indicating the location of the problem.
8162//
John McCall864e3962010-05-07 05:32:02 +00008163// Note that to reduce code duplication, this helper does no evaluation
8164// itself; the caller checks whether the expression is evaluatable, and
8165// in the rare cases where CheckICE actually cares about the evaluated
8166// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008167
Dan Gohman28ade552010-07-26 21:25:24 +00008168namespace {
8169
Richard Smith9e575da2012-12-28 13:25:52 +00008170enum ICEKind {
8171 /// This expression is an ICE.
8172 IK_ICE,
8173 /// This expression is not an ICE, but if it isn't evaluated, it's
8174 /// a legal subexpression for an ICE. This return value is used to handle
8175 /// the comma operator in C99 mode, and non-constant subexpressions.
8176 IK_ICEIfUnevaluated,
8177 /// This expression is not an ICE, and is not a legal subexpression for one.
8178 IK_NotICE
8179};
8180
John McCall864e3962010-05-07 05:32:02 +00008181struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008182 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008183 SourceLocation Loc;
8184
Richard Smith9e575da2012-12-28 13:25:52 +00008185 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008186};
8187
Dan Gohman28ade552010-07-26 21:25:24 +00008188}
8189
Richard Smith9e575da2012-12-28 13:25:52 +00008190static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8191
8192static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008193
Craig Toppera31a8822013-08-22 07:09:37 +00008194static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008195 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008196 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008197 !EVResult.Val.isInt())
8198 return ICEDiag(IK_NotICE, E->getLocStart());
8199
John McCall864e3962010-05-07 05:32:02 +00008200 return NoDiag();
8201}
8202
Craig Toppera31a8822013-08-22 07:09:37 +00008203static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008204 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008205 if (!E->getType()->isIntegralOrEnumerationType())
8206 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008207
8208 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008209#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008210#define STMT(Node, Base) case Expr::Node##Class:
8211#define EXPR(Node, Base)
8212#include "clang/AST/StmtNodes.inc"
8213 case Expr::PredefinedExprClass:
8214 case Expr::FloatingLiteralClass:
8215 case Expr::ImaginaryLiteralClass:
8216 case Expr::StringLiteralClass:
8217 case Expr::ArraySubscriptExprClass:
8218 case Expr::MemberExprClass:
8219 case Expr::CompoundAssignOperatorClass:
8220 case Expr::CompoundLiteralExprClass:
8221 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008222 case Expr::DesignatedInitExprClass:
8223 case Expr::ImplicitValueInitExprClass:
8224 case Expr::ParenListExprClass:
8225 case Expr::VAArgExprClass:
8226 case Expr::AddrLabelExprClass:
8227 case Expr::StmtExprClass:
8228 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008229 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008230 case Expr::CXXDynamicCastExprClass:
8231 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008232 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008233 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008234 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008235 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008236 case Expr::CXXThisExprClass:
8237 case Expr::CXXThrowExprClass:
8238 case Expr::CXXNewExprClass:
8239 case Expr::CXXDeleteExprClass:
8240 case Expr::CXXPseudoDestructorExprClass:
8241 case Expr::UnresolvedLookupExprClass:
8242 case Expr::DependentScopeDeclRefExprClass:
8243 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008244 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008245 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008246 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008247 case Expr::CXXTemporaryObjectExprClass:
8248 case Expr::CXXUnresolvedConstructExprClass:
8249 case Expr::CXXDependentScopeMemberExprClass:
8250 case Expr::UnresolvedMemberExprClass:
8251 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008252 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008253 case Expr::ObjCArrayLiteralClass:
8254 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008255 case Expr::ObjCEncodeExprClass:
8256 case Expr::ObjCMessageExprClass:
8257 case Expr::ObjCSelectorExprClass:
8258 case Expr::ObjCProtocolExprClass:
8259 case Expr::ObjCIvarRefExprClass:
8260 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008261 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008262 case Expr::ObjCIsaExprClass:
8263 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008264 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008265 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008266 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008267 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008268 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008269 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008270 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008271 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008272 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008273 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008274 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008275 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00008276 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008277 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008278 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008279
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008280 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008281 case Expr::GNUNullExprClass:
8282 // GCC considers the GNU __null value to be an integral constant expression.
8283 return NoDiag();
8284
John McCall7c454bb2011-07-15 05:09:51 +00008285 case Expr::SubstNonTypeTemplateParmExprClass:
8286 return
8287 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8288
John McCall864e3962010-05-07 05:32:02 +00008289 case Expr::ParenExprClass:
8290 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008291 case Expr::GenericSelectionExprClass:
8292 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008293 case Expr::IntegerLiteralClass:
8294 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008295 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008296 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008297 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008298 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008299 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008300 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008301 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008302 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008303 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008304 return NoDiag();
8305 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008306 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008307 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8308 // constant expressions, but they can never be ICEs because an ICE cannot
8309 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008310 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008311 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008312 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008313 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008314 }
Richard Smith6365c912012-02-24 22:12:32 +00008315 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008316 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8317 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008318 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008319 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008320 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008321 // Parameter variables are never constants. Without this check,
8322 // getAnyInitializer() can find a default argument, which leads
8323 // to chaos.
8324 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008325 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008326
8327 // C++ 7.1.5.1p2
8328 // A variable of non-volatile const-qualified integral or enumeration
8329 // type initialized by an ICE can be used in ICEs.
8330 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008331 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008332 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008333
Richard Smithd0b4dd62011-12-19 06:19:21 +00008334 const VarDecl *VD;
8335 // Look for a declaration of this variable that has an initializer, and
8336 // check whether it is an ICE.
8337 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8338 return NoDiag();
8339 else
Richard Smith9e575da2012-12-28 13:25:52 +00008340 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008341 }
8342 }
Richard Smith9e575da2012-12-28 13:25:52 +00008343 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008344 }
John McCall864e3962010-05-07 05:32:02 +00008345 case Expr::UnaryOperatorClass: {
8346 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8347 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008348 case UO_PostInc:
8349 case UO_PostDec:
8350 case UO_PreInc:
8351 case UO_PreDec:
8352 case UO_AddrOf:
8353 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008354 // C99 6.6/3 allows increment and decrement within unevaluated
8355 // subexpressions of constant expressions, but they can never be ICEs
8356 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008357 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008358 case UO_Extension:
8359 case UO_LNot:
8360 case UO_Plus:
8361 case UO_Minus:
8362 case UO_Not:
8363 case UO_Real:
8364 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008365 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008366 }
Richard Smith9e575da2012-12-28 13:25:52 +00008367
John McCall864e3962010-05-07 05:32:02 +00008368 // OffsetOf falls through here.
8369 }
8370 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008371 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8372 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8373 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8374 // compliance: we should warn earlier for offsetof expressions with
8375 // array subscripts that aren't ICEs, and if the array subscripts
8376 // are ICEs, the value of the offsetof must be an integer constant.
8377 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008378 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008379 case Expr::UnaryExprOrTypeTraitExprClass: {
8380 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8381 if ((Exp->getKind() == UETT_SizeOf) &&
8382 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008383 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008384 return NoDiag();
8385 }
8386 case Expr::BinaryOperatorClass: {
8387 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8388 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008389 case BO_PtrMemD:
8390 case BO_PtrMemI:
8391 case BO_Assign:
8392 case BO_MulAssign:
8393 case BO_DivAssign:
8394 case BO_RemAssign:
8395 case BO_AddAssign:
8396 case BO_SubAssign:
8397 case BO_ShlAssign:
8398 case BO_ShrAssign:
8399 case BO_AndAssign:
8400 case BO_XorAssign:
8401 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008402 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8403 // constant expressions, but they can never be ICEs because an ICE cannot
8404 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008405 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008406
John McCalle3027922010-08-25 11:45:40 +00008407 case BO_Mul:
8408 case BO_Div:
8409 case BO_Rem:
8410 case BO_Add:
8411 case BO_Sub:
8412 case BO_Shl:
8413 case BO_Shr:
8414 case BO_LT:
8415 case BO_GT:
8416 case BO_LE:
8417 case BO_GE:
8418 case BO_EQ:
8419 case BO_NE:
8420 case BO_And:
8421 case BO_Xor:
8422 case BO_Or:
8423 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008424 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8425 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008426 if (Exp->getOpcode() == BO_Div ||
8427 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008428 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008429 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008430 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008431 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008432 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008433 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008434 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008435 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008436 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008437 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008438 }
8439 }
8440 }
John McCalle3027922010-08-25 11:45:40 +00008441 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008442 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008443 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8444 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008445 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8446 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008447 } else {
8448 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008449 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008450 }
8451 }
Richard Smith9e575da2012-12-28 13:25:52 +00008452 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008453 }
John McCalle3027922010-08-25 11:45:40 +00008454 case BO_LAnd:
8455 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008456 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8457 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008458 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008459 // Rare case where the RHS has a comma "side-effect"; we need
8460 // to actually check the condition to see whether the side
8461 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008462 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008463 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008464 return RHSResult;
8465 return NoDiag();
8466 }
8467
Richard Smith9e575da2012-12-28 13:25:52 +00008468 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008469 }
8470 }
8471 }
8472 case Expr::ImplicitCastExprClass:
8473 case Expr::CStyleCastExprClass:
8474 case Expr::CXXFunctionalCastExprClass:
8475 case Expr::CXXStaticCastExprClass:
8476 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008477 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008478 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008479 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008480 if (isa<ExplicitCastExpr>(E)) {
8481 if (const FloatingLiteral *FL
8482 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8483 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8484 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8485 APSInt IgnoredVal(DestWidth, !DestSigned);
8486 bool Ignored;
8487 // If the value does not fit in the destination type, the behavior is
8488 // undefined, so we are not required to treat it as a constant
8489 // expression.
8490 if (FL->getValue().convertToInteger(IgnoredVal,
8491 llvm::APFloat::rmTowardZero,
8492 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008493 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008494 return NoDiag();
8495 }
8496 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008497 switch (cast<CastExpr>(E)->getCastKind()) {
8498 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008499 case CK_AtomicToNonAtomic:
8500 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008501 case CK_NoOp:
8502 case CK_IntegralToBoolean:
8503 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008504 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008505 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008506 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008507 }
John McCall864e3962010-05-07 05:32:02 +00008508 }
John McCallc07a0c72011-02-17 10:25:35 +00008509 case Expr::BinaryConditionalOperatorClass: {
8510 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8511 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008512 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008513 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008514 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8515 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8516 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008517 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008518 return FalseResult;
8519 }
John McCall864e3962010-05-07 05:32:02 +00008520 case Expr::ConditionalOperatorClass: {
8521 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8522 // If the condition (ignoring parens) is a __builtin_constant_p call,
8523 // then only the true side is actually considered in an integer constant
8524 // expression, and it is fully evaluated. This is an important GNU
8525 // extension. See GCC PR38377 for discussion.
8526 if (const CallExpr *CallCE
8527 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008528 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8529 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008530 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008531 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008532 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008533
Richard Smithf57d8cb2011-12-09 22:58:01 +00008534 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8535 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008536
Richard Smith9e575da2012-12-28 13:25:52 +00008537 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008538 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008539 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008540 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008541 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008542 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008543 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008544 return NoDiag();
8545 // Rare case where the diagnostics depend on which side is evaluated
8546 // Note that if we get here, CondResult is 0, and at least one of
8547 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008548 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008549 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008550 return TrueResult;
8551 }
8552 case Expr::CXXDefaultArgExprClass:
8553 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008554 case Expr::CXXDefaultInitExprClass:
8555 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008556 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008557 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008558 }
8559 }
8560
David Blaikiee4d798f2012-01-20 21:50:17 +00008561 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008562}
8563
Richard Smithf57d8cb2011-12-09 22:58:01 +00008564/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008565static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008566 const Expr *E,
8567 llvm::APSInt *Value,
8568 SourceLocation *Loc) {
8569 if (!E->getType()->isIntegralOrEnumerationType()) {
8570 if (Loc) *Loc = E->getExprLoc();
8571 return false;
8572 }
8573
Richard Smith66e05fe2012-01-18 05:21:49 +00008574 APValue Result;
8575 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008576 return false;
8577
Richard Smith66e05fe2012-01-18 05:21:49 +00008578 assert(Result.isInt() && "pointer cast to int is not an ICE");
8579 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008580 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008581}
8582
Craig Toppera31a8822013-08-22 07:09:37 +00008583bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8584 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008585 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008586 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8587
Richard Smith9e575da2012-12-28 13:25:52 +00008588 ICEDiag D = CheckICE(this, Ctx);
8589 if (D.Kind != IK_ICE) {
8590 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008591 return false;
8592 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008593 return true;
8594}
8595
Craig Toppera31a8822013-08-22 07:09:37 +00008596bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008597 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008598 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008599 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8600
8601 if (!isIntegerConstantExpr(Ctx, Loc))
8602 return false;
8603 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008604 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008605 return true;
8606}
Richard Smith66e05fe2012-01-18 05:21:49 +00008607
Craig Toppera31a8822013-08-22 07:09:37 +00008608bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008609 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008610}
8611
Craig Toppera31a8822013-08-22 07:09:37 +00008612bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008613 SourceLocation *Loc) const {
8614 // We support this checking in C++98 mode in order to diagnose compatibility
8615 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008616 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008617
Richard Smith98a0a492012-02-14 21:38:30 +00008618 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008619 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008620 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008621 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008622 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008623
8624 APValue Scratch;
8625 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8626
8627 if (!Diags.empty()) {
8628 IsConstExpr = false;
8629 if (Loc) *Loc = Diags[0].first;
8630 } else if (!IsConstExpr) {
8631 // FIXME: This shouldn't happen.
8632 if (Loc) *Loc = getExprLoc();
8633 }
8634
8635 return IsConstExpr;
8636}
Richard Smith253c2a32012-01-27 01:14:48 +00008637
8638bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008639 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008640 PartialDiagnosticAt> &Diags) {
8641 // FIXME: It would be useful to check constexpr function templates, but at the
8642 // moment the constant expression evaluator cannot cope with the non-rigorous
8643 // ASTs which we build for dependent expressions.
8644 if (FD->isDependentContext())
8645 return true;
8646
8647 Expr::EvalStatus Status;
8648 Status.Diag = &Diags;
8649
Richard Smith6d4c6582013-11-05 22:18:15 +00008650 EvalInfo Info(FD->getASTContext(), Status,
8651 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008652
8653 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8654 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8655
Richard Smith7525ff62013-05-09 07:14:00 +00008656 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008657 // is a temporary being used as the 'this' pointer.
8658 LValue This;
8659 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008660 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008661
Richard Smith253c2a32012-01-27 01:14:48 +00008662 ArrayRef<const Expr*> Args;
8663
8664 SourceLocation Loc = FD->getLocation();
8665
Richard Smith2e312c82012-03-03 22:46:17 +00008666 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008667 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8668 // Evaluate the call as a constant initializer, to allow the construction
8669 // of objects of non-literal types.
8670 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008671 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008672 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008673 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8674 Args, FD->getBody(), Info, Scratch);
8675
8676 return Diags.empty();
8677}