blob: 835938ab57907b05baac869c96ec8b998e6af434 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
204 if (IsOnePastTheEnd)
205 return true;
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208 return true;
209 return false;
210 }
211
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
214 if (Invalid)
215 return false;
216 return !isOnePastTheEnd();
217 }
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000227
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000240
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
246 }
Richard Smith96e0c102011-11-04 02:25:55 +0000247 }
Richard Smith66c96992012-02-18 22:04:06 +0000248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
250 PathEntry Entry;
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
253
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
259 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith96e0c102011-11-04 02:25:55 +0000270 return;
271 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
279 else if (N != 0) {
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 }
Richard Smith96e0c102011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smith254a73d2011-10-28 22:34:42 +0000286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
288 EvalInfo &Info;
289
290 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000292
Richard Smithf6f003a2011-12-16 19:06:07 +0000293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
295
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
298
Richard Smithb228a862012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smithd62306a2011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000305 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000308
Eli Friedman4830ec82012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
314 MapTy Temporaries;
315
Richard Smithf6f003a2011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000320
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
323 return I == Temporaries.end() ? 0 : &I->second;
324 }
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000326 };
327
Richard Smith852c9db2013-04-20 22:23:05 +0000328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
330 public:
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
333 if (Enable)
334 Frame.This = NewThis;
335 }
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
338 }
339 private:
340 CallStackFrame &Frame;
341 const LValue *OldThis;
342 };
343
Richard Smith92b1ce02011-12-12 09:28:41 +0000344 /// A partial diagnostic which we might know in advance that we are not going
345 /// to emit.
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
348
349 public:
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
351
352 template<typename T>
353 OptionalDiagnostic &operator<<(const T &v) {
354 if (Diag)
355 *Diag << v;
356 return *this;
357 }
Richard Smithfe800032012-01-31 04:08:20 +0000358
359 OptionalDiagnostic &operator<<(const APSInt &I) {
360 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000361 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000362 I.toString(Buffer);
363 *Diag << StringRef(Buffer.data(), Buffer.size());
364 }
365 return *this;
366 }
367
368 OptionalDiagnostic &operator<<(const APFloat &F) {
369 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
376 unsigned precision =
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000379 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000380 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000381 *Diag << StringRef(Buffer.data(), Buffer.size());
382 }
383 return *this;
384 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000385 };
386
Richard Smith08d6a2c2013-07-24 07:11:57 +0000387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
388 class Cleanup {
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
390
391 public:
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
394
395 bool isLifetimeExtended() const { return Value.getInt(); }
396 void endLifetime() {
397 *Value.getPointer() = APValue();
398 }
399 };
400
Richard Smithb228a862012-02-15 02:18:13 +0000401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
404 /// expression.
405 ///
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
409 ///
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000415 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000416 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000417
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
420
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
423
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
426
Richard Smithb228a862012-02-15 02:18:13 +0000427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
429
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
433 unsigned StepsLeft;
434
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000435 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000436 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 CallStackFrame BottomFrame;
438
Richard Smith08d6a2c2013-07-24 07:11:57 +0000439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
442
Richard Smithd62306a2011-11-10 06:34:14 +0000443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000445 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000446
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
450
Richard Smith357362d2011-12-13 06:39:58 +0000451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
454
Richard Smith6d4c6582013-11-05 22:18:15 +0000455 enum EvaluationMode {
456 /// Evaluate as a constant expression. Stop if we find that the expression
457 /// is not a constant expression.
458 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000459
Richard Smith6d4c6582013-11-05 22:18:15 +0000460 /// Evaluate as a potential constant expression. Keep going if we hit a
461 /// construct that we can't evaluate yet (because we don't yet know the
462 /// value of something) but stop if we hit something that could never be
463 /// a constant expression.
464 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000465
Richard Smith6d4c6582013-11-05 22:18:15 +0000466 /// Fold the expression to a constant. Stop if we hit a side-effect that
467 /// we can't model.
468 EM_ConstantFold,
469
470 /// Evaluate the expression looking for integer overflow and similar
471 /// issues. Don't worry about side-effects, and try to visit all
472 /// subexpressions.
473 EM_EvaluateForOverflow,
474
475 /// Evaluate in any way we know how. Don't worry about side-effects that
476 /// can't be modeled.
477 EM_IgnoreSideEffects
478 } EvalMode;
479
480 /// Are we checking whether the expression is a potential constant
481 /// expression?
482 bool checkingPotentialConstantExpression() const {
483 return EvalMode == EM_PotentialConstantExpression;
484 }
485
486 /// Are we checking an expression for overflow?
487 // FIXME: We should check for any kind of undefined or suspicious behavior
488 // in such constructs, not just overflow.
489 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
490
491 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000493 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000494 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000495 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000496 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
Richard Smith6d4c6582013-11-05 22:18:15 +0000497 HasActiveDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000498
Richard Smith7525ff62013-05-09 07:14:00 +0000499 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
500 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000501 EvaluatingDeclValue = &Value;
502 }
503
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000505
Richard Smith357362d2011-12-13 06:39:58 +0000506 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000507 // Don't perform any constexpr calls (other than the call we're checking)
508 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000509 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000510 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000511 if (NextCallIndex == 0) {
512 // NextCallIndex has wrapped around.
513 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
514 return false;
515 }
Richard Smith357362d2011-12-13 06:39:58 +0000516 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
517 return true;
518 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
519 << getLangOpts().ConstexprCallDepth;
520 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000521 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000522
Richard Smithb228a862012-02-15 02:18:13 +0000523 CallStackFrame *getCallFrame(unsigned CallIndex) {
524 assert(CallIndex && "no call index in getCallFrame");
525 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
526 // be null in this loop.
527 CallStackFrame *Frame = CurrentCall;
528 while (Frame->Index > CallIndex)
529 Frame = Frame->Caller;
530 return (Frame->Index == CallIndex) ? Frame : 0;
531 }
532
Richard Smitha3d3bd22013-05-08 02:12:03 +0000533 bool nextStep(const Stmt *S) {
534 if (!StepsLeft) {
535 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
536 return false;
537 }
538 --StepsLeft;
539 return true;
540 }
541
Richard Smith357362d2011-12-13 06:39:58 +0000542 private:
543 /// Add a diagnostic to the diagnostics list.
544 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
545 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
546 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
547 return EvalStatus.Diag->back().second;
548 }
549
Richard Smithf6f003a2011-12-16 19:06:07 +0000550 /// Add notes containing a call stack to the current point of evaluation.
551 void addCallStack(unsigned Limit);
552
Richard Smith357362d2011-12-13 06:39:58 +0000553 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000554 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000555 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
556 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000557 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000558 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000559 // If we have a prior diagnostic, it will be noting that the expression
560 // isn't a constant expression. This diagnostic is more important,
561 // unless we require this evaluation to produce a constant expression.
562 //
563 // FIXME: We might want to show both diagnostics to the user in
564 // EM_ConstantFold mode.
565 if (!EvalStatus.Diag->empty()) {
566 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000567 case EM_ConstantFold:
568 case EM_IgnoreSideEffects:
569 case EM_EvaluateForOverflow:
570 if (!EvalStatus.HasSideEffects)
571 break;
572 // We've had side-effects; we want the diagnostic from them, not
573 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000574 case EM_ConstantExpression:
575 case EM_PotentialConstantExpression:
Richard Smith6d4c6582013-11-05 22:18:15 +0000576 HasActiveDiagnostic = false;
577 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000578 }
579 }
580
Richard Smithf6f003a2011-12-16 19:06:07 +0000581 unsigned CallStackNotes = CallStackDepth - 1;
582 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
583 if (Limit)
584 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000585 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000586 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000587
Richard Smith357362d2011-12-13 06:39:58 +0000588 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000589 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000590 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
591 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000592 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000593 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000594 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000595 }
Richard Smith357362d2011-12-13 06:39:58 +0000596 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000597 return OptionalDiagnostic();
598 }
599
Richard Smithce1ec5e2012-03-15 04:53:45 +0000600 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
601 = diag::note_invalid_subexpr_in_const_expr,
602 unsigned ExtraNotes = 0) {
603 if (EvalStatus.Diag)
604 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
605 HasActiveDiagnostic = false;
606 return OptionalDiagnostic();
607 }
608
Richard Smith92b1ce02011-12-12 09:28:41 +0000609 /// Diagnose that the evaluation does not produce a C++11 core constant
610 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 ///
612 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
613 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000614 template<typename LocArg>
615 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000616 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000617 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000618 // Don't override a previous diagnostic. Don't bother collecting
619 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000620 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000621 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000622 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000623 }
Richard Smith357362d2011-12-13 06:39:58 +0000624 return Diag(Loc, DiagId, ExtraNotes);
625 }
626
627 /// Add a note to a prior diagnostic.
628 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
629 if (!HasActiveDiagnostic)
630 return OptionalDiagnostic();
631 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000632 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000633
634 /// Add a stack of notes to a prior diagnostic.
635 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
636 if (HasActiveDiagnostic) {
637 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
638 Diags.begin(), Diags.end());
639 }
640 }
Richard Smith253c2a32012-01-27 01:14:48 +0000641
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 /// Should we continue evaluation after encountering a side-effect that we
643 /// couldn't model?
644 bool keepEvaluatingAfterSideEffect() {
645 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000646 case EM_PotentialConstantExpression:
Richard Smith6d4c6582013-11-05 22:18:15 +0000647 case EM_EvaluateForOverflow:
648 case EM_IgnoreSideEffects:
649 return true;
650
Richard Smith6d4c6582013-11-05 22:18:15 +0000651 case EM_ConstantExpression:
652 case EM_ConstantFold:
653 return false;
654 }
655 }
656
657 /// Note that we have had a side-effect, and determine whether we should
658 /// keep evaluating.
659 bool noteSideEffect() {
660 EvalStatus.HasSideEffects = true;
661 return keepEvaluatingAfterSideEffect();
662 }
663
Richard Smith253c2a32012-01-27 01:14:48 +0000664 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000665 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000666 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000667 if (!StepsLeft)
668 return false;
669
670 switch (EvalMode) {
671 case EM_PotentialConstantExpression:
672 case EM_EvaluateForOverflow:
673 return true;
674
675 case EM_ConstantExpression:
676 case EM_ConstantFold:
677 case EM_IgnoreSideEffects:
678 return false;
679 }
Richard Smith253c2a32012-01-27 01:14:48 +0000680 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000681 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000682
683 /// Object used to treat all foldable expressions as constant expressions.
684 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000685 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000686 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000687 bool HadNoPriorDiags;
688 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000689
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 explicit FoldConstant(EvalInfo &Info, bool Enabled)
691 : Info(Info),
692 Enabled(Enabled),
693 HadNoPriorDiags(Info.EvalStatus.Diag &&
694 Info.EvalStatus.Diag->empty() &&
695 !Info.EvalStatus.HasSideEffects),
696 OldMode(Info.EvalMode) {
697 if (Enabled && Info.EvalMode == EvalInfo::EM_ConstantExpression)
698 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000699 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000700 void keepDiagnostics() { Enabled = false; }
701 ~FoldConstant() {
702 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000703 !Info.EvalStatus.HasSideEffects)
704 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000705 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000706 }
707 };
Richard Smith17100ba2012-02-16 02:46:34 +0000708
709 /// RAII object used to suppress diagnostics and side-effects from a
710 /// speculative evaluation.
711 class SpeculativeEvaluationRAII {
712 EvalInfo &Info;
713 Expr::EvalStatus Old;
714
715 public:
716 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000717 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000718 : Info(Info), Old(Info.EvalStatus) {
719 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 // If we're speculatively evaluating, we may have skipped over some
721 // evaluations and missed out a side effect.
722 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000723 }
724 ~SpeculativeEvaluationRAII() {
725 Info.EvalStatus = Old;
726 }
727 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000728
729 /// RAII object wrapping a full-expression or block scope, and handling
730 /// the ending of the lifetime of temporaries created within it.
731 template<bool IsFullExpression>
732 class ScopeRAII {
733 EvalInfo &Info;
734 unsigned OldStackSize;
735 public:
736 ScopeRAII(EvalInfo &Info)
737 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
738 ~ScopeRAII() {
739 // Body moved to a static method to encourage the compiler to inline away
740 // instances of this class.
741 cleanup(Info, OldStackSize);
742 }
743 private:
744 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
745 unsigned NewEnd = OldStackSize;
746 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
747 I != N; ++I) {
748 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
749 // Full-expression cleanup of a lifetime-extended temporary: nothing
750 // to do, just move this cleanup to the right place in the stack.
751 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
752 ++NewEnd;
753 } else {
754 // End the lifetime of the object.
755 Info.CleanupStack[I].endLifetime();
756 }
757 }
758 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
759 Info.CleanupStack.end());
760 }
761 };
762 typedef ScopeRAII<false> BlockScopeRAII;
763 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000764}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000765
Richard Smitha8105bc2012-01-06 16:39:00 +0000766bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
767 CheckSubobjectKind CSK) {
768 if (Invalid)
769 return false;
770 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000771 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000772 << CSK;
773 setInvalid();
774 return false;
775 }
776 return true;
777}
778
779void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
780 const Expr *E, uint64_t N) {
781 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000782 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000783 << static_cast<int>(N) << /*array*/ 0
784 << static_cast<unsigned>(MostDerivedArraySize);
785 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000786 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000787 << static_cast<int>(N) << /*non-array*/ 1;
788 setInvalid();
789}
790
Richard Smithf6f003a2011-12-16 19:06:07 +0000791CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
792 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000793 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000794 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000795 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000796 Info.CurrentCall = this;
797 ++Info.CallStackDepth;
798}
799
800CallStackFrame::~CallStackFrame() {
801 assert(Info.CurrentCall == this && "calls retired out of order");
802 --Info.CallStackDepth;
803 Info.CurrentCall = Caller;
804}
805
Richard Smith08d6a2c2013-07-24 07:11:57 +0000806APValue &CallStackFrame::createTemporary(const void *Key,
807 bool IsLifetimeExtended) {
808 APValue &Result = Temporaries[Key];
809 assert(Result.isUninit() && "temporary created multiple times");
810 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
811 return Result;
812}
813
Richard Smith84401042013-06-03 05:03:02 +0000814static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000815
816void EvalInfo::addCallStack(unsigned Limit) {
817 // Determine which calls to skip, if any.
818 unsigned ActiveCalls = CallStackDepth - 1;
819 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
820 if (Limit && Limit < ActiveCalls) {
821 SkipStart = Limit / 2 + Limit % 2;
822 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000823 }
824
Richard Smithf6f003a2011-12-16 19:06:07 +0000825 // Walk the call stack and add the diagnostics.
826 unsigned CallIdx = 0;
827 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
828 Frame = Frame->Caller, ++CallIdx) {
829 // Skip this call?
830 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
831 if (CallIdx == SkipStart) {
832 // Note that we're skipping calls.
833 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
834 << unsigned(ActiveCalls - Limit);
835 }
836 continue;
837 }
838
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000839 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000840 llvm::raw_svector_ostream Out(Buffer);
841 describeCall(Frame, Out);
842 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
843 }
844}
845
846namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000847 struct ComplexValue {
848 private:
849 bool IsInt;
850
851 public:
852 APSInt IntReal, IntImag;
853 APFloat FloatReal, FloatImag;
854
855 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
856
857 void makeComplexFloat() { IsInt = false; }
858 bool isComplexFloat() const { return !IsInt; }
859 APFloat &getComplexFloatReal() { return FloatReal; }
860 APFloat &getComplexFloatImag() { return FloatImag; }
861
862 void makeComplexInt() { IsInt = true; }
863 bool isComplexInt() const { return IsInt; }
864 APSInt &getComplexIntReal() { return IntReal; }
865 APSInt &getComplexIntImag() { return IntImag; }
866
Richard Smith2e312c82012-03-03 22:46:17 +0000867 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000868 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000869 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000870 else
Richard Smith2e312c82012-03-03 22:46:17 +0000871 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000872 }
Richard Smith2e312c82012-03-03 22:46:17 +0000873 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000874 assert(v.isComplexFloat() || v.isComplexInt());
875 if (v.isComplexFloat()) {
876 makeComplexFloat();
877 FloatReal = v.getComplexFloatReal();
878 FloatImag = v.getComplexFloatImag();
879 } else {
880 makeComplexInt();
881 IntReal = v.getComplexIntReal();
882 IntImag = v.getComplexIntImag();
883 }
884 }
John McCall93d91dc2010-05-07 17:22:02 +0000885 };
John McCall45d55e42010-05-07 21:00:08 +0000886
887 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000888 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000889 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000890 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000891 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000892
Richard Smithce40ad62011-11-12 22:28:03 +0000893 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000894 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000895 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000896 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000897 SubobjectDesignator &getLValueDesignator() { return Designator; }
898 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000899
Richard Smith2e312c82012-03-03 22:46:17 +0000900 void moveInto(APValue &V) const {
901 if (Designator.Invalid)
902 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
903 else
904 V = APValue(Base, Offset, Designator.Entries,
905 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000906 }
Richard Smith2e312c82012-03-03 22:46:17 +0000907 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000908 assert(V.isLValue());
909 Base = V.getLValueBase();
910 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000911 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000912 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000913 }
914
Richard Smithb228a862012-02-15 02:18:13 +0000915 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000916 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000917 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000918 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000919 Designator = SubobjectDesignator(getType(B));
920 }
921
922 // Check that this LValue is not based on a null pointer. If it is, produce
923 // a diagnostic and mark the designator as invalid.
924 bool checkNullPointer(EvalInfo &Info, const Expr *E,
925 CheckSubobjectKind CSK) {
926 if (Designator.Invalid)
927 return false;
928 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000929 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000930 << CSK;
931 Designator.setInvalid();
932 return false;
933 }
934 return true;
935 }
936
937 // Check this LValue refers to an object. If not, set the designator to be
938 // invalid and emit a diagnostic.
939 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000940 // Outside C++11, do not build a designator referring to a subobject of
941 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000942 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000943 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000944 return checkNullPointer(Info, E, CSK) &&
945 Designator.checkSubobject(Info, E, CSK);
946 }
947
948 void addDecl(EvalInfo &Info, const Expr *E,
949 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000950 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
951 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000952 }
953 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000954 if (checkSubobject(Info, E, CSK_ArrayToPointer))
955 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000956 }
Richard Smith66c96992012-02-18 22:04:06 +0000957 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000958 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
959 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000960 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000961 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000962 if (checkNullPointer(Info, E, CSK_ArrayIndex))
963 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000964 }
John McCall45d55e42010-05-07 21:00:08 +0000965 };
Richard Smith027bf112011-11-17 22:56:20 +0000966
967 struct MemberPtr {
968 MemberPtr() {}
969 explicit MemberPtr(const ValueDecl *Decl) :
970 DeclAndIsDerivedMember(Decl, false), Path() {}
971
972 /// The member or (direct or indirect) field referred to by this member
973 /// pointer, or 0 if this is a null member pointer.
974 const ValueDecl *getDecl() const {
975 return DeclAndIsDerivedMember.getPointer();
976 }
977 /// Is this actually a member of some type derived from the relevant class?
978 bool isDerivedMember() const {
979 return DeclAndIsDerivedMember.getInt();
980 }
981 /// Get the class which the declaration actually lives in.
982 const CXXRecordDecl *getContainingRecord() const {
983 return cast<CXXRecordDecl>(
984 DeclAndIsDerivedMember.getPointer()->getDeclContext());
985 }
986
Richard Smith2e312c82012-03-03 22:46:17 +0000987 void moveInto(APValue &V) const {
988 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000989 }
Richard Smith2e312c82012-03-03 22:46:17 +0000990 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000991 assert(V.isMemberPointer());
992 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
993 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
994 Path.clear();
995 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
996 Path.insert(Path.end(), P.begin(), P.end());
997 }
998
999 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1000 /// whether the member is a member of some class derived from the class type
1001 /// of the member pointer.
1002 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1003 /// Path - The path of base/derived classes from the member declaration's
1004 /// class (exclusive) to the class type of the member pointer (inclusive).
1005 SmallVector<const CXXRecordDecl*, 4> Path;
1006
1007 /// Perform a cast towards the class of the Decl (either up or down the
1008 /// hierarchy).
1009 bool castBack(const CXXRecordDecl *Class) {
1010 assert(!Path.empty());
1011 const CXXRecordDecl *Expected;
1012 if (Path.size() >= 2)
1013 Expected = Path[Path.size() - 2];
1014 else
1015 Expected = getContainingRecord();
1016 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1017 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1018 // if B does not contain the original member and is not a base or
1019 // derived class of the class containing the original member, the result
1020 // of the cast is undefined.
1021 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1022 // (D::*). We consider that to be a language defect.
1023 return false;
1024 }
1025 Path.pop_back();
1026 return true;
1027 }
1028 /// Perform a base-to-derived member pointer cast.
1029 bool castToDerived(const CXXRecordDecl *Derived) {
1030 if (!getDecl())
1031 return true;
1032 if (!isDerivedMember()) {
1033 Path.push_back(Derived);
1034 return true;
1035 }
1036 if (!castBack(Derived))
1037 return false;
1038 if (Path.empty())
1039 DeclAndIsDerivedMember.setInt(false);
1040 return true;
1041 }
1042 /// Perform a derived-to-base member pointer cast.
1043 bool castToBase(const CXXRecordDecl *Base) {
1044 if (!getDecl())
1045 return true;
1046 if (Path.empty())
1047 DeclAndIsDerivedMember.setInt(true);
1048 if (isDerivedMember()) {
1049 Path.push_back(Base);
1050 return true;
1051 }
1052 return castBack(Base);
1053 }
1054 };
Richard Smith357362d2011-12-13 06:39:58 +00001055
Richard Smith7bb00672012-02-01 01:42:44 +00001056 /// Compare two member pointers, which are assumed to be of the same type.
1057 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1058 if (!LHS.getDecl() || !RHS.getDecl())
1059 return !LHS.getDecl() && !RHS.getDecl();
1060 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1061 return false;
1062 return LHS.Path == RHS.Path;
1063 }
John McCall93d91dc2010-05-07 17:22:02 +00001064}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001065
Richard Smith2e312c82012-03-03 22:46:17 +00001066static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001067static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1068 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001069 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001070static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1071static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001072static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1073 EvalInfo &Info);
1074static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001075static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001076static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001077 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001078static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001079static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001080static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001081
1082//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001083// Misc utilities
1084//===----------------------------------------------------------------------===//
1085
Richard Smith84401042013-06-03 05:03:02 +00001086/// Produce a string describing the given constexpr call.
1087static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1088 unsigned ArgIndex = 0;
1089 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1090 !isa<CXXConstructorDecl>(Frame->Callee) &&
1091 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1092
1093 if (!IsMemberCall)
1094 Out << *Frame->Callee << '(';
1095
1096 if (Frame->This && IsMemberCall) {
1097 APValue Val;
1098 Frame->This->moveInto(Val);
1099 Val.printPretty(Out, Frame->Info.Ctx,
1100 Frame->This->Designator.MostDerivedType);
1101 // FIXME: Add parens around Val if needed.
1102 Out << "->" << *Frame->Callee << '(';
1103 IsMemberCall = false;
1104 }
1105
1106 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1107 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1108 if (ArgIndex > (unsigned)IsMemberCall)
1109 Out << ", ";
1110
1111 const ParmVarDecl *Param = *I;
1112 const APValue &Arg = Frame->Arguments[ArgIndex];
1113 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1114
1115 if (ArgIndex == 0 && IsMemberCall)
1116 Out << "->" << *Frame->Callee << '(';
1117 }
1118
1119 Out << ')';
1120}
1121
Richard Smithd9f663b2013-04-22 15:31:51 +00001122/// Evaluate an expression to see if it had side-effects, and discard its
1123/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001124/// \return \c true if the caller should keep evaluating.
1125static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001126 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001127 if (!Evaluate(Scratch, Info, E))
1128 // We don't need the value, but we might have skipped a side effect here.
1129 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001130 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001131}
1132
Richard Smith861b5b52013-05-07 23:34:45 +00001133/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1134/// return its existing value.
1135static int64_t getExtValue(const APSInt &Value) {
1136 return Value.isSigned() ? Value.getSExtValue()
1137 : static_cast<int64_t>(Value.getZExtValue());
1138}
1139
Richard Smithd62306a2011-11-10 06:34:14 +00001140/// Should this call expression be treated as a string literal?
1141static bool IsStringLiteralCall(const CallExpr *E) {
1142 unsigned Builtin = E->isBuiltinCall();
1143 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1144 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1145}
1146
Richard Smithce40ad62011-11-12 22:28:03 +00001147static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001148 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1149 // constant expression of pointer type that evaluates to...
1150
1151 // ... a null pointer value, or a prvalue core constant expression of type
1152 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001153 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001154
Richard Smithce40ad62011-11-12 22:28:03 +00001155 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1156 // ... the address of an object with static storage duration,
1157 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1158 return VD->hasGlobalStorage();
1159 // ... the address of a function,
1160 return isa<FunctionDecl>(D);
1161 }
1162
1163 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001164 switch (E->getStmtClass()) {
1165 default:
1166 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001167 case Expr::CompoundLiteralExprClass: {
1168 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1169 return CLE->isFileScope() && CLE->isLValue();
1170 }
Richard Smithe6c01442013-06-05 00:46:14 +00001171 case Expr::MaterializeTemporaryExprClass:
1172 // A materialized temporary might have been lifetime-extended to static
1173 // storage duration.
1174 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001175 // A string literal has static storage duration.
1176 case Expr::StringLiteralClass:
1177 case Expr::PredefinedExprClass:
1178 case Expr::ObjCStringLiteralClass:
1179 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001180 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001181 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001182 return true;
1183 case Expr::CallExprClass:
1184 return IsStringLiteralCall(cast<CallExpr>(E));
1185 // For GCC compatibility, &&label has static storage duration.
1186 case Expr::AddrLabelExprClass:
1187 return true;
1188 // A Block literal expression may be used as the initialization value for
1189 // Block variables at global or local static scope.
1190 case Expr::BlockExprClass:
1191 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001192 case Expr::ImplicitValueInitExprClass:
1193 // FIXME:
1194 // We can never form an lvalue with an implicit value initialization as its
1195 // base through expression evaluation, so these only appear in one case: the
1196 // implicit variable declaration we invent when checking whether a constexpr
1197 // constructor can produce a constant expression. We must assume that such
1198 // an expression might be a global lvalue.
1199 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001200 }
John McCall95007602010-05-10 23:27:23 +00001201}
1202
Richard Smithb228a862012-02-15 02:18:13 +00001203static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1204 assert(Base && "no location for a null lvalue");
1205 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1206 if (VD)
1207 Info.Note(VD->getLocation(), diag::note_declared_at);
1208 else
Ted Kremenek28831752012-08-23 20:46:57 +00001209 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001210 diag::note_constexpr_temporary_here);
1211}
1212
Richard Smith80815602011-11-07 05:07:52 +00001213/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001214/// value for an address or reference constant expression. Return true if we
1215/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001216static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1217 QualType Type, const LValue &LVal) {
1218 bool IsReferenceType = Type->isReferenceType();
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220 APValue::LValueBase Base = LVal.getLValueBase();
1221 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1222
Richard Smith0dea49e2012-02-18 04:58:18 +00001223 // Check that the object is a global. Note that the fake 'this' object we
1224 // manufacture when checking potential constant expressions is conservatively
1225 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001226 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001227 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001228 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001229 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1230 << IsReferenceType << !Designator.Entries.empty()
1231 << !!VD << VD;
1232 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001233 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001234 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001235 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001236 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001237 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001238 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001239 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001240 LVal.getLValueCallIndex() == 0) &&
1241 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001242
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001243 // Check if this is a thread-local variable.
1244 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1245 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001246 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001247 return false;
1248 }
1249 }
1250
Richard Smitha8105bc2012-01-06 16:39:00 +00001251 // Allow address constant expressions to be past-the-end pointers. This is
1252 // an extension: the standard requires them to point to an object.
1253 if (!IsReferenceType)
1254 return true;
1255
1256 // A reference constant expression must refer to an object.
1257 if (!Base) {
1258 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001259 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001260 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001261 }
1262
Richard Smith357362d2011-12-13 06:39:58 +00001263 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001265 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001266 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001267 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001268 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001269 }
1270
Richard Smith80815602011-11-07 05:07:52 +00001271 return true;
1272}
1273
Richard Smithfddd3842011-12-30 21:15:51 +00001274/// Check that this core constant expression is of literal type, and if not,
1275/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001276static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1277 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001278 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001279 return true;
1280
Richard Smith7525ff62013-05-09 07:14:00 +00001281 // C++1y: A constant initializer for an object o [...] may also invoke
1282 // constexpr constructors for o and its subobjects even if those objects
1283 // are of non-literal class types.
1284 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001285 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001286 return true;
1287
Richard Smithfddd3842011-12-30 21:15:51 +00001288 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001289 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001290 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001291 << E->getType();
1292 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001293 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001294 return false;
1295}
1296
Richard Smith0b0a0b62011-10-29 20:57:55 +00001297/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001298/// constant expression. If not, report an appropriate diagnostic. Does not
1299/// check that the expression is of literal type.
1300static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1301 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001302 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001303 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1304 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001305 return false;
1306 }
1307
Richard Smithb228a862012-02-15 02:18:13 +00001308 // Core issue 1454: For a literal constant expression of array or class type,
1309 // each subobject of its value shall have been initialized by a constant
1310 // expression.
1311 if (Value.isArray()) {
1312 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1313 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1314 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1315 Value.getArrayInitializedElt(I)))
1316 return false;
1317 }
1318 if (!Value.hasArrayFiller())
1319 return true;
1320 return CheckConstantExpression(Info, DiagLoc, EltTy,
1321 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001322 }
Richard Smithb228a862012-02-15 02:18:13 +00001323 if (Value.isUnion() && Value.getUnionField()) {
1324 return CheckConstantExpression(Info, DiagLoc,
1325 Value.getUnionField()->getType(),
1326 Value.getUnionValue());
1327 }
1328 if (Value.isStruct()) {
1329 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1330 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1331 unsigned BaseIndex = 0;
1332 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1333 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1334 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1335 Value.getStructBase(BaseIndex)))
1336 return false;
1337 }
1338 }
1339 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1340 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001341 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1342 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001343 return false;
1344 }
1345 }
1346
1347 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001348 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001349 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001350 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1351 }
1352
1353 // Everything else is fine.
1354 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001355}
1356
Richard Smith83c68212011-10-31 05:11:32 +00001357const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001358 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001359}
1360
1361static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001362 if (Value.CallIndex)
1363 return false;
1364 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1365 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001366}
1367
Richard Smithcecf1842011-11-01 21:06:14 +00001368static bool IsWeakLValue(const LValue &Value) {
1369 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001370 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001371}
1372
Richard Smith2e312c82012-03-03 22:46:17 +00001373static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001374 // A null base expression indicates a null pointer. These are always
1375 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001376 if (!Value.getLValueBase()) {
1377 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001378 return true;
1379 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001380
Richard Smith027bf112011-11-17 22:56:20 +00001381 // We have a non-null base. These are generally known to be true, but if it's
1382 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001383 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001384 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001385 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001386}
1387
Richard Smith2e312c82012-03-03 22:46:17 +00001388static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001389 switch (Val.getKind()) {
1390 case APValue::Uninitialized:
1391 return false;
1392 case APValue::Int:
1393 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001394 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001395 case APValue::Float:
1396 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001397 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001398 case APValue::ComplexInt:
1399 Result = Val.getComplexIntReal().getBoolValue() ||
1400 Val.getComplexIntImag().getBoolValue();
1401 return true;
1402 case APValue::ComplexFloat:
1403 Result = !Val.getComplexFloatReal().isZero() ||
1404 !Val.getComplexFloatImag().isZero();
1405 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001406 case APValue::LValue:
1407 return EvalPointerValueAsBool(Val, Result);
1408 case APValue::MemberPointer:
1409 Result = Val.getMemberPointerDecl();
1410 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001411 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001412 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001413 case APValue::Struct:
1414 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001415 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001416 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001417 }
1418
Richard Smith11562c52011-10-28 17:51:58 +00001419 llvm_unreachable("unknown APValue kind");
1420}
1421
1422static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1423 EvalInfo &Info) {
1424 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001425 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001426 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001427 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001428 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001429}
1430
Richard Smith357362d2011-12-13 06:39:58 +00001431template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001432static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001433 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001434 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001435 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001436}
1437
1438static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1439 QualType SrcType, const APFloat &Value,
1440 QualType DestType, APSInt &Result) {
1441 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001442 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001443 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001444
Richard Smith357362d2011-12-13 06:39:58 +00001445 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001446 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001447 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1448 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001449 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001450 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001451}
1452
Richard Smith357362d2011-12-13 06:39:58 +00001453static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1454 QualType SrcType, QualType DestType,
1455 APFloat &Result) {
1456 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001457 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001458 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1459 APFloat::rmNearestTiesToEven, &ignored)
1460 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001461 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001462 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001463}
1464
Richard Smith911e1422012-01-30 22:27:01 +00001465static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1466 QualType DestType, QualType SrcType,
1467 APSInt &Value) {
1468 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001469 APSInt Result = Value;
1470 // Figure out if this is a truncate, extend or noop cast.
1471 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001472 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001473 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001474 return Result;
1475}
1476
Richard Smith357362d2011-12-13 06:39:58 +00001477static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1478 QualType SrcType, const APSInt &Value,
1479 QualType DestType, APFloat &Result) {
1480 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1481 if (Result.convertFromAPInt(Value, Value.isSigned(),
1482 APFloat::rmNearestTiesToEven)
1483 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001484 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001485 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001486}
1487
Richard Smith49ca8aa2013-08-06 07:09:20 +00001488static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1489 APValue &Value, const FieldDecl *FD) {
1490 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1491
1492 if (!Value.isInt()) {
1493 // Trying to store a pointer-cast-to-integer into a bitfield.
1494 // FIXME: In this case, we should provide the diagnostic for casting
1495 // a pointer to an integer.
1496 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1497 Info.Diag(E);
1498 return false;
1499 }
1500
1501 APSInt &Int = Value.getInt();
1502 unsigned OldBitWidth = Int.getBitWidth();
1503 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1504 if (NewBitWidth < OldBitWidth)
1505 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1506 return true;
1507}
1508
Eli Friedman803acb32011-12-22 03:51:45 +00001509static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1510 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001511 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001512 if (!Evaluate(SVal, Info, E))
1513 return false;
1514 if (SVal.isInt()) {
1515 Res = SVal.getInt();
1516 return true;
1517 }
1518 if (SVal.isFloat()) {
1519 Res = SVal.getFloat().bitcastToAPInt();
1520 return true;
1521 }
1522 if (SVal.isVector()) {
1523 QualType VecTy = E->getType();
1524 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1525 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1526 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1527 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1528 Res = llvm::APInt::getNullValue(VecSize);
1529 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1530 APValue &Elt = SVal.getVectorElt(i);
1531 llvm::APInt EltAsInt;
1532 if (Elt.isInt()) {
1533 EltAsInt = Elt.getInt();
1534 } else if (Elt.isFloat()) {
1535 EltAsInt = Elt.getFloat().bitcastToAPInt();
1536 } else {
1537 // Don't try to handle vectors of anything other than int or float
1538 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001539 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001540 return false;
1541 }
1542 unsigned BaseEltSize = EltAsInt.getBitWidth();
1543 if (BigEndian)
1544 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1545 else
1546 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1547 }
1548 return true;
1549 }
1550 // Give up if the input isn't an int, float, or vector. For example, we
1551 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001552 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001553 return false;
1554}
1555
Richard Smith43e77732013-05-07 04:50:00 +00001556/// Perform the given integer operation, which is known to need at most BitWidth
1557/// bits, and check for overflow in the original type (if that type was not an
1558/// unsigned type).
1559template<typename Operation>
1560static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1561 const APSInt &LHS, const APSInt &RHS,
1562 unsigned BitWidth, Operation Op) {
1563 if (LHS.isUnsigned())
1564 return Op(LHS, RHS);
1565
1566 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1567 APSInt Result = Value.trunc(LHS.getBitWidth());
1568 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001569 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001570 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1571 diag::warn_integer_constant_overflow)
1572 << Result.toString(10) << E->getType();
1573 else
1574 HandleOverflow(Info, E, Value, E->getType());
1575 }
1576 return Result;
1577}
1578
1579/// Perform the given binary integer operation.
1580static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1581 BinaryOperatorKind Opcode, APSInt RHS,
1582 APSInt &Result) {
1583 switch (Opcode) {
1584 default:
1585 Info.Diag(E);
1586 return false;
1587 case BO_Mul:
1588 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1589 std::multiplies<APSInt>());
1590 return true;
1591 case BO_Add:
1592 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1593 std::plus<APSInt>());
1594 return true;
1595 case BO_Sub:
1596 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1597 std::minus<APSInt>());
1598 return true;
1599 case BO_And: Result = LHS & RHS; return true;
1600 case BO_Xor: Result = LHS ^ RHS; return true;
1601 case BO_Or: Result = LHS | RHS; return true;
1602 case BO_Div:
1603 case BO_Rem:
1604 if (RHS == 0) {
1605 Info.Diag(E, diag::note_expr_divide_by_zero);
1606 return false;
1607 }
1608 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1609 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1610 LHS.isSigned() && LHS.isMinSignedValue())
1611 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1612 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1613 return true;
1614 case BO_Shl: {
1615 if (Info.getLangOpts().OpenCL)
1616 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1617 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1618 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1619 RHS.isUnsigned());
1620 else if (RHS.isSigned() && RHS.isNegative()) {
1621 // During constant-folding, a negative shift is an opposite shift. Such
1622 // a shift is not a constant expression.
1623 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1624 RHS = -RHS;
1625 goto shift_right;
1626 }
1627 shift_left:
1628 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1629 // the shifted type.
1630 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1631 if (SA != RHS) {
1632 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1633 << RHS << E->getType() << LHS.getBitWidth();
1634 } else if (LHS.isSigned()) {
1635 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1636 // operand, and must not overflow the corresponding unsigned type.
1637 if (LHS.isNegative())
1638 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1639 else if (LHS.countLeadingZeros() < SA)
1640 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1641 }
1642 Result = LHS << SA;
1643 return true;
1644 }
1645 case BO_Shr: {
1646 if (Info.getLangOpts().OpenCL)
1647 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1648 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1649 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1650 RHS.isUnsigned());
1651 else if (RHS.isSigned() && RHS.isNegative()) {
1652 // During constant-folding, a negative shift is an opposite shift. Such a
1653 // shift is not a constant expression.
1654 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1655 RHS = -RHS;
1656 goto shift_left;
1657 }
1658 shift_right:
1659 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1660 // shifted type.
1661 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1662 if (SA != RHS)
1663 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1664 << RHS << E->getType() << LHS.getBitWidth();
1665 Result = LHS >> SA;
1666 return true;
1667 }
1668
1669 case BO_LT: Result = LHS < RHS; return true;
1670 case BO_GT: Result = LHS > RHS; return true;
1671 case BO_LE: Result = LHS <= RHS; return true;
1672 case BO_GE: Result = LHS >= RHS; return true;
1673 case BO_EQ: Result = LHS == RHS; return true;
1674 case BO_NE: Result = LHS != RHS; return true;
1675 }
1676}
1677
Richard Smith861b5b52013-05-07 23:34:45 +00001678/// Perform the given binary floating-point operation, in-place, on LHS.
1679static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1680 APFloat &LHS, BinaryOperatorKind Opcode,
1681 const APFloat &RHS) {
1682 switch (Opcode) {
1683 default:
1684 Info.Diag(E);
1685 return false;
1686 case BO_Mul:
1687 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1688 break;
1689 case BO_Add:
1690 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1691 break;
1692 case BO_Sub:
1693 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1694 break;
1695 case BO_Div:
1696 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1697 break;
1698 }
1699
1700 if (LHS.isInfinity() || LHS.isNaN())
1701 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1702 return true;
1703}
1704
Richard Smitha8105bc2012-01-06 16:39:00 +00001705/// Cast an lvalue referring to a base subobject to a derived class, by
1706/// truncating the lvalue's path to the given length.
1707static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1708 const RecordDecl *TruncatedType,
1709 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001710 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001711
1712 // Check we actually point to a derived class object.
1713 if (TruncatedElements == D.Entries.size())
1714 return true;
1715 assert(TruncatedElements >= D.MostDerivedPathLength &&
1716 "not casting to a derived class");
1717 if (!Result.checkSubobject(Info, E, CSK_Derived))
1718 return false;
1719
1720 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001721 const RecordDecl *RD = TruncatedType;
1722 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001723 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001724 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1725 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001726 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001727 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001728 else
Richard Smithd62306a2011-11-10 06:34:14 +00001729 Result.Offset -= Layout.getBaseClassOffset(Base);
1730 RD = Base;
1731 }
Richard Smith027bf112011-11-17 22:56:20 +00001732 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001733 return true;
1734}
1735
John McCalld7bca762012-05-01 00:38:49 +00001736static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001737 const CXXRecordDecl *Derived,
1738 const CXXRecordDecl *Base,
1739 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001740 if (!RL) {
1741 if (Derived->isInvalidDecl()) return false;
1742 RL = &Info.Ctx.getASTRecordLayout(Derived);
1743 }
1744
Richard Smithd62306a2011-11-10 06:34:14 +00001745 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001746 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001747 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001748}
1749
Richard Smitha8105bc2012-01-06 16:39:00 +00001750static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001751 const CXXRecordDecl *DerivedDecl,
1752 const CXXBaseSpecifier *Base) {
1753 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1754
John McCalld7bca762012-05-01 00:38:49 +00001755 if (!Base->isVirtual())
1756 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001757
Richard Smitha8105bc2012-01-06 16:39:00 +00001758 SubobjectDesignator &D = Obj.Designator;
1759 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001760 return false;
1761
Richard Smitha8105bc2012-01-06 16:39:00 +00001762 // Extract most-derived object and corresponding type.
1763 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1764 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1765 return false;
1766
1767 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001768 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001769 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1770 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001771 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001772 return true;
1773}
1774
Richard Smith84401042013-06-03 05:03:02 +00001775static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1776 QualType Type, LValue &Result) {
1777 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1778 PathE = E->path_end();
1779 PathI != PathE; ++PathI) {
1780 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1781 *PathI))
1782 return false;
1783 Type = (*PathI)->getType();
1784 }
1785 return true;
1786}
1787
Richard Smithd62306a2011-11-10 06:34:14 +00001788/// Update LVal to refer to the given field, which must be a member of the type
1789/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001790static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001791 const FieldDecl *FD,
1792 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001793 if (!RL) {
1794 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001795 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001796 }
Richard Smithd62306a2011-11-10 06:34:14 +00001797
1798 unsigned I = FD->getFieldIndex();
1799 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001800 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001801 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001802}
1803
Richard Smith1b78b3d2012-01-25 22:15:11 +00001804/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001805static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001806 LValue &LVal,
1807 const IndirectFieldDecl *IFD) {
1808 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1809 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001810 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1811 return false;
1812 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001813}
1814
Richard Smithd62306a2011-11-10 06:34:14 +00001815/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001816static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1817 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001818 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1819 // extension.
1820 if (Type->isVoidType() || Type->isFunctionType()) {
1821 Size = CharUnits::One();
1822 return true;
1823 }
1824
1825 if (!Type->isConstantSizeType()) {
1826 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001827 // FIXME: Better diagnostic.
1828 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001829 return false;
1830 }
1831
1832 Size = Info.Ctx.getTypeSizeInChars(Type);
1833 return true;
1834}
1835
1836/// Update a pointer value to model pointer arithmetic.
1837/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001838/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001839/// \param LVal - The pointer value to be updated.
1840/// \param EltTy - The pointee type represented by LVal.
1841/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001842static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1843 LValue &LVal, QualType EltTy,
1844 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001845 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001846 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001847 return false;
1848
1849 // Compute the new offset in the appropriate width.
1850 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001851 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001852 return true;
1853}
1854
Richard Smith66c96992012-02-18 22:04:06 +00001855/// Update an lvalue to refer to a component of a complex number.
1856/// \param Info - Information about the ongoing evaluation.
1857/// \param LVal - The lvalue to be updated.
1858/// \param EltTy - The complex number's component type.
1859/// \param Imag - False for the real component, true for the imaginary.
1860static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1861 LValue &LVal, QualType EltTy,
1862 bool Imag) {
1863 if (Imag) {
1864 CharUnits SizeOfComponent;
1865 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1866 return false;
1867 LVal.Offset += SizeOfComponent;
1868 }
1869 LVal.addComplex(Info, E, EltTy, Imag);
1870 return true;
1871}
1872
Richard Smith27908702011-10-24 17:54:18 +00001873/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001874///
1875/// \param Info Information about the ongoing evaluation.
1876/// \param E An expression to be used when printing diagnostics.
1877/// \param VD The variable whose initializer should be obtained.
1878/// \param Frame The frame in which the variable was created. Must be null
1879/// if this variable is not local to the evaluation.
1880/// \param Result Filled in with a pointer to the value of the variable.
1881static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1882 const VarDecl *VD, CallStackFrame *Frame,
1883 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001884 // If this is a parameter to an active constexpr function call, perform
1885 // argument substitution.
1886 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001887 // Assume arguments of a potential constant expression are unknown
1888 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001889 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001890 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001891 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001892 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001893 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001894 }
Richard Smith3229b742013-05-05 21:17:10 +00001895 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001896 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001897 }
Richard Smith27908702011-10-24 17:54:18 +00001898
Richard Smithd9f663b2013-04-22 15:31:51 +00001899 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001900 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001901 Result = Frame->getTemporary(VD);
1902 assert(Result && "missing value for local variable");
1903 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001904 }
1905
Richard Smithd0b4dd62011-12-19 06:19:21 +00001906 // Dig out the initializer, and use the declaration which it's attached to.
1907 const Expr *Init = VD->getAnyInitializer(VD);
1908 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001909 // If we're checking a potential constant expression, the variable could be
1910 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001911 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001912 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001913 return false;
1914 }
1915
Richard Smithd62306a2011-11-10 06:34:14 +00001916 // If we're currently evaluating the initializer of this declaration, use that
1917 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001918 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001919 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001920 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001921 }
1922
Richard Smithcecf1842011-11-01 21:06:14 +00001923 // Never evaluate the initializer of a weak variable. We can't be sure that
1924 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001925 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001926 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001927 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001928 }
Richard Smithcecf1842011-11-01 21:06:14 +00001929
Richard Smithd0b4dd62011-12-19 06:19:21 +00001930 // Check that we can fold the initializer. In C++, we will have already done
1931 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001932 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001933 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001934 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001935 Notes.size() + 1) << VD;
1936 Info.Note(VD->getLocation(), diag::note_declared_at);
1937 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001938 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001939 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001940 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001941 Notes.size() + 1) << VD;
1942 Info.Note(VD->getLocation(), diag::note_declared_at);
1943 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 }
Richard Smith27908702011-10-24 17:54:18 +00001945
Richard Smith3229b742013-05-05 21:17:10 +00001946 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001947 return true;
Richard Smith27908702011-10-24 17:54:18 +00001948}
1949
Richard Smith11562c52011-10-28 17:51:58 +00001950static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001951 Qualifiers Quals = T.getQualifiers();
1952 return Quals.hasConst() && !Quals.hasVolatile();
1953}
1954
Richard Smithe97cbd72011-11-11 04:05:33 +00001955/// Get the base index of the given base class within an APValue representing
1956/// the given derived class.
1957static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1958 const CXXRecordDecl *Base) {
1959 Base = Base->getCanonicalDecl();
1960 unsigned Index = 0;
1961 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1962 E = Derived->bases_end(); I != E; ++I, ++Index) {
1963 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1964 return Index;
1965 }
1966
1967 llvm_unreachable("base class missing from derived class's bases list");
1968}
1969
Richard Smith3da88fa2013-04-26 14:36:30 +00001970/// Extract the value of a character from a string literal.
1971static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1972 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001973 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 const StringLiteral *S = cast<StringLiteral>(Lit);
1975 const ConstantArrayType *CAT =
1976 Info.Ctx.getAsConstantArrayType(S->getType());
1977 assert(CAT && "string literal isn't an array");
1978 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001979 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001980
1981 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001982 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001983 if (Index < S->getLength())
1984 Value = S->getCodeUnit(Index);
1985 return Value;
1986}
1987
Richard Smith3da88fa2013-04-26 14:36:30 +00001988// Expand a string literal into an array of characters.
1989static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1990 APValue &Result) {
1991 const StringLiteral *S = cast<StringLiteral>(Lit);
1992 const ConstantArrayType *CAT =
1993 Info.Ctx.getAsConstantArrayType(S->getType());
1994 assert(CAT && "string literal isn't an array");
1995 QualType CharType = CAT->getElementType();
1996 assert(CharType->isIntegerType() && "unexpected character type");
1997
1998 unsigned Elts = CAT->getSize().getZExtValue();
1999 Result = APValue(APValue::UninitArray(),
2000 std::min(S->getLength(), Elts), Elts);
2001 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2002 CharType->isUnsignedIntegerType());
2003 if (Result.hasArrayFiller())
2004 Result.getArrayFiller() = APValue(Value);
2005 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2006 Value = S->getCodeUnit(I);
2007 Result.getArrayInitializedElt(I) = APValue(Value);
2008 }
2009}
2010
2011// Expand an array so that it has more than Index filled elements.
2012static void expandArray(APValue &Array, unsigned Index) {
2013 unsigned Size = Array.getArraySize();
2014 assert(Index < Size);
2015
2016 // Always at least double the number of elements for which we store a value.
2017 unsigned OldElts = Array.getArrayInitializedElts();
2018 unsigned NewElts = std::max(Index+1, OldElts * 2);
2019 NewElts = std::min(Size, std::max(NewElts, 8u));
2020
2021 // Copy the data across.
2022 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2023 for (unsigned I = 0; I != OldElts; ++I)
2024 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2025 for (unsigned I = OldElts; I != NewElts; ++I)
2026 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2027 if (NewValue.hasArrayFiller())
2028 NewValue.getArrayFiller() = Array.getArrayFiller();
2029 Array.swap(NewValue);
2030}
2031
Richard Smith861b5b52013-05-07 23:34:45 +00002032/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002033enum AccessKinds {
2034 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002035 AK_Assign,
2036 AK_Increment,
2037 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002038};
2039
Richard Smith3229b742013-05-05 21:17:10 +00002040/// A handle to a complete object (an object that is not a subobject of
2041/// another object).
2042struct CompleteObject {
2043 /// The value of the complete object.
2044 APValue *Value;
2045 /// The type of the complete object.
2046 QualType Type;
2047
2048 CompleteObject() : Value(0) {}
2049 CompleteObject(APValue *Value, QualType Type)
2050 : Value(Value), Type(Type) {
2051 assert(Value && "missing value for complete object");
2052 }
2053
David Blaikie7d170102013-05-15 07:37:26 +00002054 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002055};
2056
Richard Smith3da88fa2013-04-26 14:36:30 +00002057/// Find the designated sub-object of an rvalue.
2058template<typename SubobjectHandler>
2059typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002060findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002061 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002062 if (Sub.Invalid)
2063 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002064 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002065 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002066 if (Info.getLangOpts().CPlusPlus11)
2067 Info.Diag(E, diag::note_constexpr_access_past_end)
2068 << handler.AccessKind;
2069 else
2070 Info.Diag(E);
2071 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002072 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002073
Richard Smith3229b742013-05-05 21:17:10 +00002074 APValue *O = Obj.Value;
2075 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002076 const FieldDecl *LastField = 0;
2077
Richard Smithd62306a2011-11-10 06:34:14 +00002078 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002079 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2080 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002081 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002082 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2083 return handler.failed();
2084 }
2085
Richard Smith49ca8aa2013-08-06 07:09:20 +00002086 if (I == N) {
2087 if (!handler.found(*O, ObjType))
2088 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002089
Richard Smith49ca8aa2013-08-06 07:09:20 +00002090 // If we modified a bit-field, truncate it to the right width.
2091 if (handler.AccessKind != AK_Read &&
2092 LastField && LastField->isBitField() &&
2093 !truncateBitfieldValue(Info, E, *O, LastField))
2094 return false;
2095
2096 return true;
2097 }
2098
2099 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002100 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002101 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002102 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002103 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002104 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002105 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002106 // Note, it should not be possible to form a pointer with a valid
2107 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002108 if (Info.getLangOpts().CPlusPlus11)
2109 Info.Diag(E, diag::note_constexpr_access_past_end)
2110 << handler.AccessKind;
2111 else
2112 Info.Diag(E);
2113 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002114 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002115
2116 ObjType = CAT->getElementType();
2117
Richard Smith14a94132012-02-17 03:35:37 +00002118 // An array object is represented as either an Array APValue or as an
2119 // LValue which refers to a string literal.
2120 if (O->isLValue()) {
2121 assert(I == N - 1 && "extracting subobject of character?");
2122 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002123 if (handler.AccessKind != AK_Read)
2124 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2125 *O);
2126 else
2127 return handler.foundString(*O, ObjType, Index);
2128 }
2129
2130 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002131 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002132 else if (handler.AccessKind != AK_Read) {
2133 expandArray(*O, Index);
2134 O = &O->getArrayInitializedElt(Index);
2135 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002136 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002137 } else if (ObjType->isAnyComplexType()) {
2138 // Next subobject is a complex number.
2139 uint64_t Index = Sub.Entries[I].ArrayIndex;
2140 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002141 if (Info.getLangOpts().CPlusPlus11)
2142 Info.Diag(E, diag::note_constexpr_access_past_end)
2143 << handler.AccessKind;
2144 else
2145 Info.Diag(E);
2146 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002147 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002148
2149 bool WasConstQualified = ObjType.isConstQualified();
2150 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2151 if (WasConstQualified)
2152 ObjType.addConst();
2153
Richard Smith66c96992012-02-18 22:04:06 +00002154 assert(I == N - 1 && "extracting subobject of scalar?");
2155 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002156 return handler.found(Index ? O->getComplexIntImag()
2157 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002158 } else {
2159 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002160 return handler.found(Index ? O->getComplexFloatImag()
2161 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002162 }
Richard Smithd62306a2011-11-10 06:34:14 +00002163 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002164 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002165 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002166 << Field;
2167 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002168 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002169 }
2170
Richard Smithd62306a2011-11-10 06:34:14 +00002171 // Next subobject is a class, struct or union field.
2172 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2173 if (RD->isUnion()) {
2174 const FieldDecl *UnionField = O->getUnionField();
2175 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002176 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002177 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2178 << handler.AccessKind << Field << !UnionField << UnionField;
2179 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002180 }
Richard Smithd62306a2011-11-10 06:34:14 +00002181 O = &O->getUnionValue();
2182 } else
2183 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002184
2185 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002186 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002187 if (WasConstQualified && !Field->isMutable())
2188 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002189
2190 if (ObjType.isVolatileQualified()) {
2191 if (Info.getLangOpts().CPlusPlus) {
2192 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002193 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2194 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002195 Info.Note(Field->getLocation(), diag::note_declared_at);
2196 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002197 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002198 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002199 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002200 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002201
2202 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002203 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002204 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002205 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2206 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2207 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002208
2209 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002210 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002211 if (WasConstQualified)
2212 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002213 }
2214 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002215}
2216
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002217namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002218struct ExtractSubobjectHandler {
2219 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002220 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002221
2222 static const AccessKinds AccessKind = AK_Read;
2223
2224 typedef bool result_type;
2225 bool failed() { return false; }
2226 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002227 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002228 return true;
2229 }
2230 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002231 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002232 return true;
2233 }
2234 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002235 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002236 return true;
2237 }
2238 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002239 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002240 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2241 return true;
2242 }
2243};
Richard Smith3229b742013-05-05 21:17:10 +00002244} // end anonymous namespace
2245
Richard Smith3da88fa2013-04-26 14:36:30 +00002246const AccessKinds ExtractSubobjectHandler::AccessKind;
2247
2248/// Extract the designated sub-object of an rvalue.
2249static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002250 const CompleteObject &Obj,
2251 const SubobjectDesignator &Sub,
2252 APValue &Result) {
2253 ExtractSubobjectHandler Handler = { Info, Result };
2254 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002255}
2256
Richard Smith3229b742013-05-05 21:17:10 +00002257namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002258struct ModifySubobjectHandler {
2259 EvalInfo &Info;
2260 APValue &NewVal;
2261 const Expr *E;
2262
2263 typedef bool result_type;
2264 static const AccessKinds AccessKind = AK_Assign;
2265
2266 bool checkConst(QualType QT) {
2267 // Assigning to a const object has undefined behavior.
2268 if (QT.isConstQualified()) {
2269 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2270 return false;
2271 }
2272 return true;
2273 }
2274
2275 bool failed() { return false; }
2276 bool found(APValue &Subobj, QualType SubobjType) {
2277 if (!checkConst(SubobjType))
2278 return false;
2279 // We've been given ownership of NewVal, so just swap it in.
2280 Subobj.swap(NewVal);
2281 return true;
2282 }
2283 bool found(APSInt &Value, QualType SubobjType) {
2284 if (!checkConst(SubobjType))
2285 return false;
2286 if (!NewVal.isInt()) {
2287 // Maybe trying to write a cast pointer value into a complex?
2288 Info.Diag(E);
2289 return false;
2290 }
2291 Value = NewVal.getInt();
2292 return true;
2293 }
2294 bool found(APFloat &Value, QualType SubobjType) {
2295 if (!checkConst(SubobjType))
2296 return false;
2297 Value = NewVal.getFloat();
2298 return true;
2299 }
2300 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2301 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2302 }
2303};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002304} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002305
Richard Smith3229b742013-05-05 21:17:10 +00002306const AccessKinds ModifySubobjectHandler::AccessKind;
2307
Richard Smith3da88fa2013-04-26 14:36:30 +00002308/// Update the designated sub-object of an rvalue to the given value.
2309static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002310 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002311 const SubobjectDesignator &Sub,
2312 APValue &NewVal) {
2313 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002314 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002315}
2316
Richard Smith84f6dcf2012-02-02 01:16:57 +00002317/// Find the position where two subobject designators diverge, or equivalently
2318/// the length of the common initial subsequence.
2319static unsigned FindDesignatorMismatch(QualType ObjType,
2320 const SubobjectDesignator &A,
2321 const SubobjectDesignator &B,
2322 bool &WasArrayIndex) {
2323 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2324 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002325 if (!ObjType.isNull() &&
2326 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002327 // Next subobject is an array element.
2328 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2329 WasArrayIndex = true;
2330 return I;
2331 }
Richard Smith66c96992012-02-18 22:04:06 +00002332 if (ObjType->isAnyComplexType())
2333 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2334 else
2335 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002336 } else {
2337 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2338 WasArrayIndex = false;
2339 return I;
2340 }
2341 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2342 // Next subobject is a field.
2343 ObjType = FD->getType();
2344 else
2345 // Next subobject is a base class.
2346 ObjType = QualType();
2347 }
2348 }
2349 WasArrayIndex = false;
2350 return I;
2351}
2352
2353/// Determine whether the given subobject designators refer to elements of the
2354/// same array object.
2355static bool AreElementsOfSameArray(QualType ObjType,
2356 const SubobjectDesignator &A,
2357 const SubobjectDesignator &B) {
2358 if (A.Entries.size() != B.Entries.size())
2359 return false;
2360
2361 bool IsArray = A.MostDerivedArraySize != 0;
2362 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2363 // A is a subobject of the array element.
2364 return false;
2365
2366 // If A (and B) designates an array element, the last entry will be the array
2367 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2368 // of length 1' case, and the entire path must match.
2369 bool WasArrayIndex;
2370 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2371 return CommonLength >= A.Entries.size() - IsArray;
2372}
2373
Richard Smith3229b742013-05-05 21:17:10 +00002374/// Find the complete object to which an LValue refers.
2375CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2376 const LValue &LVal, QualType LValType) {
2377 if (!LVal.Base) {
2378 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2379 return CompleteObject();
2380 }
2381
2382 CallStackFrame *Frame = 0;
2383 if (LVal.CallIndex) {
2384 Frame = Info.getCallFrame(LVal.CallIndex);
2385 if (!Frame) {
2386 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2387 << AK << LVal.Base.is<const ValueDecl*>();
2388 NoteLValueLocation(Info, LVal.Base);
2389 return CompleteObject();
2390 }
Richard Smith3229b742013-05-05 21:17:10 +00002391 }
2392
2393 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2394 // is not a constant expression (even if the object is non-volatile). We also
2395 // apply this rule to C++98, in order to conform to the expected 'volatile'
2396 // semantics.
2397 if (LValType.isVolatileQualified()) {
2398 if (Info.getLangOpts().CPlusPlus)
2399 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2400 << AK << LValType;
2401 else
2402 Info.Diag(E);
2403 return CompleteObject();
2404 }
2405
2406 // Compute value storage location and type of base object.
2407 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002408 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002409
2410 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2411 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2412 // In C++11, constexpr, non-volatile variables initialized with constant
2413 // expressions are constant expressions too. Inside constexpr functions,
2414 // parameters are constant expressions even if they're non-const.
2415 // In C++1y, objects local to a constant expression (those with a Frame) are
2416 // both readable and writable inside constant expressions.
2417 // In C, such things can also be folded, although they are not ICEs.
2418 const VarDecl *VD = dyn_cast<VarDecl>(D);
2419 if (VD) {
2420 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2421 VD = VDef;
2422 }
2423 if (!VD || VD->isInvalidDecl()) {
2424 Info.Diag(E);
2425 return CompleteObject();
2426 }
2427
2428 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002429 if (BaseType.isVolatileQualified()) {
2430 if (Info.getLangOpts().CPlusPlus) {
2431 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2432 << AK << 1 << VD;
2433 Info.Note(VD->getLocation(), diag::note_declared_at);
2434 } else {
2435 Info.Diag(E);
2436 }
2437 return CompleteObject();
2438 }
2439
2440 // Unless we're looking at a local variable or argument in a constexpr call,
2441 // the variable we're reading must be const.
2442 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002443 if (Info.getLangOpts().CPlusPlus1y &&
2444 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2445 // OK, we can read and modify an object if we're in the process of
2446 // evaluating its initializer, because its lifetime began in this
2447 // evaluation.
2448 } else if (AK != AK_Read) {
2449 // All the remaining cases only permit reading.
2450 Info.Diag(E, diag::note_constexpr_modify_global);
2451 return CompleteObject();
2452 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002453 // OK, we can read this variable.
2454 } else if (BaseType->isIntegralOrEnumerationType()) {
2455 if (!BaseType.isConstQualified()) {
2456 if (Info.getLangOpts().CPlusPlus) {
2457 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2458 Info.Note(VD->getLocation(), diag::note_declared_at);
2459 } else {
2460 Info.Diag(E);
2461 }
2462 return CompleteObject();
2463 }
2464 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2465 // We support folding of const floating-point types, in order to make
2466 // static const data members of such types (supported as an extension)
2467 // more useful.
2468 if (Info.getLangOpts().CPlusPlus11) {
2469 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2470 Info.Note(VD->getLocation(), diag::note_declared_at);
2471 } else {
2472 Info.CCEDiag(E);
2473 }
2474 } else {
2475 // FIXME: Allow folding of values of any literal type in all languages.
2476 if (Info.getLangOpts().CPlusPlus11) {
2477 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2478 Info.Note(VD->getLocation(), diag::note_declared_at);
2479 } else {
2480 Info.Diag(E);
2481 }
2482 return CompleteObject();
2483 }
2484 }
2485
2486 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2487 return CompleteObject();
2488 } else {
2489 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2490
2491 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002492 if (const MaterializeTemporaryExpr *MTE =
2493 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2494 assert(MTE->getStorageDuration() == SD_Static &&
2495 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002496
Richard Smithe6c01442013-06-05 00:46:14 +00002497 // Per C++1y [expr.const]p2:
2498 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2499 // - a [...] glvalue of integral or enumeration type that refers to
2500 // a non-volatile const object [...]
2501 // [...]
2502 // - a [...] glvalue of literal type that refers to a non-volatile
2503 // object whose lifetime began within the evaluation of e.
2504 //
2505 // C++11 misses the 'began within the evaluation of e' check and
2506 // instead allows all temporaries, including things like:
2507 // int &&r = 1;
2508 // int x = ++r;
2509 // constexpr int k = r;
2510 // Therefore we use the C++1y rules in C++11 too.
2511 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2512 const ValueDecl *ED = MTE->getExtendingDecl();
2513 if (!(BaseType.isConstQualified() &&
2514 BaseType->isIntegralOrEnumerationType()) &&
2515 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2516 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2517 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2518 return CompleteObject();
2519 }
2520
2521 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2522 assert(BaseVal && "got reference to unevaluated temporary");
2523 } else {
2524 Info.Diag(E);
2525 return CompleteObject();
2526 }
2527 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002528 BaseVal = Frame->getTemporary(Base);
2529 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002530 }
Richard Smith3229b742013-05-05 21:17:10 +00002531
2532 // Volatile temporary objects cannot be accessed in constant expressions.
2533 if (BaseType.isVolatileQualified()) {
2534 if (Info.getLangOpts().CPlusPlus) {
2535 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2536 << AK << 0;
2537 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2538 } else {
2539 Info.Diag(E);
2540 }
2541 return CompleteObject();
2542 }
2543 }
2544
Richard Smith7525ff62013-05-09 07:14:00 +00002545 // During the construction of an object, it is not yet 'const'.
2546 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2547 // and this doesn't do quite the right thing for const subobjects of the
2548 // object under construction.
2549 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2550 BaseType = Info.Ctx.getCanonicalType(BaseType);
2551 BaseType.removeLocalConst();
2552 }
2553
Richard Smith6d4c6582013-11-05 22:18:15 +00002554 // In C++1y, we can't safely access any mutable state when we might be
2555 // evaluating after an unmodeled side effect or an evaluation failure.
2556 //
2557 // FIXME: Not all local state is mutable. Allow local constant subobjects
2558 // to be read here (but take care with 'mutable' fields).
Richard Smith3229b742013-05-05 21:17:10 +00002559 if (Frame && Info.getLangOpts().CPlusPlus1y &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002560 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002561 return CompleteObject();
2562
2563 return CompleteObject(BaseVal, BaseType);
2564}
2565
Richard Smith243ef902013-05-05 23:31:59 +00002566/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2567/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2568/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002569///
2570/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002571/// \param Conv - The expression for which we are performing the conversion.
2572/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002573/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2574/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002575/// \param LVal - The glvalue on which we are attempting to perform this action.
2576/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002577static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002578 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002579 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002580 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002581 return false;
2582
Richard Smith3229b742013-05-05 21:17:10 +00002583 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002584 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002585 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2586 !Type.isVolatileQualified()) {
2587 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2588 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2589 // initializer until now for such expressions. Such an expression can't be
2590 // an ICE in C, so this only matters for fold.
2591 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2592 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002593 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002594 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002595 }
Richard Smith3229b742013-05-05 21:17:10 +00002596 APValue Lit;
2597 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2598 return false;
2599 CompleteObject LitObj(&Lit, Base->getType());
2600 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2601 } else if (isa<StringLiteral>(Base)) {
2602 // We represent a string literal array as an lvalue pointing at the
2603 // corresponding expression, rather than building an array of chars.
2604 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2605 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2606 CompleteObject StrObj(&Str, Base->getType());
2607 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002608 }
Richard Smith11562c52011-10-28 17:51:58 +00002609 }
2610
Richard Smith3229b742013-05-05 21:17:10 +00002611 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2612 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002613}
2614
2615/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002616static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002617 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002618 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002619 return false;
2620
Richard Smith3229b742013-05-05 21:17:10 +00002621 if (!Info.getLangOpts().CPlusPlus1y) {
2622 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002623 return false;
2624 }
2625
Richard Smith3229b742013-05-05 21:17:10 +00002626 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2627 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002628}
2629
Richard Smith243ef902013-05-05 23:31:59 +00002630static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2631 return T->isSignedIntegerType() &&
2632 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2633}
2634
2635namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002636struct CompoundAssignSubobjectHandler {
2637 EvalInfo &Info;
2638 const Expr *E;
2639 QualType PromotedLHSType;
2640 BinaryOperatorKind Opcode;
2641 const APValue &RHS;
2642
2643 static const AccessKinds AccessKind = AK_Assign;
2644
2645 typedef bool result_type;
2646
2647 bool checkConst(QualType QT) {
2648 // Assigning to a const object has undefined behavior.
2649 if (QT.isConstQualified()) {
2650 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2651 return false;
2652 }
2653 return true;
2654 }
2655
2656 bool failed() { return false; }
2657 bool found(APValue &Subobj, QualType SubobjType) {
2658 switch (Subobj.getKind()) {
2659 case APValue::Int:
2660 return found(Subobj.getInt(), SubobjType);
2661 case APValue::Float:
2662 return found(Subobj.getFloat(), SubobjType);
2663 case APValue::ComplexInt:
2664 case APValue::ComplexFloat:
2665 // FIXME: Implement complex compound assignment.
2666 Info.Diag(E);
2667 return false;
2668 case APValue::LValue:
2669 return foundPointer(Subobj, SubobjType);
2670 default:
2671 // FIXME: can this happen?
2672 Info.Diag(E);
2673 return false;
2674 }
2675 }
2676 bool found(APSInt &Value, QualType SubobjType) {
2677 if (!checkConst(SubobjType))
2678 return false;
2679
2680 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2681 // We don't support compound assignment on integer-cast-to-pointer
2682 // values.
2683 Info.Diag(E);
2684 return false;
2685 }
2686
2687 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2688 SubobjType, Value);
2689 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2690 return false;
2691 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2692 return true;
2693 }
2694 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002695 return checkConst(SubobjType) &&
2696 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2697 Value) &&
2698 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2699 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002700 }
2701 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2702 if (!checkConst(SubobjType))
2703 return false;
2704
2705 QualType PointeeType;
2706 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2707 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002708
2709 if (PointeeType.isNull() || !RHS.isInt() ||
2710 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002711 Info.Diag(E);
2712 return false;
2713 }
2714
Richard Smith861b5b52013-05-07 23:34:45 +00002715 int64_t Offset = getExtValue(RHS.getInt());
2716 if (Opcode == BO_Sub)
2717 Offset = -Offset;
2718
2719 LValue LVal;
2720 LVal.setFrom(Info.Ctx, Subobj);
2721 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2722 return false;
2723 LVal.moveInto(Subobj);
2724 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002725 }
2726 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2727 llvm_unreachable("shouldn't encounter string elements here");
2728 }
2729};
2730} // end anonymous namespace
2731
2732const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2733
2734/// Perform a compound assignment of LVal <op>= RVal.
2735static bool handleCompoundAssignment(
2736 EvalInfo &Info, const Expr *E,
2737 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2738 BinaryOperatorKind Opcode, const APValue &RVal) {
2739 if (LVal.Designator.Invalid)
2740 return false;
2741
2742 if (!Info.getLangOpts().CPlusPlus1y) {
2743 Info.Diag(E);
2744 return false;
2745 }
2746
2747 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2748 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2749 RVal };
2750 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2751}
2752
2753namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002754struct IncDecSubobjectHandler {
2755 EvalInfo &Info;
2756 const Expr *E;
2757 AccessKinds AccessKind;
2758 APValue *Old;
2759
2760 typedef bool result_type;
2761
2762 bool checkConst(QualType QT) {
2763 // Assigning to a const object has undefined behavior.
2764 if (QT.isConstQualified()) {
2765 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2766 return false;
2767 }
2768 return true;
2769 }
2770
2771 bool failed() { return false; }
2772 bool found(APValue &Subobj, QualType SubobjType) {
2773 // Stash the old value. Also clear Old, so we don't clobber it later
2774 // if we're post-incrementing a complex.
2775 if (Old) {
2776 *Old = Subobj;
2777 Old = 0;
2778 }
2779
2780 switch (Subobj.getKind()) {
2781 case APValue::Int:
2782 return found(Subobj.getInt(), SubobjType);
2783 case APValue::Float:
2784 return found(Subobj.getFloat(), SubobjType);
2785 case APValue::ComplexInt:
2786 return found(Subobj.getComplexIntReal(),
2787 SubobjType->castAs<ComplexType>()->getElementType()
2788 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2789 case APValue::ComplexFloat:
2790 return found(Subobj.getComplexFloatReal(),
2791 SubobjType->castAs<ComplexType>()->getElementType()
2792 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2793 case APValue::LValue:
2794 return foundPointer(Subobj, SubobjType);
2795 default:
2796 // FIXME: can this happen?
2797 Info.Diag(E);
2798 return false;
2799 }
2800 }
2801 bool found(APSInt &Value, QualType SubobjType) {
2802 if (!checkConst(SubobjType))
2803 return false;
2804
2805 if (!SubobjType->isIntegerType()) {
2806 // We don't support increment / decrement on integer-cast-to-pointer
2807 // values.
2808 Info.Diag(E);
2809 return false;
2810 }
2811
2812 if (Old) *Old = APValue(Value);
2813
2814 // bool arithmetic promotes to int, and the conversion back to bool
2815 // doesn't reduce mod 2^n, so special-case it.
2816 if (SubobjType->isBooleanType()) {
2817 if (AccessKind == AK_Increment)
2818 Value = 1;
2819 else
2820 Value = !Value;
2821 return true;
2822 }
2823
2824 bool WasNegative = Value.isNegative();
2825 if (AccessKind == AK_Increment) {
2826 ++Value;
2827
2828 if (!WasNegative && Value.isNegative() &&
2829 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2830 APSInt ActualValue(Value, /*IsUnsigned*/true);
2831 HandleOverflow(Info, E, ActualValue, SubobjType);
2832 }
2833 } else {
2834 --Value;
2835
2836 if (WasNegative && !Value.isNegative() &&
2837 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2838 unsigned BitWidth = Value.getBitWidth();
2839 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2840 ActualValue.setBit(BitWidth);
2841 HandleOverflow(Info, E, ActualValue, SubobjType);
2842 }
2843 }
2844 return true;
2845 }
2846 bool found(APFloat &Value, QualType SubobjType) {
2847 if (!checkConst(SubobjType))
2848 return false;
2849
2850 if (Old) *Old = APValue(Value);
2851
2852 APFloat One(Value.getSemantics(), 1);
2853 if (AccessKind == AK_Increment)
2854 Value.add(One, APFloat::rmNearestTiesToEven);
2855 else
2856 Value.subtract(One, APFloat::rmNearestTiesToEven);
2857 return true;
2858 }
2859 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2860 if (!checkConst(SubobjType))
2861 return false;
2862
2863 QualType PointeeType;
2864 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2865 PointeeType = PT->getPointeeType();
2866 else {
2867 Info.Diag(E);
2868 return false;
2869 }
2870
2871 LValue LVal;
2872 LVal.setFrom(Info.Ctx, Subobj);
2873 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2874 AccessKind == AK_Increment ? 1 : -1))
2875 return false;
2876 LVal.moveInto(Subobj);
2877 return true;
2878 }
2879 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2880 llvm_unreachable("shouldn't encounter string elements here");
2881 }
2882};
2883} // end anonymous namespace
2884
2885/// Perform an increment or decrement on LVal.
2886static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2887 QualType LValType, bool IsIncrement, APValue *Old) {
2888 if (LVal.Designator.Invalid)
2889 return false;
2890
2891 if (!Info.getLangOpts().CPlusPlus1y) {
2892 Info.Diag(E);
2893 return false;
2894 }
2895
2896 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2897 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2898 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2899 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2900}
2901
Richard Smithe97cbd72011-11-11 04:05:33 +00002902/// Build an lvalue for the object argument of a member function call.
2903static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2904 LValue &This) {
2905 if (Object->getType()->isPointerType())
2906 return EvaluatePointer(Object, This, Info);
2907
2908 if (Object->isGLValue())
2909 return EvaluateLValue(Object, This, Info);
2910
Richard Smithd9f663b2013-04-22 15:31:51 +00002911 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002912 return EvaluateTemporary(Object, This, Info);
2913
2914 return false;
2915}
2916
2917/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2918/// lvalue referring to the result.
2919///
2920/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002921/// \param LV - An lvalue referring to the base of the member pointer.
2922/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002923/// \param IncludeMember - Specifies whether the member itself is included in
2924/// the resulting LValue subobject designator. This is not possible when
2925/// creating a bound member function.
2926/// \return The field or method declaration to which the member pointer refers,
2927/// or 0 if evaluation fails.
2928static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002929 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002930 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002931 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002932 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002933 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002934 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002935 return 0;
2936
2937 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2938 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002939 if (!MemPtr.getDecl()) {
2940 // FIXME: Specific diagnostic.
2941 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002942 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002943 }
Richard Smith253c2a32012-01-27 01:14:48 +00002944
Richard Smith027bf112011-11-17 22:56:20 +00002945 if (MemPtr.isDerivedMember()) {
2946 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002947 // The end of the derived-to-base path for the base object must match the
2948 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002949 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002950 LV.Designator.Entries.size()) {
2951 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002952 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002953 }
Richard Smith027bf112011-11-17 22:56:20 +00002954 unsigned PathLengthToMember =
2955 LV.Designator.Entries.size() - MemPtr.Path.size();
2956 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2957 const CXXRecordDecl *LVDecl = getAsBaseClass(
2958 LV.Designator.Entries[PathLengthToMember + I]);
2959 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002960 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2961 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002962 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002963 }
Richard Smith027bf112011-11-17 22:56:20 +00002964 }
2965
2966 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002967 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002968 PathLengthToMember))
2969 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002970 } else if (!MemPtr.Path.empty()) {
2971 // Extend the LValue path with the member pointer's path.
2972 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2973 MemPtr.Path.size() + IncludeMember);
2974
2975 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002976 if (const PointerType *PT = LVType->getAs<PointerType>())
2977 LVType = PT->getPointeeType();
2978 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2979 assert(RD && "member pointer access on non-class-type expression");
2980 // The first class in the path is that of the lvalue.
2981 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2982 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002983 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002984 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002985 RD = Base;
2986 }
2987 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002988 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2989 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002990 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002991 }
2992
2993 // Add the member. Note that we cannot build bound member functions here.
2994 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002995 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002996 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002997 return 0;
2998 } else if (const IndirectFieldDecl *IFD =
2999 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003000 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00003001 return 0;
3002 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003003 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003004 }
Richard Smith027bf112011-11-17 22:56:20 +00003005 }
3006
3007 return MemPtr.getDecl();
3008}
3009
Richard Smith84401042013-06-03 05:03:02 +00003010static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3011 const BinaryOperator *BO,
3012 LValue &LV,
3013 bool IncludeMember = true) {
3014 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3015
3016 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3017 if (Info.keepEvaluatingAfterFailure()) {
3018 MemberPtr MemPtr;
3019 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3020 }
3021 return 0;
3022 }
3023
3024 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3025 BO->getRHS(), IncludeMember);
3026}
3027
Richard Smith027bf112011-11-17 22:56:20 +00003028/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3029/// the provided lvalue, which currently refers to the base object.
3030static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3031 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003032 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003033 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003034 return false;
3035
Richard Smitha8105bc2012-01-06 16:39:00 +00003036 QualType TargetQT = E->getType();
3037 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3038 TargetQT = PT->getPointeeType();
3039
3040 // Check this cast lands within the final derived-to-base subobject path.
3041 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003042 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003043 << D.MostDerivedType << TargetQT;
3044 return false;
3045 }
3046
Richard Smith027bf112011-11-17 22:56:20 +00003047 // Check the type of the final cast. We don't need to check the path,
3048 // since a cast can only be formed if the path is unique.
3049 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003050 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3051 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003052 if (NewEntriesSize == D.MostDerivedPathLength)
3053 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3054 else
Richard Smith027bf112011-11-17 22:56:20 +00003055 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003057 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003058 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003059 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003060 }
Richard Smith027bf112011-11-17 22:56:20 +00003061
3062 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003063 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003064}
3065
Mike Stump876387b2009-10-27 22:09:17 +00003066namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003067enum EvalStmtResult {
3068 /// Evaluation failed.
3069 ESR_Failed,
3070 /// Hit a 'return' statement.
3071 ESR_Returned,
3072 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003073 ESR_Succeeded,
3074 /// Hit a 'continue' statement.
3075 ESR_Continue,
3076 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003077 ESR_Break,
3078 /// Still scanning for 'case' or 'default' statement.
3079 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003080};
3081}
3082
Richard Smithd9f663b2013-04-22 15:31:51 +00003083static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3084 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3085 // We don't need to evaluate the initializer for a static local.
3086 if (!VD->hasLocalStorage())
3087 return true;
3088
3089 LValue Result;
3090 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003091 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003092
Richard Smith51f03172013-06-20 03:00:05 +00003093 if (!VD->getInit()) {
3094 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3095 << false << VD->getType();
3096 Val = APValue();
3097 return false;
3098 }
3099
Richard Smithd9f663b2013-04-22 15:31:51 +00003100 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3101 // Wipe out any partially-computed value, to allow tracking that this
3102 // evaluation failed.
3103 Val = APValue();
3104 return false;
3105 }
3106 }
3107
3108 return true;
3109}
3110
Richard Smith4e18ca52013-05-06 05:56:11 +00003111/// Evaluate a condition (either a variable declaration or an expression).
3112static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3113 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003114 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003115 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3116 return false;
3117 return EvaluateAsBooleanCondition(Cond, Result, Info);
3118}
3119
3120static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003121 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003122
3123/// Evaluate the body of a loop, and translate the result as appropriate.
3124static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003125 const Stmt *Body,
3126 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003127 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003128 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003129 case ESR_Break:
3130 return ESR_Succeeded;
3131 case ESR_Succeeded:
3132 case ESR_Continue:
3133 return ESR_Continue;
3134 case ESR_Failed:
3135 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003136 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003137 return ESR;
3138 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003139 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003140}
3141
Richard Smith496ddcf2013-05-12 17:32:42 +00003142/// Evaluate a switch statement.
3143static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3144 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003145 BlockScopeRAII Scope(Info);
3146
Richard Smith496ddcf2013-05-12 17:32:42 +00003147 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003148 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003149 {
3150 FullExpressionRAII Scope(Info);
3151 if (SS->getConditionVariable() &&
3152 !EvaluateDecl(Info, SS->getConditionVariable()))
3153 return ESR_Failed;
3154 if (!EvaluateInteger(SS->getCond(), Value, Info))
3155 return ESR_Failed;
3156 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003157
3158 // Find the switch case corresponding to the value of the condition.
3159 // FIXME: Cache this lookup.
3160 const SwitchCase *Found = 0;
3161 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3162 SC = SC->getNextSwitchCase()) {
3163 if (isa<DefaultStmt>(SC)) {
3164 Found = SC;
3165 continue;
3166 }
3167
3168 const CaseStmt *CS = cast<CaseStmt>(SC);
3169 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3170 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3171 : LHS;
3172 if (LHS <= Value && Value <= RHS) {
3173 Found = SC;
3174 break;
3175 }
3176 }
3177
3178 if (!Found)
3179 return ESR_Succeeded;
3180
3181 // Search the switch body for the switch case and evaluate it from there.
3182 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3183 case ESR_Break:
3184 return ESR_Succeeded;
3185 case ESR_Succeeded:
3186 case ESR_Continue:
3187 case ESR_Failed:
3188 case ESR_Returned:
3189 return ESR;
3190 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003191 // This can only happen if the switch case is nested within a statement
3192 // expression. We have no intention of supporting that.
3193 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3194 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003195 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003196 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003197}
3198
Richard Smith254a73d2011-10-28 22:34:42 +00003199// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003200static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003201 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003202 if (!Info.nextStep(S))
3203 return ESR_Failed;
3204
Richard Smith496ddcf2013-05-12 17:32:42 +00003205 // If we're hunting down a 'case' or 'default' label, recurse through
3206 // substatements until we hit the label.
3207 if (Case) {
3208 // FIXME: We don't start the lifetime of objects whose initialization we
3209 // jump over. However, such objects must be of class type with a trivial
3210 // default constructor that initialize all subobjects, so must be empty,
3211 // so this almost never matters.
3212 switch (S->getStmtClass()) {
3213 case Stmt::CompoundStmtClass:
3214 // FIXME: Precompute which substatement of a compound statement we
3215 // would jump to, and go straight there rather than performing a
3216 // linear scan each time.
3217 case Stmt::LabelStmtClass:
3218 case Stmt::AttributedStmtClass:
3219 case Stmt::DoStmtClass:
3220 break;
3221
3222 case Stmt::CaseStmtClass:
3223 case Stmt::DefaultStmtClass:
3224 if (Case == S)
3225 Case = 0;
3226 break;
3227
3228 case Stmt::IfStmtClass: {
3229 // FIXME: Precompute which side of an 'if' we would jump to, and go
3230 // straight there rather than scanning both sides.
3231 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003232
3233 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3234 // preceded by our switch label.
3235 BlockScopeRAII Scope(Info);
3236
Richard Smith496ddcf2013-05-12 17:32:42 +00003237 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3238 if (ESR != ESR_CaseNotFound || !IS->getElse())
3239 return ESR;
3240 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3241 }
3242
3243 case Stmt::WhileStmtClass: {
3244 EvalStmtResult ESR =
3245 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3246 if (ESR != ESR_Continue)
3247 return ESR;
3248 break;
3249 }
3250
3251 case Stmt::ForStmtClass: {
3252 const ForStmt *FS = cast<ForStmt>(S);
3253 EvalStmtResult ESR =
3254 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3255 if (ESR != ESR_Continue)
3256 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003257 if (FS->getInc()) {
3258 FullExpressionRAII IncScope(Info);
3259 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3260 return ESR_Failed;
3261 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003262 break;
3263 }
3264
3265 case Stmt::DeclStmtClass:
3266 // FIXME: If the variable has initialization that can't be jumped over,
3267 // bail out of any immediately-surrounding compound-statement too.
3268 default:
3269 return ESR_CaseNotFound;
3270 }
3271 }
3272
Richard Smith254a73d2011-10-28 22:34:42 +00003273 switch (S->getStmtClass()) {
3274 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003275 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003276 // Don't bother evaluating beyond an expression-statement which couldn't
3277 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003278 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003279 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003280 return ESR_Failed;
3281 return ESR_Succeeded;
3282 }
3283
3284 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003285 return ESR_Failed;
3286
3287 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003288 return ESR_Succeeded;
3289
Richard Smithd9f663b2013-04-22 15:31:51 +00003290 case Stmt::DeclStmtClass: {
3291 const DeclStmt *DS = cast<DeclStmt>(S);
3292 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003293 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3294 // Each declaration initialization is its own full-expression.
3295 // FIXME: This isn't quite right; if we're performing aggregate
3296 // initialization, each braced subexpression is its own full-expression.
3297 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003298 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3299 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003300 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003301 return ESR_Succeeded;
3302 }
3303
Richard Smith357362d2011-12-13 06:39:58 +00003304 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003305 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003306 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003307 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003308 return ESR_Failed;
3309 return ESR_Returned;
3310 }
Richard Smith254a73d2011-10-28 22:34:42 +00003311
3312 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003313 BlockScopeRAII Scope(Info);
3314
Richard Smith254a73d2011-10-28 22:34:42 +00003315 const CompoundStmt *CS = cast<CompoundStmt>(S);
3316 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3317 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003318 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3319 if (ESR == ESR_Succeeded)
3320 Case = 0;
3321 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003322 return ESR;
3323 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003324 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003325 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003326
3327 case Stmt::IfStmtClass: {
3328 const IfStmt *IS = cast<IfStmt>(S);
3329
3330 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003331 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003332 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003333 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003334 return ESR_Failed;
3335
3336 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3337 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3338 if (ESR != ESR_Succeeded)
3339 return ESR;
3340 }
3341 return ESR_Succeeded;
3342 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003343
3344 case Stmt::WhileStmtClass: {
3345 const WhileStmt *WS = cast<WhileStmt>(S);
3346 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003347 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003348 bool Continue;
3349 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3350 Continue))
3351 return ESR_Failed;
3352 if (!Continue)
3353 break;
3354
3355 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3356 if (ESR != ESR_Continue)
3357 return ESR;
3358 }
3359 return ESR_Succeeded;
3360 }
3361
3362 case Stmt::DoStmtClass: {
3363 const DoStmt *DS = cast<DoStmt>(S);
3364 bool Continue;
3365 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003366 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003367 if (ESR != ESR_Continue)
3368 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003369 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003370
Richard Smith08d6a2c2013-07-24 07:11:57 +00003371 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003372 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3373 return ESR_Failed;
3374 } while (Continue);
3375 return ESR_Succeeded;
3376 }
3377
3378 case Stmt::ForStmtClass: {
3379 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003380 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003381 if (FS->getInit()) {
3382 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3383 if (ESR != ESR_Succeeded)
3384 return ESR;
3385 }
3386 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003387 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003388 bool Continue = true;
3389 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3390 FS->getCond(), Continue))
3391 return ESR_Failed;
3392 if (!Continue)
3393 break;
3394
3395 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3396 if (ESR != ESR_Continue)
3397 return ESR;
3398
Richard Smith08d6a2c2013-07-24 07:11:57 +00003399 if (FS->getInc()) {
3400 FullExpressionRAII IncScope(Info);
3401 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3402 return ESR_Failed;
3403 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003404 }
3405 return ESR_Succeeded;
3406 }
3407
Richard Smith896e0d72013-05-06 06:51:17 +00003408 case Stmt::CXXForRangeStmtClass: {
3409 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003410 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003411
3412 // Initialize the __range variable.
3413 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3414 if (ESR != ESR_Succeeded)
3415 return ESR;
3416
3417 // Create the __begin and __end iterators.
3418 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3419 if (ESR != ESR_Succeeded)
3420 return ESR;
3421
3422 while (true) {
3423 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003424 {
3425 bool Continue = true;
3426 FullExpressionRAII CondExpr(Info);
3427 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3428 return ESR_Failed;
3429 if (!Continue)
3430 break;
3431 }
Richard Smith896e0d72013-05-06 06:51:17 +00003432
3433 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003434 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003435 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3436 if (ESR != ESR_Succeeded)
3437 return ESR;
3438
3439 // Loop body.
3440 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3441 if (ESR != ESR_Continue)
3442 return ESR;
3443
3444 // Increment: ++__begin
3445 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3446 return ESR_Failed;
3447 }
3448
3449 return ESR_Succeeded;
3450 }
3451
Richard Smith496ddcf2013-05-12 17:32:42 +00003452 case Stmt::SwitchStmtClass:
3453 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3454
Richard Smith4e18ca52013-05-06 05:56:11 +00003455 case Stmt::ContinueStmtClass:
3456 return ESR_Continue;
3457
3458 case Stmt::BreakStmtClass:
3459 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003460
3461 case Stmt::LabelStmtClass:
3462 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3463
3464 case Stmt::AttributedStmtClass:
3465 // As a general principle, C++11 attributes can be ignored without
3466 // any semantic impact.
3467 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3468 Case);
3469
3470 case Stmt::CaseStmtClass:
3471 case Stmt::DefaultStmtClass:
3472 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003473 }
3474}
3475
Richard Smithcc36f692011-12-22 02:22:31 +00003476/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3477/// default constructor. If so, we'll fold it whether or not it's marked as
3478/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3479/// so we need special handling.
3480static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003481 const CXXConstructorDecl *CD,
3482 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003483 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3484 return false;
3485
Richard Smith66e05fe2012-01-18 05:21:49 +00003486 // Value-initialization does not call a trivial default constructor, so such a
3487 // call is a core constant expression whether or not the constructor is
3488 // constexpr.
3489 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003490 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003491 // FIXME: If DiagDecl is an implicitly-declared special member function,
3492 // we should be much more explicit about why it's not constexpr.
3493 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3494 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3495 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003496 } else {
3497 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3498 }
3499 }
3500 return true;
3501}
3502
Richard Smith357362d2011-12-13 06:39:58 +00003503/// CheckConstexprFunction - Check that a function can be called in a constant
3504/// expression.
3505static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3506 const FunctionDecl *Declaration,
3507 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003508 // Potential constant expressions can contain calls to declared, but not yet
3509 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003510 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003511 Declaration->isConstexpr())
3512 return false;
3513
Richard Smith0838f3a2013-05-14 05:18:44 +00003514 // Bail out with no diagnostic if the function declaration itself is invalid.
3515 // We will have produced a relevant diagnostic while parsing it.
3516 if (Declaration->isInvalidDecl())
3517 return false;
3518
Richard Smith357362d2011-12-13 06:39:58 +00003519 // Can we evaluate this function call?
3520 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3521 return true;
3522
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003523 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003524 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003525 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3526 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003527 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3528 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3529 << DiagDecl;
3530 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3531 } else {
3532 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3533 }
3534 return false;
3535}
3536
Richard Smithd62306a2011-11-10 06:34:14 +00003537namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003538typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003539}
3540
3541/// EvaluateArgs - Evaluate the arguments to a function call.
3542static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3543 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003544 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003545 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003546 I != E; ++I) {
3547 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3548 // If we're checking for a potential constant expression, evaluate all
3549 // initializers even if some of them fail.
3550 if (!Info.keepEvaluatingAfterFailure())
3551 return false;
3552 Success = false;
3553 }
3554 }
3555 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003556}
3557
Richard Smith254a73d2011-10-28 22:34:42 +00003558/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003559static bool HandleFunctionCall(SourceLocation CallLoc,
3560 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003561 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003562 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003563 ArgVector ArgValues(Args.size());
3564 if (!EvaluateArgs(Args, ArgValues, Info))
3565 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003566
Richard Smith253c2a32012-01-27 01:14:48 +00003567 if (!Info.CheckCallLimit(CallLoc))
3568 return false;
3569
3570 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003571
3572 // For a trivial copy or move assignment, perform an APValue copy. This is
3573 // essential for unions, where the operations performed by the assignment
3574 // operator cannot be represented as statements.
3575 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3576 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3577 assert(This &&
3578 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3579 LValue RHS;
3580 RHS.setFrom(Info.Ctx, ArgValues[0]);
3581 APValue RHSValue;
3582 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3583 RHS, RHSValue))
3584 return false;
3585 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3586 RHSValue))
3587 return false;
3588 This->moveInto(Result);
3589 return true;
3590 }
3591
Richard Smithd9f663b2013-04-22 15:31:51 +00003592 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003593 if (ESR == ESR_Succeeded) {
3594 if (Callee->getResultType()->isVoidType())
3595 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003596 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003597 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003598 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003599}
3600
Richard Smithd62306a2011-11-10 06:34:14 +00003601/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003602static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003603 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003604 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003605 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003606 ArgVector ArgValues(Args.size());
3607 if (!EvaluateArgs(Args, ArgValues, Info))
3608 return false;
3609
Richard Smith253c2a32012-01-27 01:14:48 +00003610 if (!Info.CheckCallLimit(CallLoc))
3611 return false;
3612
Richard Smith3607ffe2012-02-13 03:54:03 +00003613 const CXXRecordDecl *RD = Definition->getParent();
3614 if (RD->getNumVBases()) {
3615 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3616 return false;
3617 }
3618
Richard Smith253c2a32012-01-27 01:14:48 +00003619 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003620
3621 // If it's a delegating constructor, just delegate.
3622 if (Definition->isDelegatingConstructor()) {
3623 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003624 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3625 return false;
3626 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003627 }
3628
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003629 // For a trivial copy or move constructor, perform an APValue copy. This is
3630 // essential for unions, where the operations performed by the constructor
3631 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003632 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003633 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3634 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003635 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003636 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003637 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003638 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003639 }
3640
3641 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003642 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003643 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3644 std::distance(RD->field_begin(), RD->field_end()));
3645
John McCalld7bca762012-05-01 00:38:49 +00003646 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003647 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3648
Richard Smith08d6a2c2013-07-24 07:11:57 +00003649 // A scope for temporaries lifetime-extended by reference members.
3650 BlockScopeRAII LifetimeExtendedScope(Info);
3651
Richard Smith253c2a32012-01-27 01:14:48 +00003652 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003653 unsigned BasesSeen = 0;
3654#ifndef NDEBUG
3655 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3656#endif
3657 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3658 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003659 LValue Subobject = This;
3660 APValue *Value = &Result;
3661
3662 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003663 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003664 if ((*I)->isBaseInitializer()) {
3665 QualType BaseType((*I)->getBaseClass(), 0);
3666#ifndef NDEBUG
3667 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003668 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003669 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3670 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3671 "base class initializers not in expected order");
3672 ++BaseIt;
3673#endif
John McCalld7bca762012-05-01 00:38:49 +00003674 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3675 BaseType->getAsCXXRecordDecl(), &Layout))
3676 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003677 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003678 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003679 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3680 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003681 if (RD->isUnion()) {
3682 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003683 Value = &Result.getUnionValue();
3684 } else {
3685 Value = &Result.getStructField(FD->getFieldIndex());
3686 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003687 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003688 // Walk the indirect field decl's chain to find the object to initialize,
3689 // and make sure we've initialized every step along it.
3690 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3691 CE = IFD->chain_end();
3692 C != CE; ++C) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003693 FD = cast<FieldDecl>(*C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003694 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3695 // Switch the union field if it differs. This happens if we had
3696 // preceding zero-initialization, and we're now initializing a union
3697 // subobject other than the first.
3698 // FIXME: In this case, the values of the other subobjects are
3699 // specified, since zero-initialization sets all padding bits to zero.
3700 if (Value->isUninit() ||
3701 (Value->isUnion() && Value->getUnionField() != FD)) {
3702 if (CD->isUnion())
3703 *Value = APValue(FD);
3704 else
3705 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3706 std::distance(CD->field_begin(), CD->field_end()));
3707 }
John McCalld7bca762012-05-01 00:38:49 +00003708 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3709 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003710 if (CD->isUnion())
3711 Value = &Value->getUnionValue();
3712 else
3713 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003714 }
Richard Smithd62306a2011-11-10 06:34:14 +00003715 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003716 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003717 }
Richard Smith253c2a32012-01-27 01:14:48 +00003718
Richard Smith08d6a2c2013-07-24 07:11:57 +00003719 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003720 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3721 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3722 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003723 // If we're checking for a potential constant expression, evaluate all
3724 // initializers even if some of them fail.
3725 if (!Info.keepEvaluatingAfterFailure())
3726 return false;
3727 Success = false;
3728 }
Richard Smithd62306a2011-11-10 06:34:14 +00003729 }
3730
Richard Smithd9f663b2013-04-22 15:31:51 +00003731 return Success &&
3732 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003733}
3734
Eli Friedman9a156e52008-11-12 09:44:48 +00003735//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003736// Generic Evaluation
3737//===----------------------------------------------------------------------===//
3738namespace {
3739
Richard Smithf57d8cb2011-12-09 22:58:01 +00003740// FIXME: RetTy is always bool. Remove it.
3741template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003742class ExprEvaluatorBase
3743 : public ConstStmtVisitor<Derived, RetTy> {
3744private:
Richard Smith2e312c82012-03-03 22:46:17 +00003745 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003746 return static_cast<Derived*>(this)->Success(V, E);
3747 }
Richard Smithfddd3842011-12-30 21:15:51 +00003748 RetTy DerivedZeroInitialization(const Expr *E) {
3749 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003750 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003751
Richard Smith17100ba2012-02-16 02:46:34 +00003752 // Check whether a conditional operator with a non-constant condition is a
3753 // potential constant expression. If neither arm is a potential constant
3754 // expression, then the conditional operator is not either.
3755 template<typename ConditionalOperator>
3756 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003757 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003758
3759 // Speculatively evaluate both arms.
3760 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003761 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003762 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3763
3764 StmtVisitorTy::Visit(E->getFalseExpr());
3765 if (Diag.empty())
3766 return;
3767
3768 Diag.clear();
3769 StmtVisitorTy::Visit(E->getTrueExpr());
3770 if (Diag.empty())
3771 return;
3772 }
3773
3774 Error(E, diag::note_constexpr_conditional_never_const);
3775 }
3776
3777
3778 template<typename ConditionalOperator>
3779 bool HandleConditionalOperator(const ConditionalOperator *E) {
3780 bool BoolResult;
3781 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003782 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003783 CheckPotentialConstantConditional(E);
3784 return false;
3785 }
3786
3787 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3788 return StmtVisitorTy::Visit(EvalExpr);
3789 }
3790
Peter Collingbournee9200682011-05-13 03:29:01 +00003791protected:
3792 EvalInfo &Info;
3793 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3794 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3795
Richard Smith92b1ce02011-12-12 09:28:41 +00003796 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003797 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003798 }
3799
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003800 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3801
3802public:
3803 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3804
3805 EvalInfo &getEvalInfo() { return Info; }
3806
Richard Smithf57d8cb2011-12-09 22:58:01 +00003807 /// Report an evaluation error. This should only be called when an error is
3808 /// first discovered. When propagating an error, just return false.
3809 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003810 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003811 return false;
3812 }
3813 bool Error(const Expr *E) {
3814 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3815 }
3816
Peter Collingbournee9200682011-05-13 03:29:01 +00003817 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003818 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003819 }
3820 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003821 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003822 }
3823
3824 RetTy VisitParenExpr(const ParenExpr *E)
3825 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3826 RetTy VisitUnaryExtension(const UnaryOperator *E)
3827 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3828 RetTy VisitUnaryPlus(const UnaryOperator *E)
3829 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3830 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003831 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003832 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3833 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003834 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3835 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003836 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3837 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith17e32462013-09-13 20:51:45 +00003838 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3839 // The initializer may not have been parsed yet, or might be erroneous.
3840 if (!E->getExpr())
3841 return Error(E);
3842 return StmtVisitorTy::Visit(E->getExpr());
3843 }
Richard Smith5894a912011-12-19 22:12:41 +00003844 // We cannot create any objects for which cleanups are required, so there is
3845 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3846 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3847 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003848
Richard Smith6d6ecc32011-12-12 12:46:16 +00003849 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3850 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3851 return static_cast<Derived*>(this)->VisitCastExpr(E);
3852 }
3853 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3854 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3855 return static_cast<Derived*>(this)->VisitCastExpr(E);
3856 }
3857
Richard Smith027bf112011-11-17 22:56:20 +00003858 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3859 switch (E->getOpcode()) {
3860 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003861 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003862
3863 case BO_Comma:
3864 VisitIgnoredValue(E->getLHS());
3865 return StmtVisitorTy::Visit(E->getRHS());
3866
3867 case BO_PtrMemD:
3868 case BO_PtrMemI: {
3869 LValue Obj;
3870 if (!HandleMemberPointerAccess(Info, E, Obj))
3871 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003872 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003873 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003874 return false;
3875 return DerivedSuccess(Result, E);
3876 }
3877 }
3878 }
3879
Peter Collingbournee9200682011-05-13 03:29:01 +00003880 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003881 // Evaluate and cache the common expression. We treat it as a temporary,
3882 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003883 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003884 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003885 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003886
Richard Smith17100ba2012-02-16 02:46:34 +00003887 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003888 }
3889
3890 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003891 bool IsBcpCall = false;
3892 // If the condition (ignoring parens) is a __builtin_constant_p call,
3893 // the result is a constant expression if it can be folded without
3894 // side-effects. This is an important GNU extension. See GCC PR38377
3895 // for discussion.
3896 if (const CallExpr *CallCE =
3897 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3898 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3899 IsBcpCall = true;
3900
3901 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3902 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00003903 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00003904 return false;
3905
Richard Smith6d4c6582013-11-05 22:18:15 +00003906 FoldConstant Fold(Info, IsBcpCall);
3907 if (!HandleConditionalOperator(E)) {
3908 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003909 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00003910 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00003911
3912 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003913 }
3914
3915 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003916 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3917 return DerivedSuccess(*Value, E);
3918
3919 const Expr *Source = E->getSourceExpr();
3920 if (!Source)
3921 return Error(E);
3922 if (Source == E) { // sanity checking.
3923 assert(0 && "OpaqueValueExpr recursively refers to itself");
3924 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003925 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003926 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003927 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003928
Richard Smith254a73d2011-10-28 22:34:42 +00003929 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003930 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003931 QualType CalleeType = Callee->getType();
3932
Richard Smith254a73d2011-10-28 22:34:42 +00003933 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003934 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003935 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003936 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003937
Richard Smithe97cbd72011-11-11 04:05:33 +00003938 // Extract function decl and 'this' pointer from the callee.
3939 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003940 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003941 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3942 // Explicit bound member calls, such as x.f() or p->g();
3943 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003944 return false;
3945 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003946 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003947 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003948 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3949 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003950 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3951 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003952 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003953 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003954 return Error(Callee);
3955
3956 FD = dyn_cast<FunctionDecl>(Member);
3957 if (!FD)
3958 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003959 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003960 LValue Call;
3961 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003962 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003963
Richard Smitha8105bc2012-01-06 16:39:00 +00003964 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003965 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003966 FD = dyn_cast_or_null<FunctionDecl>(
3967 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003968 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003969 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003970
3971 // Overloaded operator calls to member functions are represented as normal
3972 // calls with '*this' as the first argument.
3973 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3974 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003975 // FIXME: When selecting an implicit conversion for an overloaded
3976 // operator delete, we sometimes try to evaluate calls to conversion
3977 // operators without a 'this' parameter!
3978 if (Args.empty())
3979 return Error(E);
3980
Richard Smithe97cbd72011-11-11 04:05:33 +00003981 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3982 return false;
3983 This = &ThisVal;
3984 Args = Args.slice(1);
3985 }
3986
3987 // Don't call function pointers which have been cast to some other type.
3988 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003989 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003990 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003991 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003992
Richard Smith47b34932012-02-01 02:39:43 +00003993 if (This && !This->checkSubobject(Info, E, CSK_This))
3994 return false;
3995
Richard Smith3607ffe2012-02-13 03:54:03 +00003996 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3997 // calls to such functions in constant expressions.
3998 if (This && !HasQualifier &&
3999 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4000 return Error(E, diag::note_constexpr_virtual_call);
4001
Richard Smith357362d2011-12-13 06:39:58 +00004002 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00004003 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004004 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004005
Richard Smith357362d2011-12-13 06:39:58 +00004006 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004007 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4008 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004009 return false;
4010
Richard Smithb228a862012-02-15 02:18:13 +00004011 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004012 }
4013
Richard Smith11562c52011-10-28 17:51:58 +00004014 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4015 return StmtVisitorTy::Visit(E->getInitializer());
4016 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004017 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004018 if (E->getNumInits() == 0)
4019 return DerivedZeroInitialization(E);
4020 if (E->getNumInits() == 1)
4021 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004022 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004023 }
4024 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004025 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004026 }
4027 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004028 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004029 }
Richard Smith027bf112011-11-17 22:56:20 +00004030 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004031 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004032 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004033
Richard Smithd62306a2011-11-10 06:34:14 +00004034 /// A member expression where the object is a prvalue is itself a prvalue.
4035 RetTy VisitMemberExpr(const MemberExpr *E) {
4036 assert(!E->isArrow() && "missing call to bound member function?");
4037
Richard Smith2e312c82012-03-03 22:46:17 +00004038 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004039 if (!Evaluate(Val, Info, E->getBase()))
4040 return false;
4041
4042 QualType BaseTy = E->getBase()->getType();
4043
4044 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004045 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004046 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004047 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004048 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4049
Richard Smith3229b742013-05-05 21:17:10 +00004050 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004051 SubobjectDesignator Designator(BaseTy);
4052 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004053
Richard Smith3229b742013-05-05 21:17:10 +00004054 APValue Result;
4055 return extractSubobject(Info, E, Obj, Designator, Result) &&
4056 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004057 }
4058
Richard Smith11562c52011-10-28 17:51:58 +00004059 RetTy VisitCastExpr(const CastExpr *E) {
4060 switch (E->getCastKind()) {
4061 default:
4062 break;
4063
Richard Smitha23ab512013-05-23 00:30:41 +00004064 case CK_AtomicToNonAtomic: {
4065 APValue AtomicVal;
4066 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4067 return false;
4068 return DerivedSuccess(AtomicVal, E);
4069 }
4070
Richard Smith11562c52011-10-28 17:51:58 +00004071 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004072 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004073 return StmtVisitorTy::Visit(E->getSubExpr());
4074
4075 case CK_LValueToRValue: {
4076 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004077 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4078 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004079 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004080 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004081 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004082 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004083 return false;
4084 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004085 }
4086 }
4087
Richard Smithf57d8cb2011-12-09 22:58:01 +00004088 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004089 }
4090
Richard Smith243ef902013-05-05 23:31:59 +00004091 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4092 return VisitUnaryPostIncDec(UO);
4093 }
4094 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4095 return VisitUnaryPostIncDec(UO);
4096 }
4097 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4098 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4099 return Error(UO);
4100
4101 LValue LVal;
4102 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4103 return false;
4104 APValue RVal;
4105 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4106 UO->isIncrementOp(), &RVal))
4107 return false;
4108 return DerivedSuccess(RVal, UO);
4109 }
4110
Richard Smith51f03172013-06-20 03:00:05 +00004111 RetTy VisitStmtExpr(const StmtExpr *E) {
4112 // We will have checked the full-expressions inside the statement expression
4113 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004114 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004115 return Error(E);
4116
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004118 const CompoundStmt *CS = E->getSubStmt();
4119 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4120 BE = CS->body_end();
4121 /**/; ++BI) {
4122 if (BI + 1 == BE) {
4123 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4124 if (!FinalExpr) {
4125 Info.Diag((*BI)->getLocStart(),
4126 diag::note_constexpr_stmt_expr_unsupported);
4127 return false;
4128 }
4129 return this->Visit(FinalExpr);
4130 }
4131
4132 APValue ReturnValue;
4133 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4134 if (ESR != ESR_Succeeded) {
4135 // FIXME: If the statement-expression terminated due to 'return',
4136 // 'break', or 'continue', it would be nice to propagate that to
4137 // the outer statement evaluation rather than bailing out.
4138 if (ESR != ESR_Failed)
4139 Info.Diag((*BI)->getLocStart(),
4140 diag::note_constexpr_stmt_expr_unsupported);
4141 return false;
4142 }
4143 }
4144 }
4145
Richard Smith4a678122011-10-24 18:44:57 +00004146 /// Visit a value which is evaluated, but whose value is ignored.
4147 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004148 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004149 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004150};
4151
4152}
4153
4154//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004155// Common base class for lvalue and temporary evaluation.
4156//===----------------------------------------------------------------------===//
4157namespace {
4158template<class Derived>
4159class LValueExprEvaluatorBase
4160 : public ExprEvaluatorBase<Derived, bool> {
4161protected:
4162 LValue &Result;
4163 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4164 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4165
4166 bool Success(APValue::LValueBase B) {
4167 Result.set(B);
4168 return true;
4169 }
4170
4171public:
4172 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4173 ExprEvaluatorBaseTy(Info), Result(Result) {}
4174
Richard Smith2e312c82012-03-03 22:46:17 +00004175 bool Success(const APValue &V, const Expr *E) {
4176 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004177 return true;
4178 }
Richard Smith027bf112011-11-17 22:56:20 +00004179
Richard Smith027bf112011-11-17 22:56:20 +00004180 bool VisitMemberExpr(const MemberExpr *E) {
4181 // Handle non-static data members.
4182 QualType BaseTy;
4183 if (E->isArrow()) {
4184 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4185 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004186 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004187 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004188 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004189 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4190 return false;
4191 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004192 } else {
4193 if (!this->Visit(E->getBase()))
4194 return false;
4195 BaseTy = E->getBase()->getType();
4196 }
Richard Smith027bf112011-11-17 22:56:20 +00004197
Richard Smith1b78b3d2012-01-25 22:15:11 +00004198 const ValueDecl *MD = E->getMemberDecl();
4199 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4200 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4201 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4202 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004203 if (!HandleLValueMember(this->Info, E, Result, FD))
4204 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004205 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004206 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4207 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004208 } else
4209 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004210
Richard Smith1b78b3d2012-01-25 22:15:11 +00004211 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004212 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004213 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004214 RefValue))
4215 return false;
4216 return Success(RefValue, E);
4217 }
4218 return true;
4219 }
4220
4221 bool VisitBinaryOperator(const BinaryOperator *E) {
4222 switch (E->getOpcode()) {
4223 default:
4224 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4225
4226 case BO_PtrMemD:
4227 case BO_PtrMemI:
4228 return HandleMemberPointerAccess(this->Info, E, Result);
4229 }
4230 }
4231
4232 bool VisitCastExpr(const CastExpr *E) {
4233 switch (E->getCastKind()) {
4234 default:
4235 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4236
4237 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004238 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004239 if (!this->Visit(E->getSubExpr()))
4240 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004241
4242 // Now figure out the necessary offset to add to the base LV to get from
4243 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004244 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4245 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004246 }
4247 }
4248};
4249}
4250
4251//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004252// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004253//
4254// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4255// function designators (in C), decl references to void objects (in C), and
4256// temporaries (if building with -Wno-address-of-temporary).
4257//
4258// LValue evaluation produces values comprising a base expression of one of the
4259// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004260// - Declarations
4261// * VarDecl
4262// * FunctionDecl
4263// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004264// * CompoundLiteralExpr in C
4265// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004266// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004267// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004268// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004269// * ObjCEncodeExpr
4270// * AddrLabelExpr
4271// * BlockExpr
4272// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004273// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004274// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004275// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004276// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4277// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004278// * A MaterializeTemporaryExpr that has static storage duration, with no
4279// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004280// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004281//===----------------------------------------------------------------------===//
4282namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004283class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004284 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004285public:
Richard Smith027bf112011-11-17 22:56:20 +00004286 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4287 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004288
Richard Smith11562c52011-10-28 17:51:58 +00004289 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004290 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004291
Peter Collingbournee9200682011-05-13 03:29:01 +00004292 bool VisitDeclRefExpr(const DeclRefExpr *E);
4293 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004294 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004295 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4296 bool VisitMemberExpr(const MemberExpr *E);
4297 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4298 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004299 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004300 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004301 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4302 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004303 bool VisitUnaryReal(const UnaryOperator *E);
4304 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004305 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4306 return VisitUnaryPreIncDec(UO);
4307 }
4308 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4309 return VisitUnaryPreIncDec(UO);
4310 }
Richard Smith3229b742013-05-05 21:17:10 +00004311 bool VisitBinAssign(const BinaryOperator *BO);
4312 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004313
Peter Collingbournee9200682011-05-13 03:29:01 +00004314 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004315 switch (E->getCastKind()) {
4316 default:
Richard Smith027bf112011-11-17 22:56:20 +00004317 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004318
Eli Friedmance3e02a2011-10-11 00:13:24 +00004319 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004320 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004321 if (!Visit(E->getSubExpr()))
4322 return false;
4323 Result.Designator.setInvalid();
4324 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004325
Richard Smith027bf112011-11-17 22:56:20 +00004326 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004327 if (!Visit(E->getSubExpr()))
4328 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004329 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004330 }
4331 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004332};
4333} // end anonymous namespace
4334
Richard Smith11562c52011-10-28 17:51:58 +00004335/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004336/// expressions which are not glvalues, in two cases:
4337/// * function designators in C, and
4338/// * "extern void" objects
4339static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4340 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4341 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004342 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004343}
4344
Peter Collingbournee9200682011-05-13 03:29:01 +00004345bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004346 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4347 return Success(FD);
4348 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004349 return VisitVarDecl(E, VD);
4350 return Error(E);
4351}
Richard Smith733237d2011-10-24 23:14:33 +00004352
Richard Smith11562c52011-10-28 17:51:58 +00004353bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004354 CallStackFrame *Frame = 0;
4355 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4356 Frame = Info.CurrentCall;
4357
Richard Smithfec09922011-11-01 16:57:24 +00004358 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004359 if (Frame) {
4360 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004361 return true;
4362 }
Richard Smithce40ad62011-11-12 22:28:03 +00004363 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004364 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004365
Richard Smith3229b742013-05-05 21:17:10 +00004366 APValue *V;
4367 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004368 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004369 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004370 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004371 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4372 return false;
4373 }
Richard Smith3229b742013-05-05 21:17:10 +00004374 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004375}
4376
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004377bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4378 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004379 // Walk through the expression to find the materialized temporary itself.
4380 SmallVector<const Expr *, 2> CommaLHSs;
4381 SmallVector<SubobjectAdjustment, 2> Adjustments;
4382 const Expr *Inner = E->GetTemporaryExpr()->
4383 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004384
Richard Smith84401042013-06-03 05:03:02 +00004385 // If we passed any comma operators, evaluate their LHSs.
4386 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4387 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4388 return false;
4389
Richard Smithe6c01442013-06-05 00:46:14 +00004390 // A materialized temporary with static storage duration can appear within the
4391 // result of a constant expression evaluation, so we need to preserve its
4392 // value for use outside this evaluation.
4393 APValue *Value;
4394 if (E->getStorageDuration() == SD_Static) {
4395 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004396 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004397 Result.set(E);
4398 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004399 Value = &Info.CurrentCall->
4400 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004401 Result.set(E, Info.CurrentCall->Index);
4402 }
4403
Richard Smithea4ad5d2013-06-06 08:19:16 +00004404 QualType Type = Inner->getType();
4405
Richard Smith84401042013-06-03 05:03:02 +00004406 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004407 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4408 (E->getStorageDuration() == SD_Static &&
4409 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4410 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004411 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004412 }
Richard Smith84401042013-06-03 05:03:02 +00004413
4414 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004415 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4416 --I;
4417 switch (Adjustments[I].Kind) {
4418 case SubobjectAdjustment::DerivedToBaseAdjustment:
4419 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4420 Type, Result))
4421 return false;
4422 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4423 break;
4424
4425 case SubobjectAdjustment::FieldAdjustment:
4426 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4427 return false;
4428 Type = Adjustments[I].Field->getType();
4429 break;
4430
4431 case SubobjectAdjustment::MemberPointerAdjustment:
4432 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4433 Adjustments[I].Ptr.RHS))
4434 return false;
4435 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4436 break;
4437 }
4438 }
4439
4440 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004441}
4442
Peter Collingbournee9200682011-05-13 03:29:01 +00004443bool
4444LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004445 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4446 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4447 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004448 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004449}
4450
Richard Smith6e525142011-12-27 12:18:28 +00004451bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004452 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004453 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004454
4455 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4456 << E->getExprOperand()->getType()
4457 << E->getExprOperand()->getSourceRange();
4458 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004459}
4460
Francois Pichet0066db92012-04-16 04:08:35 +00004461bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4462 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004463}
Francois Pichet0066db92012-04-16 04:08:35 +00004464
Peter Collingbournee9200682011-05-13 03:29:01 +00004465bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004466 // Handle static data members.
4467 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4468 VisitIgnoredValue(E->getBase());
4469 return VisitVarDecl(E, VD);
4470 }
4471
Richard Smith254a73d2011-10-28 22:34:42 +00004472 // Handle static member functions.
4473 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4474 if (MD->isStatic()) {
4475 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004476 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004477 }
4478 }
4479
Richard Smithd62306a2011-11-10 06:34:14 +00004480 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004481 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004482}
4483
Peter Collingbournee9200682011-05-13 03:29:01 +00004484bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004485 // FIXME: Deal with vectors as array subscript bases.
4486 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004487 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004488
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004489 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004490 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004491
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004492 APSInt Index;
4493 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004494 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004495
Richard Smith861b5b52013-05-07 23:34:45 +00004496 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4497 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004498}
Eli Friedman9a156e52008-11-12 09:44:48 +00004499
Peter Collingbournee9200682011-05-13 03:29:01 +00004500bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004501 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004502}
4503
Richard Smith66c96992012-02-18 22:04:06 +00004504bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4505 if (!Visit(E->getSubExpr()))
4506 return false;
4507 // __real is a no-op on scalar lvalues.
4508 if (E->getSubExpr()->getType()->isAnyComplexType())
4509 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4510 return true;
4511}
4512
4513bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4514 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4515 "lvalue __imag__ on scalar?");
4516 if (!Visit(E->getSubExpr()))
4517 return false;
4518 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4519 return true;
4520}
4521
Richard Smith243ef902013-05-05 23:31:59 +00004522bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4523 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004524 return Error(UO);
4525
4526 if (!this->Visit(UO->getSubExpr()))
4527 return false;
4528
Richard Smith243ef902013-05-05 23:31:59 +00004529 return handleIncDec(
4530 this->Info, UO, Result, UO->getSubExpr()->getType(),
4531 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004532}
4533
4534bool LValueExprEvaluator::VisitCompoundAssignOperator(
4535 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004536 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004537 return Error(CAO);
4538
Richard Smith3229b742013-05-05 21:17:10 +00004539 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004540
4541 // The overall lvalue result is the result of evaluating the LHS.
4542 if (!this->Visit(CAO->getLHS())) {
4543 if (Info.keepEvaluatingAfterFailure())
4544 Evaluate(RHS, this->Info, CAO->getRHS());
4545 return false;
4546 }
4547
Richard Smith3229b742013-05-05 21:17:10 +00004548 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4549 return false;
4550
Richard Smith43e77732013-05-07 04:50:00 +00004551 return handleCompoundAssignment(
4552 this->Info, CAO,
4553 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4554 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004555}
4556
4557bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004558 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4559 return Error(E);
4560
Richard Smith3229b742013-05-05 21:17:10 +00004561 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004562
4563 if (!this->Visit(E->getLHS())) {
4564 if (Info.keepEvaluatingAfterFailure())
4565 Evaluate(NewVal, this->Info, E->getRHS());
4566 return false;
4567 }
4568
Richard Smith3229b742013-05-05 21:17:10 +00004569 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4570 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004571
4572 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004573 NewVal);
4574}
4575
Eli Friedman9a156e52008-11-12 09:44:48 +00004576//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004577// Pointer Evaluation
4578//===----------------------------------------------------------------------===//
4579
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004580namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004581class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004582 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004583 LValue &Result;
4584
Peter Collingbournee9200682011-05-13 03:29:01 +00004585 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004586 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004587 return true;
4588 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004589public:
Mike Stump11289f42009-09-09 15:08:12 +00004590
John McCall45d55e42010-05-07 21:00:08 +00004591 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004592 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004593
Richard Smith2e312c82012-03-03 22:46:17 +00004594 bool Success(const APValue &V, const Expr *E) {
4595 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004596 return true;
4597 }
Richard Smithfddd3842011-12-30 21:15:51 +00004598 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004599 return Success((Expr*)0);
4600 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004601
John McCall45d55e42010-05-07 21:00:08 +00004602 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004603 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004604 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004605 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004606 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004607 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004608 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004609 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004610 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004611 bool VisitCallExpr(const CallExpr *E);
4612 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004613 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004614 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004616 }
Richard Smithd62306a2011-11-10 06:34:14 +00004617 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004618 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004619 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004620 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004621 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004623 Result = *Info.CurrentCall->This;
4624 return true;
4625 }
John McCallc07a0c72011-02-17 10:25:35 +00004626
Eli Friedman449fe542009-03-23 04:56:01 +00004627 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004628};
Chris Lattner05706e882008-07-11 18:11:29 +00004629} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004630
John McCall45d55e42010-05-07 21:00:08 +00004631static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004632 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004633 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004634}
4635
John McCall45d55e42010-05-07 21:00:08 +00004636bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004637 if (E->getOpcode() != BO_Add &&
4638 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004639 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004640
Chris Lattner05706e882008-07-11 18:11:29 +00004641 const Expr *PExp = E->getLHS();
4642 const Expr *IExp = E->getRHS();
4643 if (IExp->getType()->isPointerType())
4644 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004645
Richard Smith253c2a32012-01-27 01:14:48 +00004646 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4647 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004648 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004649
John McCall45d55e42010-05-07 21:00:08 +00004650 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004651 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004652 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004653
4654 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004655 if (E->getOpcode() == BO_Sub)
4656 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004657
Ted Kremenek28831752012-08-23 20:46:57 +00004658 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004659 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4660 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004661}
Eli Friedman9a156e52008-11-12 09:44:48 +00004662
John McCall45d55e42010-05-07 21:00:08 +00004663bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4664 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004665}
Mike Stump11289f42009-09-09 15:08:12 +00004666
Peter Collingbournee9200682011-05-13 03:29:01 +00004667bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4668 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004669
Eli Friedman847a2bc2009-12-27 05:43:15 +00004670 switch (E->getCastKind()) {
4671 default:
4672 break;
4673
John McCalle3027922010-08-25 11:45:40 +00004674 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004675 case CK_CPointerToObjCPointerCast:
4676 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004677 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004678 if (!Visit(SubExpr))
4679 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004680 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4681 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4682 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004683 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004684 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004685 if (SubExpr->getType()->isVoidPointerType())
4686 CCEDiag(E, diag::note_constexpr_invalid_cast)
4687 << 3 << SubExpr->getType();
4688 else
4689 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4690 }
Richard Smith96e0c102011-11-04 02:25:55 +00004691 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004692
Anders Carlsson18275092010-10-31 20:41:46 +00004693 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004694 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004695 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004696 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004697 if (!Result.Base && Result.Offset.isZero())
4698 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004699
Richard Smithd62306a2011-11-10 06:34:14 +00004700 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004701 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004702 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4703 castAs<PointerType>()->getPointeeType(),
4704 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004705
Richard Smith027bf112011-11-17 22:56:20 +00004706 case CK_BaseToDerived:
4707 if (!Visit(E->getSubExpr()))
4708 return false;
4709 if (!Result.Base && Result.Offset.isZero())
4710 return true;
4711 return HandleBaseToDerivedCast(Info, E, Result);
4712
Richard Smith0b0a0b62011-10-29 20:57:55 +00004713 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004714 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004715 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004716
John McCalle3027922010-08-25 11:45:40 +00004717 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004718 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4719
Richard Smith2e312c82012-03-03 22:46:17 +00004720 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004721 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004722 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004723
John McCall45d55e42010-05-07 21:00:08 +00004724 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004725 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4726 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004727 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004728 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004729 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004730 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004731 return true;
4732 } else {
4733 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004734 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004735 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004736 }
4737 }
John McCalle3027922010-08-25 11:45:40 +00004738 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004739 if (SubExpr->isGLValue()) {
4740 if (!EvaluateLValue(SubExpr, Result, Info))
4741 return false;
4742 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004743 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004744 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004745 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004746 return false;
4747 }
Richard Smith96e0c102011-11-04 02:25:55 +00004748 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004749 if (const ConstantArrayType *CAT
4750 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4751 Result.addArray(Info, E, CAT);
4752 else
4753 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004754 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004755
John McCalle3027922010-08-25 11:45:40 +00004756 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004757 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004758 }
4759
Richard Smith11562c52011-10-28 17:51:58 +00004760 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004761}
Chris Lattner05706e882008-07-11 18:11:29 +00004762
Peter Collingbournee9200682011-05-13 03:29:01 +00004763bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004764 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004765 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004766
Richard Smith6cbd65d2013-07-11 02:27:57 +00004767 switch (E->isBuiltinCall()) {
4768 case Builtin::BI__builtin_addressof:
4769 return EvaluateLValue(E->getArg(0), Result, Info);
4770
4771 default:
4772 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4773 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004774}
Chris Lattner05706e882008-07-11 18:11:29 +00004775
4776//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004777// Member Pointer Evaluation
4778//===----------------------------------------------------------------------===//
4779
4780namespace {
4781class MemberPointerExprEvaluator
4782 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4783 MemberPtr &Result;
4784
4785 bool Success(const ValueDecl *D) {
4786 Result = MemberPtr(D);
4787 return true;
4788 }
4789public:
4790
4791 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4792 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4793
Richard Smith2e312c82012-03-03 22:46:17 +00004794 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004795 Result.setFrom(V);
4796 return true;
4797 }
Richard Smithfddd3842011-12-30 21:15:51 +00004798 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004799 return Success((const ValueDecl*)0);
4800 }
4801
4802 bool VisitCastExpr(const CastExpr *E);
4803 bool VisitUnaryAddrOf(const UnaryOperator *E);
4804};
4805} // end anonymous namespace
4806
4807static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4808 EvalInfo &Info) {
4809 assert(E->isRValue() && E->getType()->isMemberPointerType());
4810 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4811}
4812
4813bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4814 switch (E->getCastKind()) {
4815 default:
4816 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4817
4818 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004819 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004820 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004821
4822 case CK_BaseToDerivedMemberPointer: {
4823 if (!Visit(E->getSubExpr()))
4824 return false;
4825 if (E->path_empty())
4826 return true;
4827 // Base-to-derived member pointer casts store the path in derived-to-base
4828 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4829 // the wrong end of the derived->base arc, so stagger the path by one class.
4830 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4831 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4832 PathI != PathE; ++PathI) {
4833 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4834 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4835 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004836 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004837 }
4838 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4839 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004840 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004841 return true;
4842 }
4843
4844 case CK_DerivedToBaseMemberPointer:
4845 if (!Visit(E->getSubExpr()))
4846 return false;
4847 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4848 PathE = E->path_end(); PathI != PathE; ++PathI) {
4849 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4850 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4851 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004852 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004853 }
4854 return true;
4855 }
4856}
4857
4858bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4859 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4860 // member can be formed.
4861 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4862}
4863
4864//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004865// Record Evaluation
4866//===----------------------------------------------------------------------===//
4867
4868namespace {
4869 class RecordExprEvaluator
4870 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4871 const LValue &This;
4872 APValue &Result;
4873 public:
4874
4875 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4876 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4877
Richard Smith2e312c82012-03-03 22:46:17 +00004878 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004879 Result = V;
4880 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004881 }
Richard Smithfddd3842011-12-30 21:15:51 +00004882 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004883
Richard Smithe97cbd72011-11-11 04:05:33 +00004884 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004885 bool VisitInitListExpr(const InitListExpr *E);
4886 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004887 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004888 };
4889}
4890
Richard Smithfddd3842011-12-30 21:15:51 +00004891/// Perform zero-initialization on an object of non-union class type.
4892/// C++11 [dcl.init]p5:
4893/// To zero-initialize an object or reference of type T means:
4894/// [...]
4895/// -- if T is a (possibly cv-qualified) non-union class type,
4896/// each non-static data member and each base-class subobject is
4897/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004898static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4899 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004900 const LValue &This, APValue &Result) {
4901 assert(!RD->isUnion() && "Expected non-union class type");
4902 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4903 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4904 std::distance(RD->field_begin(), RD->field_end()));
4905
John McCalld7bca762012-05-01 00:38:49 +00004906 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004907 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4908
4909 if (CD) {
4910 unsigned Index = 0;
4911 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004912 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004913 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4914 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004915 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4916 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004917 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004918 Result.getStructBase(Index)))
4919 return false;
4920 }
4921 }
4922
Richard Smitha8105bc2012-01-06 16:39:00 +00004923 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4924 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004925 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004926 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004927 continue;
4928
4929 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004930 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004931 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004932
David Blaikie2d7c57e2012-04-30 02:36:29 +00004933 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004934 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004935 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004936 return false;
4937 }
4938
4939 return true;
4940}
4941
4942bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4943 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004944 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004945 if (RD->isUnion()) {
4946 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4947 // object's first non-static named data member is zero-initialized
4948 RecordDecl::field_iterator I = RD->field_begin();
4949 if (I == RD->field_end()) {
4950 Result = APValue((const FieldDecl*)0);
4951 return true;
4952 }
4953
4954 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004955 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004956 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004957 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004958 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004959 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004960 }
4961
Richard Smith5d108602012-02-17 00:44:16 +00004962 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004963 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004964 return false;
4965 }
4966
Richard Smitha8105bc2012-01-06 16:39:00 +00004967 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004968}
4969
Richard Smithe97cbd72011-11-11 04:05:33 +00004970bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4971 switch (E->getCastKind()) {
4972 default:
4973 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4974
4975 case CK_ConstructorConversion:
4976 return Visit(E->getSubExpr());
4977
4978 case CK_DerivedToBase:
4979 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004980 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004981 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004982 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004983 if (!DerivedObject.isStruct())
4984 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004985
4986 // Derived-to-base rvalue conversion: just slice off the derived part.
4987 APValue *Value = &DerivedObject;
4988 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4989 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4990 PathE = E->path_end(); PathI != PathE; ++PathI) {
4991 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4992 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4993 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4994 RD = Base;
4995 }
4996 Result = *Value;
4997 return true;
4998 }
4999 }
5000}
5001
Richard Smithd62306a2011-11-10 06:34:14 +00005002bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5003 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005004 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005005 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5006
5007 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005008 const FieldDecl *Field = E->getInitializedFieldInUnion();
5009 Result = APValue(Field);
5010 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005011 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005012
5013 // If the initializer list for a union does not contain any elements, the
5014 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005015 // FIXME: The element should be initialized from an initializer list.
5016 // Is this difference ever observable for initializer lists which
5017 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005018 ImplicitValueInitExpr VIE(Field->getType());
5019 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5020
Richard Smithd62306a2011-11-10 06:34:14 +00005021 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005022 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5023 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005024
5025 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5026 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5027 isa<CXXDefaultInitExpr>(InitExpr));
5028
Richard Smithb228a862012-02-15 02:18:13 +00005029 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005030 }
5031
5032 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5033 "initializer list for class with base classes");
5034 Result = APValue(APValue::UninitStruct(), 0,
5035 std::distance(RD->field_begin(), RD->field_end()));
5036 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005037 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005038 for (RecordDecl::field_iterator Field = RD->field_begin(),
5039 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5040 // Anonymous bit-fields are not considered members of the class for
5041 // purposes of aggregate initialization.
5042 if (Field->isUnnamedBitfield())
5043 continue;
5044
5045 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005046
Richard Smith253c2a32012-01-27 01:14:48 +00005047 bool HaveInit = ElementNo < E->getNumInits();
5048
5049 // FIXME: Diagnostics here should point to the end of the initializer
5050 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005051 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00005052 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005053 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005054
5055 // Perform an implicit value-initialization for members beyond the end of
5056 // the initializer list.
5057 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005058 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005059
Richard Smith852c9db2013-04-20 22:23:05 +00005060 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5061 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5062 isa<CXXDefaultInitExpr>(Init));
5063
Richard Smith49ca8aa2013-08-06 07:09:20 +00005064 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5065 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5066 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5067 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005068 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005069 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005070 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005071 }
5072 }
5073
Richard Smith253c2a32012-01-27 01:14:48 +00005074 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005075}
5076
5077bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5078 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005079 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5080
Richard Smithfddd3842011-12-30 21:15:51 +00005081 bool ZeroInit = E->requiresZeroInitialization();
5082 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005083 // If we've already performed zero-initialization, we're already done.
5084 if (!Result.isUninit())
5085 return true;
5086
Richard Smithfddd3842011-12-30 21:15:51 +00005087 if (ZeroInit)
5088 return ZeroInitialization(E);
5089
Richard Smithcc36f692011-12-22 02:22:31 +00005090 const CXXRecordDecl *RD = FD->getParent();
5091 if (RD->isUnion())
5092 Result = APValue((FieldDecl*)0);
5093 else
5094 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5095 std::distance(RD->field_begin(), RD->field_end()));
5096 return true;
5097 }
5098
Richard Smithd62306a2011-11-10 06:34:14 +00005099 const FunctionDecl *Definition = 0;
5100 FD->getBody(Definition);
5101
Richard Smith357362d2011-12-13 06:39:58 +00005102 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5103 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005104
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005105 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005106 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005107 if (const MaterializeTemporaryExpr *ME
5108 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5109 return Visit(ME->GetTemporaryExpr());
5110
Richard Smithfddd3842011-12-30 21:15:51 +00005111 if (ZeroInit && !ZeroInitialization(E))
5112 return false;
5113
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005114 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005115 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005116 cast<CXXConstructorDecl>(Definition), Info,
5117 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005118}
5119
Richard Smithcc1b96d2013-06-12 22:31:48 +00005120bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5121 const CXXStdInitializerListExpr *E) {
5122 const ConstantArrayType *ArrayType =
5123 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5124
5125 LValue Array;
5126 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5127 return false;
5128
5129 // Get a pointer to the first element of the array.
5130 Array.addArray(Info, E, ArrayType);
5131
5132 // FIXME: Perform the checks on the field types in SemaInit.
5133 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5134 RecordDecl::field_iterator Field = Record->field_begin();
5135 if (Field == Record->field_end())
5136 return Error(E);
5137
5138 // Start pointer.
5139 if (!Field->getType()->isPointerType() ||
5140 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5141 ArrayType->getElementType()))
5142 return Error(E);
5143
5144 // FIXME: What if the initializer_list type has base classes, etc?
5145 Result = APValue(APValue::UninitStruct(), 0, 2);
5146 Array.moveInto(Result.getStructField(0));
5147
5148 if (++Field == Record->field_end())
5149 return Error(E);
5150
5151 if (Field->getType()->isPointerType() &&
5152 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5153 ArrayType->getElementType())) {
5154 // End pointer.
5155 if (!HandleLValueArrayAdjustment(Info, E, Array,
5156 ArrayType->getElementType(),
5157 ArrayType->getSize().getZExtValue()))
5158 return false;
5159 Array.moveInto(Result.getStructField(1));
5160 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5161 // Length.
5162 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5163 else
5164 return Error(E);
5165
5166 if (++Field != Record->field_end())
5167 return Error(E);
5168
5169 return true;
5170}
5171
Richard Smithd62306a2011-11-10 06:34:14 +00005172static bool EvaluateRecord(const Expr *E, const LValue &This,
5173 APValue &Result, EvalInfo &Info) {
5174 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005175 "can't evaluate expression as a record rvalue");
5176 return RecordExprEvaluator(Info, This, Result).Visit(E);
5177}
5178
5179//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005180// Temporary Evaluation
5181//
5182// Temporaries are represented in the AST as rvalues, but generally behave like
5183// lvalues. The full-object of which the temporary is a subobject is implicitly
5184// materialized so that a reference can bind to it.
5185//===----------------------------------------------------------------------===//
5186namespace {
5187class TemporaryExprEvaluator
5188 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5189public:
5190 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5191 LValueExprEvaluatorBaseTy(Info, Result) {}
5192
5193 /// Visit an expression which constructs the value of this temporary.
5194 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005195 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005196 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5197 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005198 }
5199
5200 bool VisitCastExpr(const CastExpr *E) {
5201 switch (E->getCastKind()) {
5202 default:
5203 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5204
5205 case CK_ConstructorConversion:
5206 return VisitConstructExpr(E->getSubExpr());
5207 }
5208 }
5209 bool VisitInitListExpr(const InitListExpr *E) {
5210 return VisitConstructExpr(E);
5211 }
5212 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5213 return VisitConstructExpr(E);
5214 }
5215 bool VisitCallExpr(const CallExpr *E) {
5216 return VisitConstructExpr(E);
5217 }
5218};
5219} // end anonymous namespace
5220
5221/// Evaluate an expression of record type as a temporary.
5222static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005223 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005224 return TemporaryExprEvaluator(Info, Result).Visit(E);
5225}
5226
5227//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005228// Vector Evaluation
5229//===----------------------------------------------------------------------===//
5230
5231namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005232 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005233 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5234 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005235 public:
Mike Stump11289f42009-09-09 15:08:12 +00005236
Richard Smith2d406342011-10-22 21:10:00 +00005237 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5238 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005239
Richard Smith2d406342011-10-22 21:10:00 +00005240 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5241 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5242 // FIXME: remove this APValue copy.
5243 Result = APValue(V.data(), V.size());
5244 return true;
5245 }
Richard Smith2e312c82012-03-03 22:46:17 +00005246 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005247 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005248 Result = V;
5249 return true;
5250 }
Richard Smithfddd3842011-12-30 21:15:51 +00005251 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005252
Richard Smith2d406342011-10-22 21:10:00 +00005253 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005254 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005255 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005256 bool VisitInitListExpr(const InitListExpr *E);
5257 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005258 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005259 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005260 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005261 };
5262} // end anonymous namespace
5263
5264static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005265 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005266 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005267}
5268
Richard Smith2d406342011-10-22 21:10:00 +00005269bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5270 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005271 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005272
Richard Smith161f09a2011-12-06 22:44:34 +00005273 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005274 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005275
Eli Friedmanc757de22011-03-25 00:43:55 +00005276 switch (E->getCastKind()) {
5277 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005278 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005279 if (SETy->isIntegerType()) {
5280 APSInt IntResult;
5281 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005282 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005283 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005284 } else if (SETy->isRealFloatingType()) {
5285 APFloat F(0.0);
5286 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005287 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005288 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005289 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005290 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005291 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005292
5293 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005294 SmallVector<APValue, 4> Elts(NElts, Val);
5295 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005296 }
Eli Friedman803acb32011-12-22 03:51:45 +00005297 case CK_BitCast: {
5298 // Evaluate the operand into an APInt we can extract from.
5299 llvm::APInt SValInt;
5300 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5301 return false;
5302 // Extract the elements
5303 QualType EltTy = VTy->getElementType();
5304 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5305 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5306 SmallVector<APValue, 4> Elts;
5307 if (EltTy->isRealFloatingType()) {
5308 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005309 unsigned FloatEltSize = EltSize;
5310 if (&Sem == &APFloat::x87DoubleExtended)
5311 FloatEltSize = 80;
5312 for (unsigned i = 0; i < NElts; i++) {
5313 llvm::APInt Elt;
5314 if (BigEndian)
5315 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5316 else
5317 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005318 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005319 }
5320 } else if (EltTy->isIntegerType()) {
5321 for (unsigned i = 0; i < NElts; i++) {
5322 llvm::APInt Elt;
5323 if (BigEndian)
5324 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5325 else
5326 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5327 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5328 }
5329 } else {
5330 return Error(E);
5331 }
5332 return Success(Elts, E);
5333 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005334 default:
Richard Smith11562c52011-10-28 17:51:58 +00005335 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005336 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005337}
5338
Richard Smith2d406342011-10-22 21:10:00 +00005339bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005340VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005341 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005342 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005343 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005344
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005345 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005346 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005347
Eli Friedmanb9c71292012-01-03 23:24:20 +00005348 // The number of initializers can be less than the number of
5349 // vector elements. For OpenCL, this can be due to nested vector
5350 // initialization. For GCC compatibility, missing trailing elements
5351 // should be initialized with zeroes.
5352 unsigned CountInits = 0, CountElts = 0;
5353 while (CountElts < NumElements) {
5354 // Handle nested vector initialization.
5355 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005356 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005357 APValue v;
5358 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5359 return Error(E);
5360 unsigned vlen = v.getVectorLength();
5361 for (unsigned j = 0; j < vlen; j++)
5362 Elements.push_back(v.getVectorElt(j));
5363 CountElts += vlen;
5364 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005365 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005366 if (CountInits < NumInits) {
5367 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005368 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005369 } else // trailing integer zero.
5370 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5371 Elements.push_back(APValue(sInt));
5372 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005373 } else {
5374 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005375 if (CountInits < NumInits) {
5376 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005377 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005378 } else // trailing float zero.
5379 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5380 Elements.push_back(APValue(f));
5381 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005382 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005383 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005384 }
Richard Smith2d406342011-10-22 21:10:00 +00005385 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005386}
5387
Richard Smith2d406342011-10-22 21:10:00 +00005388bool
Richard Smithfddd3842011-12-30 21:15:51 +00005389VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005390 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005391 QualType EltTy = VT->getElementType();
5392 APValue ZeroElement;
5393 if (EltTy->isIntegerType())
5394 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5395 else
5396 ZeroElement =
5397 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005399 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005400 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005401}
5402
Richard Smith2d406342011-10-22 21:10:00 +00005403bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005404 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005405 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005406}
5407
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005408//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005409// Array Evaluation
5410//===----------------------------------------------------------------------===//
5411
5412namespace {
5413 class ArrayExprEvaluator
5414 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005415 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005416 APValue &Result;
5417 public:
5418
Richard Smithd62306a2011-11-10 06:34:14 +00005419 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5420 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005421
5422 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005423 assert((V.isArray() || V.isLValue()) &&
5424 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005425 Result = V;
5426 return true;
5427 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005428
Richard Smithfddd3842011-12-30 21:15:51 +00005429 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005430 const ConstantArrayType *CAT =
5431 Info.Ctx.getAsConstantArrayType(E->getType());
5432 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005433 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005434
5435 Result = APValue(APValue::UninitArray(), 0,
5436 CAT->getSize().getZExtValue());
5437 if (!Result.hasArrayFiller()) return true;
5438
Richard Smithfddd3842011-12-30 21:15:51 +00005439 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005440 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005441 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005442 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005443 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005444 }
5445
Richard Smithf3e9e432011-11-07 09:22:26 +00005446 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005447 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005448 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5449 const LValue &Subobject,
5450 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005451 };
5452} // end anonymous namespace
5453
Richard Smithd62306a2011-11-10 06:34:14 +00005454static bool EvaluateArray(const Expr *E, const LValue &This,
5455 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005456 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005457 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005458}
5459
5460bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5461 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5462 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005463 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005464
Richard Smithca2cfbf2011-12-22 01:07:19 +00005465 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5466 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005467 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005468 LValue LV;
5469 if (!EvaluateLValue(E->getInit(0), LV, Info))
5470 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005471 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005472 LV.moveInto(Val);
5473 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005474 }
5475
Richard Smith253c2a32012-01-27 01:14:48 +00005476 bool Success = true;
5477
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005478 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5479 "zero-initialized array shouldn't have any initialized elts");
5480 APValue Filler;
5481 if (Result.isArray() && Result.hasArrayFiller())
5482 Filler = Result.getArrayFiller();
5483
Richard Smith9543c5e2013-04-22 14:44:29 +00005484 unsigned NumEltsToInit = E->getNumInits();
5485 unsigned NumElts = CAT->getSize().getZExtValue();
5486 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5487
5488 // If the initializer might depend on the array index, run it for each
5489 // array element. For now, just whitelist non-class value-initialization.
5490 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5491 NumEltsToInit = NumElts;
5492
5493 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005494
5495 // If the array was previously zero-initialized, preserve the
5496 // zero-initialized values.
5497 if (!Filler.isUninit()) {
5498 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5499 Result.getArrayInitializedElt(I) = Filler;
5500 if (Result.hasArrayFiller())
5501 Result.getArrayFiller() = Filler;
5502 }
5503
Richard Smithd62306a2011-11-10 06:34:14 +00005504 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005505 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005506 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5507 const Expr *Init =
5508 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005509 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005510 Info, Subobject, Init) ||
5511 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005512 CAT->getElementType(), 1)) {
5513 if (!Info.keepEvaluatingAfterFailure())
5514 return false;
5515 Success = false;
5516 }
Richard Smithd62306a2011-11-10 06:34:14 +00005517 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005518
Richard Smith9543c5e2013-04-22 14:44:29 +00005519 if (!Result.hasArrayFiller())
5520 return Success;
5521
5522 // If we get here, we have a trivial filler, which we can just evaluate
5523 // once and splat over the rest of the array elements.
5524 assert(FillerExpr && "no array filler for incomplete init list");
5525 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5526 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005527}
5528
Richard Smith027bf112011-11-17 22:56:20 +00005529bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005530 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5531}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005532
Richard Smith9543c5e2013-04-22 14:44:29 +00005533bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5534 const LValue &Subobject,
5535 APValue *Value,
5536 QualType Type) {
5537 bool HadZeroInit = !Value->isUninit();
5538
5539 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5540 unsigned N = CAT->getSize().getZExtValue();
5541
5542 // Preserve the array filler if we had prior zero-initialization.
5543 APValue Filler =
5544 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5545 : APValue();
5546
5547 *Value = APValue(APValue::UninitArray(), N, N);
5548
5549 if (HadZeroInit)
5550 for (unsigned I = 0; I != N; ++I)
5551 Value->getArrayInitializedElt(I) = Filler;
5552
5553 // Initialize the elements.
5554 LValue ArrayElt = Subobject;
5555 ArrayElt.addArray(Info, E, CAT);
5556 for (unsigned I = 0; I != N; ++I)
5557 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5558 CAT->getElementType()) ||
5559 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5560 CAT->getElementType(), 1))
5561 return false;
5562
5563 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005564 }
Richard Smith027bf112011-11-17 22:56:20 +00005565
Richard Smith9543c5e2013-04-22 14:44:29 +00005566 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005567 return Error(E);
5568
Richard Smith027bf112011-11-17 22:56:20 +00005569 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005570
Richard Smithfddd3842011-12-30 21:15:51 +00005571 bool ZeroInit = E->requiresZeroInitialization();
5572 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005573 if (HadZeroInit)
5574 return true;
5575
Richard Smithfddd3842011-12-30 21:15:51 +00005576 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005577 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005578 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005579 }
5580
Richard Smithcc36f692011-12-22 02:22:31 +00005581 const CXXRecordDecl *RD = FD->getParent();
5582 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005583 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005584 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005585 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005586 APValue(APValue::UninitStruct(), RD->getNumBases(),
5587 std::distance(RD->field_begin(), RD->field_end()));
5588 return true;
5589 }
5590
Richard Smith027bf112011-11-17 22:56:20 +00005591 const FunctionDecl *Definition = 0;
5592 FD->getBody(Definition);
5593
Richard Smith357362d2011-12-13 06:39:58 +00005594 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5595 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005596
Richard Smith9eae7232012-01-12 18:54:33 +00005597 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005598 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005599 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005600 return false;
5601 }
5602
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005603 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005604 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005605 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005606 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005607}
5608
Richard Smithf3e9e432011-11-07 09:22:26 +00005609//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005610// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005611//
5612// As a GNU extension, we support casting pointers to sufficiently-wide integer
5613// types and back in constant folding. Integer values are thus represented
5614// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005615//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005616
5617namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005618class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005619 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005620 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005621public:
Richard Smith2e312c82012-03-03 22:46:17 +00005622 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005623 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005624
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005625 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005626 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005627 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005628 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005629 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005630 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005631 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005632 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005633 return true;
5634 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005635 bool Success(const llvm::APSInt &SI, const Expr *E) {
5636 return Success(SI, E, Result);
5637 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005638
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005639 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005640 assert(E->getType()->isIntegralOrEnumerationType() &&
5641 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005642 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005643 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005644 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005645 Result.getInt().setIsUnsigned(
5646 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005647 return true;
5648 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005649 bool Success(const llvm::APInt &I, const Expr *E) {
5650 return Success(I, E, Result);
5651 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005652
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005653 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005654 assert(E->getType()->isIntegralOrEnumerationType() &&
5655 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005656 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005657 return true;
5658 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005659 bool Success(uint64_t Value, const Expr *E) {
5660 return Success(Value, E, Result);
5661 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005662
Ken Dyckdbc01912011-03-11 02:13:43 +00005663 bool Success(CharUnits Size, const Expr *E) {
5664 return Success(Size.getQuantity(), E);
5665 }
5666
Richard Smith2e312c82012-03-03 22:46:17 +00005667 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005668 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005669 Result = V;
5670 return true;
5671 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005672 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005673 }
Mike Stump11289f42009-09-09 15:08:12 +00005674
Richard Smithfddd3842011-12-30 21:15:51 +00005675 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005676
Peter Collingbournee9200682011-05-13 03:29:01 +00005677 //===--------------------------------------------------------------------===//
5678 // Visitor Methods
5679 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005680
Chris Lattner7174bf32008-07-12 00:38:25 +00005681 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005682 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005683 }
5684 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005685 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005686 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005687
5688 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5689 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005690 if (CheckReferencedDecl(E, E->getDecl()))
5691 return true;
5692
5693 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005694 }
5695 bool VisitMemberExpr(const MemberExpr *E) {
5696 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005697 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005698 return true;
5699 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005700
5701 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005702 }
5703
Peter Collingbournee9200682011-05-13 03:29:01 +00005704 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005705 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005706 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005707 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005708
Peter Collingbournee9200682011-05-13 03:29:01 +00005709 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005710 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005711
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005712 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005713 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005714 }
Mike Stump11289f42009-09-09 15:08:12 +00005715
Ted Kremeneke65b0862012-03-06 20:05:56 +00005716 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5717 return Success(E->getValue(), E);
5718 }
5719
Richard Smith4ce706a2011-10-11 21:43:33 +00005720 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005721 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005722 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005723 }
5724
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005725 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005726 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005727 }
5728
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005729 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5730 return Success(E->getValue(), E);
5731 }
5732
Douglas Gregor29c42f22012-02-24 07:38:34 +00005733 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5734 return Success(E->getValue(), E);
5735 }
5736
John Wiegley6242b6a2011-04-28 00:16:57 +00005737 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5738 return Success(E->getValue(), E);
5739 }
5740
John Wiegleyf9f65842011-04-25 06:54:41 +00005741 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5742 return Success(E->getValue(), E);
5743 }
5744
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005745 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005746 bool VisitUnaryImag(const UnaryOperator *E);
5747
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005748 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005749 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005750
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005751private:
Ken Dyck160146e2010-01-27 17:10:57 +00005752 CharUnits GetAlignOfExpr(const Expr *E);
5753 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005754 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005755 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005756 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005757};
Chris Lattner05706e882008-07-11 18:11:29 +00005758} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005759
Richard Smith11562c52011-10-28 17:51:58 +00005760/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5761/// produce either the integer value or a pointer.
5762///
5763/// GCC has a heinous extension which folds casts between pointer types and
5764/// pointer-sized integral types. We support this by allowing the evaluation of
5765/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5766/// Some simple arithmetic on such values is supported (they are treated much
5767/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005768static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005769 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005770 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005771 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005772}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005773
Richard Smithf57d8cb2011-12-09 22:58:01 +00005774static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005775 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005776 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005777 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005778 if (!Val.isInt()) {
5779 // FIXME: It would be better to produce the diagnostic for casting
5780 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005781 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005782 return false;
5783 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005784 Result = Val.getInt();
5785 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005786}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005787
Richard Smithf57d8cb2011-12-09 22:58:01 +00005788/// Check whether the given declaration can be directly converted to an integral
5789/// rvalue. If not, no diagnostic is produced; there are other things we can
5790/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005791bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005792 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005793 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005794 // Check for signedness/width mismatches between E type and ECD value.
5795 bool SameSign = (ECD->getInitVal().isSigned()
5796 == E->getType()->isSignedIntegerOrEnumerationType());
5797 bool SameWidth = (ECD->getInitVal().getBitWidth()
5798 == Info.Ctx.getIntWidth(E->getType()));
5799 if (SameSign && SameWidth)
5800 return Success(ECD->getInitVal(), E);
5801 else {
5802 // Get rid of mismatch (otherwise Success assertions will fail)
5803 // by computing a new value matching the type of E.
5804 llvm::APSInt Val = ECD->getInitVal();
5805 if (!SameSign)
5806 Val.setIsSigned(!ECD->getInitVal().isSigned());
5807 if (!SameWidth)
5808 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5809 return Success(Val, E);
5810 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005811 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005812 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005813}
5814
Chris Lattner86ee2862008-10-06 06:40:35 +00005815/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5816/// as GCC.
5817static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5818 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005819 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005820 enum gcc_type_class {
5821 no_type_class = -1,
5822 void_type_class, integer_type_class, char_type_class,
5823 enumeral_type_class, boolean_type_class,
5824 pointer_type_class, reference_type_class, offset_type_class,
5825 real_type_class, complex_type_class,
5826 function_type_class, method_type_class,
5827 record_type_class, union_type_class,
5828 array_type_class, string_type_class,
5829 lang_type_class
5830 };
Mike Stump11289f42009-09-09 15:08:12 +00005831
5832 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005833 // ideal, however it is what gcc does.
5834 if (E->getNumArgs() == 0)
5835 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005836
Chris Lattner86ee2862008-10-06 06:40:35 +00005837 QualType ArgTy = E->getArg(0)->getType();
5838 if (ArgTy->isVoidType())
5839 return void_type_class;
5840 else if (ArgTy->isEnumeralType())
5841 return enumeral_type_class;
5842 else if (ArgTy->isBooleanType())
5843 return boolean_type_class;
5844 else if (ArgTy->isCharType())
5845 return string_type_class; // gcc doesn't appear to use char_type_class
5846 else if (ArgTy->isIntegerType())
5847 return integer_type_class;
5848 else if (ArgTy->isPointerType())
5849 return pointer_type_class;
5850 else if (ArgTy->isReferenceType())
5851 return reference_type_class;
5852 else if (ArgTy->isRealType())
5853 return real_type_class;
5854 else if (ArgTy->isComplexType())
5855 return complex_type_class;
5856 else if (ArgTy->isFunctionType())
5857 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005858 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005859 return record_type_class;
5860 else if (ArgTy->isUnionType())
5861 return union_type_class;
5862 else if (ArgTy->isArrayType())
5863 return array_type_class;
5864 else if (ArgTy->isUnionType())
5865 return union_type_class;
5866 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005867 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005868}
5869
Richard Smith5fab0c92011-12-28 19:48:30 +00005870/// EvaluateBuiltinConstantPForLValue - Determine the result of
5871/// __builtin_constant_p when applied to the given lvalue.
5872///
5873/// An lvalue is only "constant" if it is a pointer or reference to the first
5874/// character of a string literal.
5875template<typename LValue>
5876static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005877 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005878 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5879}
5880
5881/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5882/// GCC as we can manage.
5883static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5884 QualType ArgType = Arg->getType();
5885
5886 // __builtin_constant_p always has one operand. The rules which gcc follows
5887 // are not precisely documented, but are as follows:
5888 //
5889 // - If the operand is of integral, floating, complex or enumeration type,
5890 // and can be folded to a known value of that type, it returns 1.
5891 // - If the operand and can be folded to a pointer to the first character
5892 // of a string literal (or such a pointer cast to an integral type), it
5893 // returns 1.
5894 //
5895 // Otherwise, it returns 0.
5896 //
5897 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5898 // its support for this does not currently work.
5899 if (ArgType->isIntegralOrEnumerationType()) {
5900 Expr::EvalResult Result;
5901 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5902 return false;
5903
5904 APValue &V = Result.Val;
5905 if (V.getKind() == APValue::Int)
5906 return true;
5907
5908 return EvaluateBuiltinConstantPForLValue(V);
5909 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5910 return Arg->isEvaluatable(Ctx);
5911 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5912 LValue LV;
5913 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00005914 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00005915 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5916 : EvaluatePointer(Arg, LV, Info)) &&
5917 !Status.HasSideEffects)
5918 return EvaluateBuiltinConstantPForLValue(LV);
5919 }
5920
5921 // Anything else isn't considered to be sufficiently constant.
5922 return false;
5923}
5924
John McCall95007602010-05-10 23:27:23 +00005925/// Retrieves the "underlying object type" of the given expression,
5926/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005927QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5928 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5929 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005930 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005931 } else if (const Expr *E = B.get<const Expr*>()) {
5932 if (isa<CompoundLiteralExpr>(E))
5933 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005934 }
5935
5936 return QualType();
5937}
5938
Peter Collingbournee9200682011-05-13 03:29:01 +00005939bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005940 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005941
5942 {
5943 // The operand of __builtin_object_size is never evaluated for side-effects.
5944 // If there are any, but we can determine the pointed-to object anyway, then
5945 // ignore the side-effects.
5946 SpeculativeEvaluationRAII SpeculativeEval(Info);
5947 if (!EvaluatePointer(E->getArg(0), Base, Info))
5948 return false;
5949 }
John McCall95007602010-05-10 23:27:23 +00005950
5951 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005952 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005953
Richard Smithce40ad62011-11-12 22:28:03 +00005954 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005955 if (T.isNull() ||
5956 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005957 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005958 T->isVariablyModifiedType() ||
5959 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005960 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005961
5962 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5963 CharUnits Offset = Base.getLValueOffset();
5964
5965 if (!Offset.isNegative() && Offset <= Size)
5966 Size -= Offset;
5967 else
5968 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005969 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005970}
5971
Peter Collingbournee9200682011-05-13 03:29:01 +00005972bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005973 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005974 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005975 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005976
5977 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005978 if (TryEvaluateBuiltinObjectSize(E))
5979 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005980
Richard Smith0421ce72012-08-07 04:16:51 +00005981 // If evaluating the argument has side-effects, we can't determine the size
5982 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5983 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005984 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005985 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005986 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005987 return Success(0, E);
5988 }
Mike Stump876387b2009-10-27 22:09:17 +00005989
Richard Smith01ade172012-05-23 04:13:20 +00005990 // Expression had no side effects, but we couldn't statically determine the
5991 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005992 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005993 }
5994
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005995 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005996 case Builtin::BI__builtin_bswap32:
5997 case Builtin::BI__builtin_bswap64: {
5998 APSInt Val;
5999 if (!EvaluateInteger(E->getArg(0), Val, Info))
6000 return false;
6001
6002 return Success(Val.byteSwap(), E);
6003 }
6004
Richard Smith8889a3d2013-06-13 06:26:32 +00006005 case Builtin::BI__builtin_classify_type:
6006 return Success(EvaluateBuiltinClassifyType(E), E);
6007
6008 // FIXME: BI__builtin_clrsb
6009 // FIXME: BI__builtin_clrsbl
6010 // FIXME: BI__builtin_clrsbll
6011
Richard Smith80b3c8e2013-06-13 05:04:16 +00006012 case Builtin::BI__builtin_clz:
6013 case Builtin::BI__builtin_clzl:
6014 case Builtin::BI__builtin_clzll: {
6015 APSInt Val;
6016 if (!EvaluateInteger(E->getArg(0), Val, Info))
6017 return false;
6018 if (!Val)
6019 return Error(E);
6020
6021 return Success(Val.countLeadingZeros(), E);
6022 }
6023
Richard Smith8889a3d2013-06-13 06:26:32 +00006024 case Builtin::BI__builtin_constant_p:
6025 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6026
Richard Smith80b3c8e2013-06-13 05:04:16 +00006027 case Builtin::BI__builtin_ctz:
6028 case Builtin::BI__builtin_ctzl:
6029 case Builtin::BI__builtin_ctzll: {
6030 APSInt Val;
6031 if (!EvaluateInteger(E->getArg(0), Val, Info))
6032 return false;
6033 if (!Val)
6034 return Error(E);
6035
6036 return Success(Val.countTrailingZeros(), E);
6037 }
6038
Richard Smith8889a3d2013-06-13 06:26:32 +00006039 case Builtin::BI__builtin_eh_return_data_regno: {
6040 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6041 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6042 return Success(Operand, E);
6043 }
6044
6045 case Builtin::BI__builtin_expect:
6046 return Visit(E->getArg(0));
6047
6048 case Builtin::BI__builtin_ffs:
6049 case Builtin::BI__builtin_ffsl:
6050 case Builtin::BI__builtin_ffsll: {
6051 APSInt Val;
6052 if (!EvaluateInteger(E->getArg(0), Val, Info))
6053 return false;
6054
6055 unsigned N = Val.countTrailingZeros();
6056 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6057 }
6058
6059 case Builtin::BI__builtin_fpclassify: {
6060 APFloat Val(0.0);
6061 if (!EvaluateFloat(E->getArg(5), Val, Info))
6062 return false;
6063 unsigned Arg;
6064 switch (Val.getCategory()) {
6065 case APFloat::fcNaN: Arg = 0; break;
6066 case APFloat::fcInfinity: Arg = 1; break;
6067 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6068 case APFloat::fcZero: Arg = 4; break;
6069 }
6070 return Visit(E->getArg(Arg));
6071 }
6072
6073 case Builtin::BI__builtin_isinf_sign: {
6074 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006075 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006076 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6077 }
6078
Richard Smithea3019d2013-10-15 19:07:14 +00006079 case Builtin::BI__builtin_isinf: {
6080 APFloat Val(0.0);
6081 return EvaluateFloat(E->getArg(0), Val, Info) &&
6082 Success(Val.isInfinity() ? 1 : 0, E);
6083 }
6084
6085 case Builtin::BI__builtin_isfinite: {
6086 APFloat Val(0.0);
6087 return EvaluateFloat(E->getArg(0), Val, Info) &&
6088 Success(Val.isFinite() ? 1 : 0, E);
6089 }
6090
6091 case Builtin::BI__builtin_isnan: {
6092 APFloat Val(0.0);
6093 return EvaluateFloat(E->getArg(0), Val, Info) &&
6094 Success(Val.isNaN() ? 1 : 0, E);
6095 }
6096
6097 case Builtin::BI__builtin_isnormal: {
6098 APFloat Val(0.0);
6099 return EvaluateFloat(E->getArg(0), Val, Info) &&
6100 Success(Val.isNormal() ? 1 : 0, E);
6101 }
6102
Richard Smith8889a3d2013-06-13 06:26:32 +00006103 case Builtin::BI__builtin_parity:
6104 case Builtin::BI__builtin_parityl:
6105 case Builtin::BI__builtin_parityll: {
6106 APSInt Val;
6107 if (!EvaluateInteger(E->getArg(0), Val, Info))
6108 return false;
6109
6110 return Success(Val.countPopulation() % 2, E);
6111 }
6112
Richard Smith80b3c8e2013-06-13 05:04:16 +00006113 case Builtin::BI__builtin_popcount:
6114 case Builtin::BI__builtin_popcountl:
6115 case Builtin::BI__builtin_popcountll: {
6116 APSInt Val;
6117 if (!EvaluateInteger(E->getArg(0), Val, Info))
6118 return false;
6119
6120 return Success(Val.countPopulation(), E);
6121 }
6122
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006123 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006124 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006125 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006126 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006127 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6128 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006129 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006130 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006131 case Builtin::BI__builtin_strlen:
6132 // As an extension, we support strlen() and __builtin_strlen() as constant
6133 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00006134 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006135 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6136 // The string literal may have embedded null characters. Find the first
6137 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006138 StringRef Str = S->getString();
6139 StringRef::size_type Pos = Str.find(0);
6140 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006141 Str = Str.substr(0, Pos);
6142
6143 return Success(Str.size(), E);
6144 }
6145
Richard Smithf57d8cb2011-12-09 22:58:01 +00006146 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006147
Richard Smith01ba47d2012-04-13 00:45:38 +00006148 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006149 case Builtin::BI__atomic_is_lock_free:
6150 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006151 APSInt SizeVal;
6152 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6153 return false;
6154
6155 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6156 // of two less than the maximum inline atomic width, we know it is
6157 // lock-free. If the size isn't a power of two, or greater than the
6158 // maximum alignment where we promote atomics, we know it is not lock-free
6159 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6160 // the answer can only be determined at runtime; for example, 16-byte
6161 // atomics have lock-free implementations on some, but not all,
6162 // x86-64 processors.
6163
6164 // Check power-of-two.
6165 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006166 if (Size.isPowerOfTwo()) {
6167 // Check against inlining width.
6168 unsigned InlineWidthBits =
6169 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6170 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6171 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6172 Size == CharUnits::One() ||
6173 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6174 Expr::NPC_NeverValueDependent))
6175 // OK, we will inline appropriately-aligned operations of this size,
6176 // and _Atomic(T) is appropriately-aligned.
6177 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006178
Richard Smith01ba47d2012-04-13 00:45:38 +00006179 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6180 castAs<PointerType>()->getPointeeType();
6181 if (!PointeeType->isIncompleteType() &&
6182 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6183 // OK, we will inline operations on this object.
6184 return Success(1, E);
6185 }
6186 }
6187 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006188
Richard Smith01ba47d2012-04-13 00:45:38 +00006189 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6190 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006191 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006192 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006193}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006194
Richard Smith8b3497e2011-10-31 01:37:14 +00006195static bool HasSameBase(const LValue &A, const LValue &B) {
6196 if (!A.getLValueBase())
6197 return !B.getLValueBase();
6198 if (!B.getLValueBase())
6199 return false;
6200
Richard Smithce40ad62011-11-12 22:28:03 +00006201 if (A.getLValueBase().getOpaqueValue() !=
6202 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006203 const Decl *ADecl = GetLValueBaseDecl(A);
6204 if (!ADecl)
6205 return false;
6206 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006207 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006208 return false;
6209 }
6210
6211 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006212 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006213}
6214
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006215namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006216
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006217/// \brief Data recursive integer evaluator of certain binary operators.
6218///
6219/// We use a data recursive algorithm for binary operators so that we are able
6220/// to handle extreme cases of chained binary operators without causing stack
6221/// overflow.
6222class DataRecursiveIntBinOpEvaluator {
6223 struct EvalResult {
6224 APValue Val;
6225 bool Failed;
6226
6227 EvalResult() : Failed(false) { }
6228
6229 void swap(EvalResult &RHS) {
6230 Val.swap(RHS.Val);
6231 Failed = RHS.Failed;
6232 RHS.Failed = false;
6233 }
6234 };
6235
6236 struct Job {
6237 const Expr *E;
6238 EvalResult LHSResult; // meaningful only for binary operator expression.
6239 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6240
6241 Job() : StoredInfo(0) { }
6242 void startSpeculativeEval(EvalInfo &Info) {
6243 OldEvalStatus = Info.EvalStatus;
6244 Info.EvalStatus.Diag = 0;
6245 StoredInfo = &Info;
6246 }
6247 ~Job() {
6248 if (StoredInfo) {
6249 StoredInfo->EvalStatus = OldEvalStatus;
6250 }
6251 }
6252 private:
6253 EvalInfo *StoredInfo; // non-null if status changed.
6254 Expr::EvalStatus OldEvalStatus;
6255 };
6256
6257 SmallVector<Job, 16> Queue;
6258
6259 IntExprEvaluator &IntEval;
6260 EvalInfo &Info;
6261 APValue &FinalResult;
6262
6263public:
6264 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6265 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6266
6267 /// \brief True if \param E is a binary operator that we are going to handle
6268 /// data recursively.
6269 /// We handle binary operators that are comma, logical, or that have operands
6270 /// with integral or enumeration type.
6271 static bool shouldEnqueue(const BinaryOperator *E) {
6272 return E->getOpcode() == BO_Comma ||
6273 E->isLogicalOp() ||
6274 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6275 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006276 }
6277
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006278 bool Traverse(const BinaryOperator *E) {
6279 enqueue(E);
6280 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006281 while (!Queue.empty())
6282 process(PrevResult);
6283
6284 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006285
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006286 FinalResult.swap(PrevResult.Val);
6287 return true;
6288 }
6289
6290private:
6291 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6292 return IntEval.Success(Value, E, Result);
6293 }
6294 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6295 return IntEval.Success(Value, E, Result);
6296 }
6297 bool Error(const Expr *E) {
6298 return IntEval.Error(E);
6299 }
6300 bool Error(const Expr *E, diag::kind D) {
6301 return IntEval.Error(E, D);
6302 }
6303
6304 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6305 return Info.CCEDiag(E, D);
6306 }
6307
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006308 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6309 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006310 bool &SuppressRHSDiags);
6311
6312 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6313 const BinaryOperator *E, APValue &Result);
6314
6315 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6316 Result.Failed = !Evaluate(Result.Val, Info, E);
6317 if (Result.Failed)
6318 Result.Val = APValue();
6319 }
6320
Richard Trieuba4d0872012-03-21 23:30:30 +00006321 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006322
6323 void enqueue(const Expr *E) {
6324 E = E->IgnoreParens();
6325 Queue.resize(Queue.size()+1);
6326 Queue.back().E = E;
6327 Queue.back().Kind = Job::AnyExprKind;
6328 }
6329};
6330
6331}
6332
6333bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006334 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006335 bool &SuppressRHSDiags) {
6336 if (E->getOpcode() == BO_Comma) {
6337 // Ignore LHS but note if we could not evaluate it.
6338 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006339 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006340 return true;
6341 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006342
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006343 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006344 bool LHSAsBool;
6345 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006346 // We were able to evaluate the LHS, see if we can get away with not
6347 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006348 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6349 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006350 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006351 }
6352 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006353 LHSResult.Failed = true;
6354
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006355 // Since we weren't able to evaluate the left hand side, it
6356 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006357 if (!Info.noteSideEffect())
6358 return false;
6359
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006360 // We can't evaluate the LHS; however, sometimes the result
6361 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6362 // Don't ignore RHS and suppress diagnostics from this arm.
6363 SuppressRHSDiags = true;
6364 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006365
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006366 return true;
6367 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006368
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006369 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6370 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006371
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006372 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006373 return false; // Ignore RHS;
6374
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006375 return true;
6376}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006378bool DataRecursiveIntBinOpEvaluator::
6379 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6380 const BinaryOperator *E, APValue &Result) {
6381 if (E->getOpcode() == BO_Comma) {
6382 if (RHSResult.Failed)
6383 return false;
6384 Result = RHSResult.Val;
6385 return true;
6386 }
6387
6388 if (E->isLogicalOp()) {
6389 bool lhsResult, rhsResult;
6390 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6391 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6392
6393 if (LHSIsOK) {
6394 if (RHSIsOK) {
6395 if (E->getOpcode() == BO_LOr)
6396 return Success(lhsResult || rhsResult, E, Result);
6397 else
6398 return Success(lhsResult && rhsResult, E, Result);
6399 }
6400 } else {
6401 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006402 // We can't evaluate the LHS; however, sometimes the result
6403 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6404 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006405 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006406 }
6407 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006408
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006409 return false;
6410 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006411
6412 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6413 E->getRHS()->getType()->isIntegralOrEnumerationType());
6414
6415 if (LHSResult.Failed || RHSResult.Failed)
6416 return false;
6417
6418 const APValue &LHSVal = LHSResult.Val;
6419 const APValue &RHSVal = RHSResult.Val;
6420
6421 // Handle cases like (unsigned long)&a + 4.
6422 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6423 Result = LHSVal;
6424 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6425 RHSVal.getInt().getZExtValue());
6426 if (E->getOpcode() == BO_Add)
6427 Result.getLValueOffset() += AdditionalOffset;
6428 else
6429 Result.getLValueOffset() -= AdditionalOffset;
6430 return true;
6431 }
6432
6433 // Handle cases like 4 + (unsigned long)&a
6434 if (E->getOpcode() == BO_Add &&
6435 RHSVal.isLValue() && LHSVal.isInt()) {
6436 Result = RHSVal;
6437 Result.getLValueOffset() += CharUnits::fromQuantity(
6438 LHSVal.getInt().getZExtValue());
6439 return true;
6440 }
6441
6442 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6443 // Handle (intptr_t)&&A - (intptr_t)&&B.
6444 if (!LHSVal.getLValueOffset().isZero() ||
6445 !RHSVal.getLValueOffset().isZero())
6446 return false;
6447 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6448 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6449 if (!LHSExpr || !RHSExpr)
6450 return false;
6451 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6452 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6453 if (!LHSAddrExpr || !RHSAddrExpr)
6454 return false;
6455 // Make sure both labels come from the same function.
6456 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6457 RHSAddrExpr->getLabel()->getDeclContext())
6458 return false;
6459 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6460 return true;
6461 }
Richard Smith43e77732013-05-07 04:50:00 +00006462
6463 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006464 if (!LHSVal.isInt() || !RHSVal.isInt())
6465 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006466
6467 // Set up the width and signedness manually, in case it can't be deduced
6468 // from the operation we're performing.
6469 // FIXME: Don't do this in the cases where we can deduce it.
6470 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6471 E->getType()->isUnsignedIntegerOrEnumerationType());
6472 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6473 RHSVal.getInt(), Value))
6474 return false;
6475 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006476}
6477
Richard Trieuba4d0872012-03-21 23:30:30 +00006478void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006479 Job &job = Queue.back();
6480
6481 switch (job.Kind) {
6482 case Job::AnyExprKind: {
6483 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6484 if (shouldEnqueue(Bop)) {
6485 job.Kind = Job::BinOpKind;
6486 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006487 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006488 }
6489 }
6490
6491 EvaluateExpr(job.E, Result);
6492 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006493 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006494 }
6495
6496 case Job::BinOpKind: {
6497 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006498 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006499 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006500 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006501 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006502 }
6503 if (SuppressRHSDiags)
6504 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006505 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006506 job.Kind = Job::BinOpVisitedLHSKind;
6507 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006508 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006509 }
6510
6511 case Job::BinOpVisitedLHSKind: {
6512 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6513 EvalResult RHS;
6514 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006515 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006516 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006517 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006518 }
6519 }
6520
6521 llvm_unreachable("Invalid Job::Kind!");
6522}
6523
6524bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6525 if (E->isAssignmentOp())
6526 return Error(E);
6527
6528 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6529 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006530
Anders Carlssonacc79812008-11-16 07:17:21 +00006531 QualType LHSTy = E->getLHS()->getType();
6532 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006533
6534 if (LHSTy->isAnyComplexType()) {
6535 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006536 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006537
Richard Smith253c2a32012-01-27 01:14:48 +00006538 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6539 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006540 return false;
6541
Richard Smith253c2a32012-01-27 01:14:48 +00006542 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006543 return false;
6544
6545 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006546 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006547 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006548 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006549 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6550
John McCalle3027922010-08-25 11:45:40 +00006551 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006552 return Success((CR_r == APFloat::cmpEqual &&
6553 CR_i == APFloat::cmpEqual), E);
6554 else {
John McCalle3027922010-08-25 11:45:40 +00006555 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006556 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006557 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006558 CR_r == APFloat::cmpLessThan ||
6559 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006560 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006561 CR_i == APFloat::cmpLessThan ||
6562 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006563 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006564 } else {
John McCalle3027922010-08-25 11:45:40 +00006565 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006566 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6567 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6568 else {
John McCalle3027922010-08-25 11:45:40 +00006569 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006570 "Invalid compex comparison.");
6571 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6572 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6573 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006574 }
6575 }
Mike Stump11289f42009-09-09 15:08:12 +00006576
Anders Carlssonacc79812008-11-16 07:17:21 +00006577 if (LHSTy->isRealFloatingType() &&
6578 RHSTy->isRealFloatingType()) {
6579 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006580
Richard Smith253c2a32012-01-27 01:14:48 +00006581 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6582 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006583 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006584
Richard Smith253c2a32012-01-27 01:14:48 +00006585 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006586 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006587
Anders Carlssonacc79812008-11-16 07:17:21 +00006588 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006589
Anders Carlssonacc79812008-11-16 07:17:21 +00006590 switch (E->getOpcode()) {
6591 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006592 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006593 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006594 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006595 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006596 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006597 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006598 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006599 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006600 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006601 E);
John McCalle3027922010-08-25 11:45:40 +00006602 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006603 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006604 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006605 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006606 || CR == APFloat::cmpLessThan
6607 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006608 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Eli Friedmana38da572009-04-28 19:17:36 +00006611 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006612 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006613 LValue LHSValue, RHSValue;
6614
6615 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6616 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006617 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006618
Richard Smith253c2a32012-01-27 01:14:48 +00006619 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006620 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006621
Richard Smith8b3497e2011-10-31 01:37:14 +00006622 // Reject differing bases from the normal codepath; we special-case
6623 // comparisons to null.
6624 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006625 if (E->getOpcode() == BO_Sub) {
6626 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006627 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6628 return false;
6629 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006630 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006631 if (!LHSExpr || !RHSExpr)
6632 return false;
6633 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6634 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6635 if (!LHSAddrExpr || !RHSAddrExpr)
6636 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006637 // Make sure both labels come from the same function.
6638 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6639 RHSAddrExpr->getLabel()->getDeclContext())
6640 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006641 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006642 return true;
6643 }
Richard Smith83c68212011-10-31 05:11:32 +00006644 // Inequalities and subtractions between unrelated pointers have
6645 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006646 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006647 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006648 // A constant address may compare equal to the address of a symbol.
6649 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006650 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006651 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6652 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006653 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006654 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006655 // distinct addresses. In clang, the result of such a comparison is
6656 // unspecified, so it is not a constant expression. However, we do know
6657 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006658 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6659 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006660 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006661 // We can't tell whether weak symbols will end up pointing to the same
6662 // object.
6663 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006664 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006665 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006666 // (Note that clang defaults to -fmerge-all-constants, which can
6667 // lead to inconsistent results for comparisons involving the address
6668 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006669 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006670 }
Eli Friedman64004332009-03-23 04:38:34 +00006671
Richard Smith1b470412012-02-01 08:10:20 +00006672 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6673 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6674
Richard Smith84f6dcf2012-02-02 01:16:57 +00006675 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6676 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6677
John McCalle3027922010-08-25 11:45:40 +00006678 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006679 // C++11 [expr.add]p6:
6680 // Unless both pointers point to elements of the same array object, or
6681 // one past the last element of the array object, the behavior is
6682 // undefined.
6683 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6684 !AreElementsOfSameArray(getType(LHSValue.Base),
6685 LHSDesignator, RHSDesignator))
6686 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6687
Chris Lattner882bdf22010-04-20 17:13:14 +00006688 QualType Type = E->getLHS()->getType();
6689 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006690
Richard Smithd62306a2011-11-10 06:34:14 +00006691 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006692 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006693 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006694
Richard Smith84c6b3d2013-09-10 21:34:14 +00006695 // As an extension, a type may have zero size (empty struct or union in
6696 // C, array of zero length). Pointer subtraction in such cases has
6697 // undefined behavior, so is not constant.
6698 if (ElementSize.isZero()) {
6699 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6700 << ElementType;
6701 return false;
6702 }
6703
Richard Smith1b470412012-02-01 08:10:20 +00006704 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6705 // and produce incorrect results when it overflows. Such behavior
6706 // appears to be non-conforming, but is common, so perhaps we should
6707 // assume the standard intended for such cases to be undefined behavior
6708 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006709
Richard Smith1b470412012-02-01 08:10:20 +00006710 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6711 // overflow in the final conversion to ptrdiff_t.
6712 APSInt LHS(
6713 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6714 APSInt RHS(
6715 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6716 APSInt ElemSize(
6717 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6718 APSInt TrueResult = (LHS - RHS) / ElemSize;
6719 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6720
6721 if (Result.extend(65) != TrueResult)
6722 HandleOverflow(Info, E, TrueResult, E->getType());
6723 return Success(Result, E);
6724 }
Richard Smithde21b242012-01-31 06:41:30 +00006725
6726 // C++11 [expr.rel]p3:
6727 // Pointers to void (after pointer conversions) can be compared, with a
6728 // result defined as follows: If both pointers represent the same
6729 // address or are both the null pointer value, the result is true if the
6730 // operator is <= or >= and false otherwise; otherwise the result is
6731 // unspecified.
6732 // We interpret this as applying to pointers to *cv* void.
6733 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006734 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006735 CCEDiag(E, diag::note_constexpr_void_comparison);
6736
Richard Smith84f6dcf2012-02-02 01:16:57 +00006737 // C++11 [expr.rel]p2:
6738 // - If two pointers point to non-static data members of the same object,
6739 // or to subobjects or array elements fo such members, recursively, the
6740 // pointer to the later declared member compares greater provided the
6741 // two members have the same access control and provided their class is
6742 // not a union.
6743 // [...]
6744 // - Otherwise pointer comparisons are unspecified.
6745 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6746 E->isRelationalOp()) {
6747 bool WasArrayIndex;
6748 unsigned Mismatch =
6749 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6750 RHSDesignator, WasArrayIndex);
6751 // At the point where the designators diverge, the comparison has a
6752 // specified value if:
6753 // - we are comparing array indices
6754 // - we are comparing fields of a union, or fields with the same access
6755 // Otherwise, the result is unspecified and thus the comparison is not a
6756 // constant expression.
6757 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6758 Mismatch < RHSDesignator.Entries.size()) {
6759 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6760 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6761 if (!LF && !RF)
6762 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6763 else if (!LF)
6764 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6765 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6766 << RF->getParent() << RF;
6767 else if (!RF)
6768 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6769 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6770 << LF->getParent() << LF;
6771 else if (!LF->getParent()->isUnion() &&
6772 LF->getAccess() != RF->getAccess())
6773 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6774 << LF << LF->getAccess() << RF << RF->getAccess()
6775 << LF->getParent();
6776 }
6777 }
6778
Eli Friedman6c31cb42012-04-16 04:30:08 +00006779 // The comparison here must be unsigned, and performed with the same
6780 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006781 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6782 uint64_t CompareLHS = LHSOffset.getQuantity();
6783 uint64_t CompareRHS = RHSOffset.getQuantity();
6784 assert(PtrSize <= 64 && "Unexpected pointer width");
6785 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6786 CompareLHS &= Mask;
6787 CompareRHS &= Mask;
6788
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006789 // If there is a base and this is a relational operator, we can only
6790 // compare pointers within the object in question; otherwise, the result
6791 // depends on where the object is located in memory.
6792 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6793 QualType BaseTy = getType(LHSValue.Base);
6794 if (BaseTy->isIncompleteType())
6795 return Error(E);
6796 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6797 uint64_t OffsetLimit = Size.getQuantity();
6798 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6799 return Error(E);
6800 }
6801
Richard Smith8b3497e2011-10-31 01:37:14 +00006802 switch (E->getOpcode()) {
6803 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006804 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6805 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6806 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6807 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6808 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6809 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006810 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006811 }
6812 }
Richard Smith7bb00672012-02-01 01:42:44 +00006813
6814 if (LHSTy->isMemberPointerType()) {
6815 assert(E->isEqualityOp() && "unexpected member pointer operation");
6816 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6817
6818 MemberPtr LHSValue, RHSValue;
6819
6820 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6821 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6822 return false;
6823
6824 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6825 return false;
6826
6827 // C++11 [expr.eq]p2:
6828 // If both operands are null, they compare equal. Otherwise if only one is
6829 // null, they compare unequal.
6830 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6831 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6832 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6833 }
6834
6835 // Otherwise if either is a pointer to a virtual member function, the
6836 // result is unspecified.
6837 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6838 if (MD->isVirtual())
6839 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6840 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6841 if (MD->isVirtual())
6842 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6843
6844 // Otherwise they compare equal if and only if they would refer to the
6845 // same member of the same most derived object or the same subobject if
6846 // they were dereferenced with a hypothetical object of the associated
6847 // class type.
6848 bool Equal = LHSValue == RHSValue;
6849 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6850 }
6851
Richard Smithab44d9b2012-02-14 22:35:28 +00006852 if (LHSTy->isNullPtrType()) {
6853 assert(E->isComparisonOp() && "unexpected nullptr operation");
6854 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6855 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6856 // are compared, the result is true of the operator is <=, >= or ==, and
6857 // false otherwise.
6858 BinaryOperator::Opcode Opcode = E->getOpcode();
6859 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6860 }
6861
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006862 assert((!LHSTy->isIntegralOrEnumerationType() ||
6863 !RHSTy->isIntegralOrEnumerationType()) &&
6864 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6865 // We can't continue from here for non-integral types.
6866 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006867}
6868
Ken Dyck160146e2010-01-27 17:10:57 +00006869CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006870 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6871 // result shall be the alignment of the referenced type."
6872 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6873 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006874
6875 // __alignof is defined to return the preferred alignment.
6876 return Info.Ctx.toCharUnitsFromBits(
6877 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006878}
6879
Ken Dyck160146e2010-01-27 17:10:57 +00006880CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006881 E = E->IgnoreParens();
6882
John McCall768439e2013-05-06 07:40:34 +00006883 // The kinds of expressions that we have special-case logic here for
6884 // should be kept up to date with the special checks for those
6885 // expressions in Sema.
6886
Chris Lattner68061312009-01-24 21:53:27 +00006887 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006888 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006889 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006890 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6891 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006892
Chris Lattner68061312009-01-24 21:53:27 +00006893 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006894 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6895 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006896
Chris Lattner24aeeab2009-01-24 21:09:06 +00006897 return GetAlignOfType(E->getType());
6898}
6899
6900
Peter Collingbournee190dee2011-03-11 19:24:49 +00006901/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6902/// a result as the expression's type.
6903bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6904 const UnaryExprOrTypeTraitExpr *E) {
6905 switch(E->getKind()) {
6906 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006907 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006908 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006909 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006910 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006911 }
Eli Friedman64004332009-03-23 04:38:34 +00006912
Peter Collingbournee190dee2011-03-11 19:24:49 +00006913 case UETT_VecStep: {
6914 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006915
Peter Collingbournee190dee2011-03-11 19:24:49 +00006916 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006917 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006918
Peter Collingbournee190dee2011-03-11 19:24:49 +00006919 // The vec_step built-in functions that take a 3-component
6920 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6921 if (n == 3)
6922 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006923
Peter Collingbournee190dee2011-03-11 19:24:49 +00006924 return Success(n, E);
6925 } else
6926 return Success(1, E);
6927 }
6928
6929 case UETT_SizeOf: {
6930 QualType SrcTy = E->getTypeOfArgument();
6931 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6932 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006933 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6934 SrcTy = Ref->getPointeeType();
6935
Richard Smithd62306a2011-11-10 06:34:14 +00006936 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006937 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006938 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006939 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006940 }
6941 }
6942
6943 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006944}
6945
Peter Collingbournee9200682011-05-13 03:29:01 +00006946bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006947 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006948 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006949 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006950 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006951 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006952 for (unsigned i = 0; i != n; ++i) {
6953 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6954 switch (ON.getKind()) {
6955 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006956 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006957 APSInt IdxResult;
6958 if (!EvaluateInteger(Idx, IdxResult, Info))
6959 return false;
6960 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6961 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006962 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006963 CurrentType = AT->getElementType();
6964 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6965 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006966 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006967 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006968
Douglas Gregor882211c2010-04-28 22:16:22 +00006969 case OffsetOfExpr::OffsetOfNode::Field: {
6970 FieldDecl *MemberDecl = ON.getField();
6971 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006972 if (!RT)
6973 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006974 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006975 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006976 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006977 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006978 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006979 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006980 CurrentType = MemberDecl->getType().getNonReferenceType();
6981 break;
6982 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006983
Douglas Gregor882211c2010-04-28 22:16:22 +00006984 case OffsetOfExpr::OffsetOfNode::Identifier:
6985 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006986
Douglas Gregord1702062010-04-29 00:18:15 +00006987 case OffsetOfExpr::OffsetOfNode::Base: {
6988 CXXBaseSpecifier *BaseSpec = ON.getBase();
6989 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006990 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006991
6992 // Find the layout of the class whose base we are looking into.
6993 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006994 if (!RT)
6995 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006996 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006997 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006998 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6999
7000 // Find the base class itself.
7001 CurrentType = BaseSpec->getType();
7002 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7003 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007004 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007005
7006 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007007 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007008 break;
7009 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007010 }
7011 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007012 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007013}
7014
Chris Lattnere13042c2008-07-11 19:10:17 +00007015bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007016 switch (E->getOpcode()) {
7017 default:
7018 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7019 // See C99 6.6p3.
7020 return Error(E);
7021 case UO_Extension:
7022 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7023 // If so, we could clear the diagnostic ID.
7024 return Visit(E->getSubExpr());
7025 case UO_Plus:
7026 // The result is just the value.
7027 return Visit(E->getSubExpr());
7028 case UO_Minus: {
7029 if (!Visit(E->getSubExpr()))
7030 return false;
7031 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007032 const APSInt &Value = Result.getInt();
7033 if (Value.isSigned() && Value.isMinSignedValue())
7034 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7035 E->getType());
7036 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007037 }
7038 case UO_Not: {
7039 if (!Visit(E->getSubExpr()))
7040 return false;
7041 if (!Result.isInt()) return Error(E);
7042 return Success(~Result.getInt(), E);
7043 }
7044 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007045 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007046 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007047 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007048 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007049 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007050 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007051}
Mike Stump11289f42009-09-09 15:08:12 +00007052
Chris Lattner477c4be2008-07-12 01:15:53 +00007053/// HandleCast - This is used to evaluate implicit or explicit casts where the
7054/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007055bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7056 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007057 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007058 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007059
Eli Friedmanc757de22011-03-25 00:43:55 +00007060 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007061 case CK_BaseToDerived:
7062 case CK_DerivedToBase:
7063 case CK_UncheckedDerivedToBase:
7064 case CK_Dynamic:
7065 case CK_ToUnion:
7066 case CK_ArrayToPointerDecay:
7067 case CK_FunctionToPointerDecay:
7068 case CK_NullToPointer:
7069 case CK_NullToMemberPointer:
7070 case CK_BaseToDerivedMemberPointer:
7071 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007072 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007073 case CK_ConstructorConversion:
7074 case CK_IntegralToPointer:
7075 case CK_ToVoid:
7076 case CK_VectorSplat:
7077 case CK_IntegralToFloating:
7078 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007079 case CK_CPointerToObjCPointerCast:
7080 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007081 case CK_AnyPointerToBlockPointerCast:
7082 case CK_ObjCObjectLValueCast:
7083 case CK_FloatingRealToComplex:
7084 case CK_FloatingComplexToReal:
7085 case CK_FloatingComplexCast:
7086 case CK_FloatingComplexToIntegralComplex:
7087 case CK_IntegralRealToComplex:
7088 case CK_IntegralComplexCast:
7089 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007090 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007091 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007092 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007093 llvm_unreachable("invalid cast kind for integral value");
7094
Eli Friedman9faf2f92011-03-25 19:07:11 +00007095 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007096 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007097 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007098 case CK_ARCProduceObject:
7099 case CK_ARCConsumeObject:
7100 case CK_ARCReclaimReturnedObject:
7101 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007102 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007103 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007104
Richard Smith4ef685b2012-01-17 21:17:26 +00007105 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007106 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007107 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007108 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007109 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007110
7111 case CK_MemberPointerToBoolean:
7112 case CK_PointerToBoolean:
7113 case CK_IntegralToBoolean:
7114 case CK_FloatingToBoolean:
7115 case CK_FloatingComplexToBoolean:
7116 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007117 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007118 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007119 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007120 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007121 }
7122
Eli Friedmanc757de22011-03-25 00:43:55 +00007123 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007124 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007125 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007126
Eli Friedman742421e2009-02-20 01:15:07 +00007127 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007128 // Allow casts of address-of-label differences if they are no-ops
7129 // or narrowing. (The narrowing case isn't actually guaranteed to
7130 // be constant-evaluatable except in some narrow cases which are hard
7131 // to detect here. We let it through on the assumption the user knows
7132 // what they are doing.)
7133 if (Result.isAddrLabelDiff())
7134 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007135 // Only allow casts of lvalues if they are lossless.
7136 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7137 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007138
Richard Smith911e1422012-01-30 22:27:01 +00007139 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7140 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007141 }
Mike Stump11289f42009-09-09 15:08:12 +00007142
Eli Friedmanc757de22011-03-25 00:43:55 +00007143 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007144 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7145
John McCall45d55e42010-05-07 21:00:08 +00007146 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007147 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007148 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007149
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007150 if (LV.getLValueBase()) {
7151 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007152 // FIXME: Allow a larger integer size than the pointer size, and allow
7153 // narrowing back down to pointer width in subsequent integral casts.
7154 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007155 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007156 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007157
Richard Smithcf74da72011-11-16 07:18:12 +00007158 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007159 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007160 return true;
7161 }
7162
Ken Dyck02990832010-01-15 12:37:54 +00007163 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7164 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007165 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007166 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007167
Eli Friedmanc757de22011-03-25 00:43:55 +00007168 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007169 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007170 if (!EvaluateComplex(SubExpr, C, Info))
7171 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007172 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007173 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007174
Eli Friedmanc757de22011-03-25 00:43:55 +00007175 case CK_FloatingToIntegral: {
7176 APFloat F(0.0);
7177 if (!EvaluateFloat(SubExpr, F, Info))
7178 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007179
Richard Smith357362d2011-12-13 06:39:58 +00007180 APSInt Value;
7181 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7182 return false;
7183 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007184 }
7185 }
Mike Stump11289f42009-09-09 15:08:12 +00007186
Eli Friedmanc757de22011-03-25 00:43:55 +00007187 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007188}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007189
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007190bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7191 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007192 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007193 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7194 return false;
7195 if (!LV.isComplexInt())
7196 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007197 return Success(LV.getComplexIntReal(), E);
7198 }
7199
7200 return Visit(E->getSubExpr());
7201}
7202
Eli Friedman4e7a2412009-02-27 04:45:43 +00007203bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007204 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007205 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007206 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7207 return false;
7208 if (!LV.isComplexInt())
7209 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007210 return Success(LV.getComplexIntImag(), E);
7211 }
7212
Richard Smith4a678122011-10-24 18:44:57 +00007213 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007214 return Success(0, E);
7215}
7216
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007217bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7218 return Success(E->getPackLength(), E);
7219}
7220
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007221bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7222 return Success(E->getValue(), E);
7223}
7224
Chris Lattner05706e882008-07-11 18:11:29 +00007225//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007226// Float Evaluation
7227//===----------------------------------------------------------------------===//
7228
7229namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007230class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007231 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007232 APFloat &Result;
7233public:
7234 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007235 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007236
Richard Smith2e312c82012-03-03 22:46:17 +00007237 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007238 Result = V.getFloat();
7239 return true;
7240 }
Eli Friedman24c01542008-08-22 00:06:13 +00007241
Richard Smithfddd3842011-12-30 21:15:51 +00007242 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007243 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7244 return true;
7245 }
7246
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007247 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007248
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007249 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007250 bool VisitBinaryOperator(const BinaryOperator *E);
7251 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007252 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007253
John McCallb1fb0d32010-05-07 22:08:54 +00007254 bool VisitUnaryReal(const UnaryOperator *E);
7255 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007256
Richard Smithfddd3842011-12-30 21:15:51 +00007257 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007258};
7259} // end anonymous namespace
7260
7261static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007262 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007263 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007264}
7265
Jay Foad39c79802011-01-12 09:06:06 +00007266static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007267 QualType ResultTy,
7268 const Expr *Arg,
7269 bool SNaN,
7270 llvm::APFloat &Result) {
7271 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7272 if (!S) return false;
7273
7274 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7275
7276 llvm::APInt fill;
7277
7278 // Treat empty strings as if they were zero.
7279 if (S->getString().empty())
7280 fill = llvm::APInt(32, 0);
7281 else if (S->getString().getAsInteger(0, fill))
7282 return false;
7283
7284 if (SNaN)
7285 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7286 else
7287 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7288 return true;
7289}
7290
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007291bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007292 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007293 default:
7294 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7295
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007296 case Builtin::BI__builtin_huge_val:
7297 case Builtin::BI__builtin_huge_valf:
7298 case Builtin::BI__builtin_huge_vall:
7299 case Builtin::BI__builtin_inf:
7300 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007301 case Builtin::BI__builtin_infl: {
7302 const llvm::fltSemantics &Sem =
7303 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007304 Result = llvm::APFloat::getInf(Sem);
7305 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007306 }
Mike Stump11289f42009-09-09 15:08:12 +00007307
John McCall16291492010-02-28 13:00:19 +00007308 case Builtin::BI__builtin_nans:
7309 case Builtin::BI__builtin_nansf:
7310 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007311 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7312 true, Result))
7313 return Error(E);
7314 return true;
John McCall16291492010-02-28 13:00:19 +00007315
Chris Lattner0b7282e2008-10-06 06:31:58 +00007316 case Builtin::BI__builtin_nan:
7317 case Builtin::BI__builtin_nanf:
7318 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007319 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007320 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007321 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7322 false, Result))
7323 return Error(E);
7324 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007325
7326 case Builtin::BI__builtin_fabs:
7327 case Builtin::BI__builtin_fabsf:
7328 case Builtin::BI__builtin_fabsl:
7329 if (!EvaluateFloat(E->getArg(0), Result, Info))
7330 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007331
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007332 if (Result.isNegative())
7333 Result.changeSign();
7334 return true;
7335
Richard Smith8889a3d2013-06-13 06:26:32 +00007336 // FIXME: Builtin::BI__builtin_powi
7337 // FIXME: Builtin::BI__builtin_powif
7338 // FIXME: Builtin::BI__builtin_powil
7339
Mike Stump11289f42009-09-09 15:08:12 +00007340 case Builtin::BI__builtin_copysign:
7341 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007342 case Builtin::BI__builtin_copysignl: {
7343 APFloat RHS(0.);
7344 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7345 !EvaluateFloat(E->getArg(1), RHS, Info))
7346 return false;
7347 Result.copySign(RHS);
7348 return true;
7349 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007350 }
7351}
7352
John McCallb1fb0d32010-05-07 22:08:54 +00007353bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007354 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7355 ComplexValue CV;
7356 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7357 return false;
7358 Result = CV.FloatReal;
7359 return true;
7360 }
7361
7362 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007363}
7364
7365bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007366 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7367 ComplexValue CV;
7368 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7369 return false;
7370 Result = CV.FloatImag;
7371 return true;
7372 }
7373
Richard Smith4a678122011-10-24 18:44:57 +00007374 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007375 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7376 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007377 return true;
7378}
7379
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007380bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007381 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007382 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007383 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007384 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007385 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007386 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7387 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007388 Result.changeSign();
7389 return true;
7390 }
7391}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007392
Eli Friedman24c01542008-08-22 00:06:13 +00007393bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007394 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7395 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007396
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007397 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007398 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7399 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007400 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007401 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7402 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007403}
7404
7405bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7406 Result = E->getValue();
7407 return true;
7408}
7409
Peter Collingbournee9200682011-05-13 03:29:01 +00007410bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7411 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007412
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007413 switch (E->getCastKind()) {
7414 default:
Richard Smith11562c52011-10-28 17:51:58 +00007415 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007416
7417 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007418 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007419 return EvaluateInteger(SubExpr, IntResult, Info) &&
7420 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7421 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007422 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007423
7424 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007425 if (!Visit(SubExpr))
7426 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007427 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7428 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007429 }
John McCalld7646252010-11-14 08:17:51 +00007430
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007431 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007432 ComplexValue V;
7433 if (!EvaluateComplex(SubExpr, V, Info))
7434 return false;
7435 Result = V.getComplexFloatReal();
7436 return true;
7437 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007438 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007439}
7440
Eli Friedman24c01542008-08-22 00:06:13 +00007441//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007442// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007443//===----------------------------------------------------------------------===//
7444
7445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007446class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007447 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007448 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007449
Anders Carlsson537969c2008-11-16 20:27:53 +00007450public:
John McCall93d91dc2010-05-07 17:22:02 +00007451 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007452 : ExprEvaluatorBaseTy(info), Result(Result) {}
7453
Richard Smith2e312c82012-03-03 22:46:17 +00007454 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007455 Result.setFrom(V);
7456 return true;
7457 }
Mike Stump11289f42009-09-09 15:08:12 +00007458
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007459 bool ZeroInitialization(const Expr *E);
7460
Anders Carlsson537969c2008-11-16 20:27:53 +00007461 //===--------------------------------------------------------------------===//
7462 // Visitor Methods
7463 //===--------------------------------------------------------------------===//
7464
Peter Collingbournee9200682011-05-13 03:29:01 +00007465 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007466 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007467 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007468 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007469 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007470};
7471} // end anonymous namespace
7472
John McCall93d91dc2010-05-07 17:22:02 +00007473static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7474 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007475 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007476 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007477}
7478
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007479bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007480 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007481 if (ElemTy->isRealFloatingType()) {
7482 Result.makeComplexFloat();
7483 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7484 Result.FloatReal = Zero;
7485 Result.FloatImag = Zero;
7486 } else {
7487 Result.makeComplexInt();
7488 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7489 Result.IntReal = Zero;
7490 Result.IntImag = Zero;
7491 }
7492 return true;
7493}
7494
Peter Collingbournee9200682011-05-13 03:29:01 +00007495bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7496 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007497
7498 if (SubExpr->getType()->isRealFloatingType()) {
7499 Result.makeComplexFloat();
7500 APFloat &Imag = Result.FloatImag;
7501 if (!EvaluateFloat(SubExpr, Imag, Info))
7502 return false;
7503
7504 Result.FloatReal = APFloat(Imag.getSemantics());
7505 return true;
7506 } else {
7507 assert(SubExpr->getType()->isIntegerType() &&
7508 "Unexpected imaginary literal.");
7509
7510 Result.makeComplexInt();
7511 APSInt &Imag = Result.IntImag;
7512 if (!EvaluateInteger(SubExpr, Imag, Info))
7513 return false;
7514
7515 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7516 return true;
7517 }
7518}
7519
Peter Collingbournee9200682011-05-13 03:29:01 +00007520bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007521
John McCallfcef3cf2010-12-14 17:51:41 +00007522 switch (E->getCastKind()) {
7523 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007524 case CK_BaseToDerived:
7525 case CK_DerivedToBase:
7526 case CK_UncheckedDerivedToBase:
7527 case CK_Dynamic:
7528 case CK_ToUnion:
7529 case CK_ArrayToPointerDecay:
7530 case CK_FunctionToPointerDecay:
7531 case CK_NullToPointer:
7532 case CK_NullToMemberPointer:
7533 case CK_BaseToDerivedMemberPointer:
7534 case CK_DerivedToBaseMemberPointer:
7535 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007536 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007537 case CK_ConstructorConversion:
7538 case CK_IntegralToPointer:
7539 case CK_PointerToIntegral:
7540 case CK_PointerToBoolean:
7541 case CK_ToVoid:
7542 case CK_VectorSplat:
7543 case CK_IntegralCast:
7544 case CK_IntegralToBoolean:
7545 case CK_IntegralToFloating:
7546 case CK_FloatingToIntegral:
7547 case CK_FloatingToBoolean:
7548 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007549 case CK_CPointerToObjCPointerCast:
7550 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007551 case CK_AnyPointerToBlockPointerCast:
7552 case CK_ObjCObjectLValueCast:
7553 case CK_FloatingComplexToReal:
7554 case CK_FloatingComplexToBoolean:
7555 case CK_IntegralComplexToReal:
7556 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007557 case CK_ARCProduceObject:
7558 case CK_ARCConsumeObject:
7559 case CK_ARCReclaimReturnedObject:
7560 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007561 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007562 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007563 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007564 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007565 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007566
John McCallfcef3cf2010-12-14 17:51:41 +00007567 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007568 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007569 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007570 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007571
7572 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007573 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007574 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007575 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007576
7577 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007578 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007579 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007580 return false;
7581
John McCallfcef3cf2010-12-14 17:51:41 +00007582 Result.makeComplexFloat();
7583 Result.FloatImag = APFloat(Real.getSemantics());
7584 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007585 }
7586
John McCallfcef3cf2010-12-14 17:51:41 +00007587 case CK_FloatingComplexCast: {
7588 if (!Visit(E->getSubExpr()))
7589 return false;
7590
7591 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7592 QualType From
7593 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7594
Richard Smith357362d2011-12-13 06:39:58 +00007595 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7596 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007597 }
7598
7599 case CK_FloatingComplexToIntegralComplex: {
7600 if (!Visit(E->getSubExpr()))
7601 return false;
7602
7603 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7604 QualType From
7605 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7606 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007607 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7608 To, Result.IntReal) &&
7609 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7610 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007611 }
7612
7613 case CK_IntegralRealToComplex: {
7614 APSInt &Real = Result.IntReal;
7615 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7616 return false;
7617
7618 Result.makeComplexInt();
7619 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7620 return true;
7621 }
7622
7623 case CK_IntegralComplexCast: {
7624 if (!Visit(E->getSubExpr()))
7625 return false;
7626
7627 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7628 QualType From
7629 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7630
Richard Smith911e1422012-01-30 22:27:01 +00007631 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7632 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007633 return true;
7634 }
7635
7636 case CK_IntegralComplexToFloatingComplex: {
7637 if (!Visit(E->getSubExpr()))
7638 return false;
7639
Ted Kremenek28831752012-08-23 20:46:57 +00007640 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007641 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007642 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007643 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007644 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7645 To, Result.FloatReal) &&
7646 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7647 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007648 }
7649 }
7650
7651 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007652}
7653
John McCall93d91dc2010-05-07 17:22:02 +00007654bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007655 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007656 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7657
Richard Smith253c2a32012-01-27 01:14:48 +00007658 bool LHSOK = Visit(E->getLHS());
7659 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007660 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007661
John McCall93d91dc2010-05-07 17:22:02 +00007662 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007663 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007664 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007665
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007666 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7667 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007668 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007669 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007670 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007671 if (Result.isComplexFloat()) {
7672 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7673 APFloat::rmNearestTiesToEven);
7674 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7675 APFloat::rmNearestTiesToEven);
7676 } else {
7677 Result.getComplexIntReal() += RHS.getComplexIntReal();
7678 Result.getComplexIntImag() += RHS.getComplexIntImag();
7679 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007680 break;
John McCalle3027922010-08-25 11:45:40 +00007681 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007682 if (Result.isComplexFloat()) {
7683 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7684 APFloat::rmNearestTiesToEven);
7685 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7686 APFloat::rmNearestTiesToEven);
7687 } else {
7688 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7689 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7690 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007691 break;
John McCalle3027922010-08-25 11:45:40 +00007692 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007693 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007694 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007695 APFloat &LHS_r = LHS.getComplexFloatReal();
7696 APFloat &LHS_i = LHS.getComplexFloatImag();
7697 APFloat &RHS_r = RHS.getComplexFloatReal();
7698 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007699
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007700 APFloat Tmp = LHS_r;
7701 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7702 Result.getComplexFloatReal() = Tmp;
7703 Tmp = LHS_i;
7704 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7705 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7706
7707 Tmp = LHS_r;
7708 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7709 Result.getComplexFloatImag() = Tmp;
7710 Tmp = LHS_i;
7711 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7712 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7713 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007714 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007715 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007716 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7717 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007718 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007719 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7720 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7721 }
7722 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007723 case BO_Div:
7724 if (Result.isComplexFloat()) {
7725 ComplexValue LHS = Result;
7726 APFloat &LHS_r = LHS.getComplexFloatReal();
7727 APFloat &LHS_i = LHS.getComplexFloatImag();
7728 APFloat &RHS_r = RHS.getComplexFloatReal();
7729 APFloat &RHS_i = RHS.getComplexFloatImag();
7730 APFloat &Res_r = Result.getComplexFloatReal();
7731 APFloat &Res_i = Result.getComplexFloatImag();
7732
7733 APFloat Den = RHS_r;
7734 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7735 APFloat Tmp = RHS_i;
7736 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7737 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7738
7739 Res_r = LHS_r;
7740 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7741 Tmp = LHS_i;
7742 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7743 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7744 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7745
7746 Res_i = LHS_i;
7747 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7748 Tmp = LHS_r;
7749 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7750 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7751 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7752 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007753 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7754 return Error(E, diag::note_expr_divide_by_zero);
7755
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007756 ComplexValue LHS = Result;
7757 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7758 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7759 Result.getComplexIntReal() =
7760 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7761 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7762 Result.getComplexIntImag() =
7763 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7764 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7765 }
7766 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007767 }
7768
John McCall93d91dc2010-05-07 17:22:02 +00007769 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007770}
7771
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007772bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7773 // Get the operand value into 'Result'.
7774 if (!Visit(E->getSubExpr()))
7775 return false;
7776
7777 switch (E->getOpcode()) {
7778 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007779 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007780 case UO_Extension:
7781 return true;
7782 case UO_Plus:
7783 // The result is always just the subexpr.
7784 return true;
7785 case UO_Minus:
7786 if (Result.isComplexFloat()) {
7787 Result.getComplexFloatReal().changeSign();
7788 Result.getComplexFloatImag().changeSign();
7789 }
7790 else {
7791 Result.getComplexIntReal() = -Result.getComplexIntReal();
7792 Result.getComplexIntImag() = -Result.getComplexIntImag();
7793 }
7794 return true;
7795 case UO_Not:
7796 if (Result.isComplexFloat())
7797 Result.getComplexFloatImag().changeSign();
7798 else
7799 Result.getComplexIntImag() = -Result.getComplexIntImag();
7800 return true;
7801 }
7802}
7803
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007804bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7805 if (E->getNumInits() == 2) {
7806 if (E->getType()->isComplexType()) {
7807 Result.makeComplexFloat();
7808 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7809 return false;
7810 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7811 return false;
7812 } else {
7813 Result.makeComplexInt();
7814 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7815 return false;
7816 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7817 return false;
7818 }
7819 return true;
7820 }
7821 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7822}
7823
Anders Carlsson537969c2008-11-16 20:27:53 +00007824//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007825// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7826// implicit conversion.
7827//===----------------------------------------------------------------------===//
7828
7829namespace {
7830class AtomicExprEvaluator :
7831 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7832 APValue &Result;
7833public:
7834 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7835 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7836
7837 bool Success(const APValue &V, const Expr *E) {
7838 Result = V;
7839 return true;
7840 }
7841
7842 bool ZeroInitialization(const Expr *E) {
7843 ImplicitValueInitExpr VIE(
7844 E->getType()->castAs<AtomicType>()->getValueType());
7845 return Evaluate(Result, Info, &VIE);
7846 }
7847
7848 bool VisitCastExpr(const CastExpr *E) {
7849 switch (E->getCastKind()) {
7850 default:
7851 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7852 case CK_NonAtomicToAtomic:
7853 return Evaluate(Result, Info, E->getSubExpr());
7854 }
7855 }
7856};
7857} // end anonymous namespace
7858
7859static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7860 assert(E->isRValue() && E->getType()->isAtomicType());
7861 return AtomicExprEvaluator(Info, Result).Visit(E);
7862}
7863
7864//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007865// Void expression evaluation, primarily for a cast to void on the LHS of a
7866// comma operator
7867//===----------------------------------------------------------------------===//
7868
7869namespace {
7870class VoidExprEvaluator
7871 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7872public:
7873 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7874
Richard Smith2e312c82012-03-03 22:46:17 +00007875 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007876
7877 bool VisitCastExpr(const CastExpr *E) {
7878 switch (E->getCastKind()) {
7879 default:
7880 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7881 case CK_ToVoid:
7882 VisitIgnoredValue(E->getSubExpr());
7883 return true;
7884 }
7885 }
7886};
7887} // end anonymous namespace
7888
7889static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7890 assert(E->isRValue() && E->getType()->isVoidType());
7891 return VoidExprEvaluator(Info).Visit(E);
7892}
7893
7894//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007895// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007896//===----------------------------------------------------------------------===//
7897
Richard Smith2e312c82012-03-03 22:46:17 +00007898static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007899 // In C, function designators are not lvalues, but we evaluate them as if they
7900 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007901 QualType T = E->getType();
7902 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007903 LValue LV;
7904 if (!EvaluateLValue(E, LV, Info))
7905 return false;
7906 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007907 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007908 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007909 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007910 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007911 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007912 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007913 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007914 LValue LV;
7915 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007916 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007917 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007918 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007919 llvm::APFloat F(0.0);
7920 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007921 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007922 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007923 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007924 ComplexValue C;
7925 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007926 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007927 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007928 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007929 MemberPtr P;
7930 if (!EvaluateMemberPointer(E, P, Info))
7931 return false;
7932 P.moveInto(Result);
7933 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007934 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007935 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007936 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007937 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7938 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007939 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007940 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007941 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007942 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007943 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007944 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7945 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007946 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007947 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007948 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007949 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007950 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007951 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007952 if (!EvaluateVoid(E, Info))
7953 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007954 } else if (T->isAtomicType()) {
7955 if (!EvaluateAtomic(E, Result, Info))
7956 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007957 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007958 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007959 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007960 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007961 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007962 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007963 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007964
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007965 return true;
7966}
7967
Richard Smithb228a862012-02-15 02:18:13 +00007968/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7969/// cases, the in-place evaluation is essential, since later initializers for
7970/// an object can indirectly refer to subobjects which were initialized earlier.
7971static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007972 const Expr *E, bool AllowNonLiteralTypes) {
7973 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007974 return false;
7975
7976 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007977 // Evaluate arrays and record types in-place, so that later initializers can
7978 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007979 if (E->getType()->isArrayType())
7980 return EvaluateArray(E, This, Result, Info);
7981 else if (E->getType()->isRecordType())
7982 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007983 }
7984
7985 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007986 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007987}
7988
Richard Smithf57d8cb2011-12-09 22:58:01 +00007989/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7990/// lvalue-to-rvalue cast if it is an lvalue.
7991static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007992 if (!CheckLiteralType(Info, E))
7993 return false;
7994
Richard Smith2e312c82012-03-03 22:46:17 +00007995 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007996 return false;
7997
7998 if (E->isGLValue()) {
7999 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008000 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008001 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008002 return false;
8003 }
8004
Richard Smith2e312c82012-03-03 22:46:17 +00008005 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008006 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008007}
Richard Smith11562c52011-10-28 17:51:58 +00008008
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008009static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8010 const ASTContext &Ctx, bool &IsConst) {
8011 // Fast-path evaluations of integer literals, since we sometimes see files
8012 // containing vast quantities of these.
8013 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8014 Result.Val = APValue(APSInt(L->getValue(),
8015 L->getType()->isUnsignedIntegerType()));
8016 IsConst = true;
8017 return true;
8018 }
8019
8020 // FIXME: Evaluating values of large array and record types can cause
8021 // performance problems. Only do so in C++11 for now.
8022 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8023 Exp->getType()->isRecordType()) &&
8024 !Ctx.getLangOpts().CPlusPlus11) {
8025 IsConst = false;
8026 return true;
8027 }
8028 return false;
8029}
8030
8031
Richard Smith7b553f12011-10-29 00:50:52 +00008032/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008033/// any crazy technique (that has nothing to do with language standards) that
8034/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008035/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8036/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008037bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008038 bool IsConst;
8039 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8040 return IsConst;
8041
Richard Smith6d4c6582013-11-05 22:18:15 +00008042 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008043 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008044}
8045
Jay Foad39c79802011-01-12 09:06:06 +00008046bool Expr::EvaluateAsBooleanCondition(bool &Result,
8047 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008048 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008049 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008050 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008051}
8052
Richard Smith5fab0c92011-12-28 19:48:30 +00008053bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8054 SideEffectsKind AllowSideEffects) const {
8055 if (!getType()->isIntegralOrEnumerationType())
8056 return false;
8057
Richard Smith11562c52011-10-28 17:51:58 +00008058 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008059 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8060 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008061 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008062
Richard Smith11562c52011-10-28 17:51:58 +00008063 Result = ExprResult.Val.getInt();
8064 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008065}
8066
Jay Foad39c79802011-01-12 09:06:06 +00008067bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008068 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008069
John McCall45d55e42010-05-07 21:00:08 +00008070 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008071 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8072 !CheckLValueConstantExpression(Info, getExprLoc(),
8073 Ctx.getLValueReferenceType(getType()), LV))
8074 return false;
8075
Richard Smith2e312c82012-03-03 22:46:17 +00008076 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008077 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008078}
8079
Richard Smithd0b4dd62011-12-19 06:19:21 +00008080bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8081 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008082 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008083 // FIXME: Evaluating initializers for large array and record types can cause
8084 // performance problems. Only do so in C++11 for now.
8085 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008086 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008087 return false;
8088
Richard Smithd0b4dd62011-12-19 06:19:21 +00008089 Expr::EvalStatus EStatus;
8090 EStatus.Diag = &Notes;
8091
Richard Smith6d4c6582013-11-05 22:18:15 +00008092 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008093 InitInfo.setEvaluatingDecl(VD, Value);
8094
8095 LValue LVal;
8096 LVal.set(VD);
8097
Richard Smithfddd3842011-12-30 21:15:51 +00008098 // C++11 [basic.start.init]p2:
8099 // Variables with static storage duration or thread storage duration shall be
8100 // zero-initialized before any other initialization takes place.
8101 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008102 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008103 !VD->getType()->isReferenceType()) {
8104 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008105 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008106 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008107 return false;
8108 }
8109
Richard Smith7525ff62013-05-09 07:14:00 +00008110 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8111 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008112 EStatus.HasSideEffects)
8113 return false;
8114
8115 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8116 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008117}
8118
Richard Smith7b553f12011-10-29 00:50:52 +00008119/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8120/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008121bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008122 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008123 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008124}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008125
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008126APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008127 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008128 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008129 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008130 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008131 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008132 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008133 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008134
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008135 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008136}
John McCall864e3962010-05-07 05:32:02 +00008137
Richard Smithe9ff7702013-11-05 22:23:30 +00008138void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008139 bool IsConst;
8140 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008141 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}