blob: 6ad9938906007e5af35bf3955d1d5d19dbed4af2 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Smith745f5142012-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
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
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 Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Chris Lattner87eae5e2008-07-11 22:52:41 +000054/// EvalInfo - This is a private struct used by the evaluator to capture
55/// information about a subexpression as it is folded. It retains information
56/// about the AST context, but also maintains information about the folded
57/// expression.
58///
59/// If an expression could be evaluated, it is still possible it is not a C
60/// "integer constant expression" or constant expression. If not, this struct
61/// captures information about how and why not.
62///
63/// One bit of information passed *into* the request for constant folding
64/// indicates whether the subexpression is "evaluated" or not according to C
65/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
66/// evaluate the expression regardless of what the RHS is, but C only allows
67/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000068namespace {
Richard Smith180f4792011-11-10 06:34:14 +000069 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000070 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000071 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000072
Richard Smith1bf9a9e2011-11-12 22:28:03 +000073 QualType getType(APValue::LValueBase B) {
74 if (!B) return QualType();
75 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
76 return D->getType();
77 return B.get<const Expr*>()->getType();
78 }
79
Richard Smith180f4792011-11-10 06:34:14 +000080 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000081 /// field or base class.
82 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000083 APValue::BaseOrMemberType Value;
84 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000085 return Value;
86 }
87
88 /// Get an LValue path entry, which is known to not be an array index, as a
89 /// field declaration.
90 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// base class declaration.
95 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000096 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000097 }
98 /// Determine whether this LValue path entry for a base class names a virtual
99 /// base class.
100 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +0000101 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +0000102 }
103
Richard Smithb4e85ed2012-01-06 16:39:00 +0000104 /// Find the path length and type of the most-derived subobject in the given
105 /// path, and find the size of the containing array, if any.
106 static
107 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
108 ArrayRef<APValue::LValuePathEntry> Path,
109 uint64_t &ArraySize, QualType &Type) {
110 unsigned MostDerivedLength = 0;
111 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000112 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 if (Type->isArrayType()) {
114 const ConstantArrayType *CAT =
115 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
116 Type = CAT->getElementType();
117 ArraySize = CAT->getSize().getZExtValue();
118 MostDerivedLength = I + 1;
119 } else if (const FieldDecl *FD = getAsField(Path[I])) {
120 Type = FD->getType();
121 ArraySize = 0;
122 MostDerivedLength = I + 1;
123 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000124 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 ArraySize = 0;
126 }
Richard Smith9a17a682011-11-07 05:07:52 +0000127 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000128 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000129 }
130
Richard Smithb4e85ed2012-01-06 16:39:00 +0000131 // The order of this enum is important for diagnostics.
132 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000133 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
134 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000135 };
136
Richard Smith0a3bdb62011-11-04 02:25:55 +0000137 /// A path from a glvalue to a subobject of that glvalue.
138 struct SubobjectDesignator {
139 /// True if the subobject was named in a manner not supported by C++11. Such
140 /// lvalues can still be folded, but they are not core constant expressions
141 /// and we cannot perform lvalue-to-rvalue conversions on them.
142 bool Invalid : 1;
143
Richard Smithb4e85ed2012-01-06 16:39:00 +0000144 /// Is this a pointer one past the end of an object?
145 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146
Richard Smithb4e85ed2012-01-06 16:39:00 +0000147 /// The length of the path to the most-derived object of which this is a
148 /// subobject.
149 unsigned MostDerivedPathLength : 30;
150
151 /// The size of the array of which the most-derived object is an element, or
152 /// 0 if the most-derived object is not an array element.
153 uint64_t MostDerivedArraySize;
154
155 /// The type of the most derived object referred to by this address.
156 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000157
Richard Smith9a17a682011-11-07 05:07:52 +0000158 typedef APValue::LValuePathEntry PathEntry;
159
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 /// The entries on the path from the glvalue to the designated subobject.
161 SmallVector<PathEntry, 8> Entries;
162
Richard Smithb4e85ed2012-01-06 16:39:00 +0000163 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000164
Richard Smithb4e85ed2012-01-06 16:39:00 +0000165 explicit SubobjectDesignator(QualType T)
166 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
167 MostDerivedArraySize(0), MostDerivedType(T) {}
168
169 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
170 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
171 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000172 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000173 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000174 ArrayRef<PathEntry> VEntries = V.getLValuePath();
175 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
176 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000177 MostDerivedPathLength =
178 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
179 V.getLValuePath(), MostDerivedArraySize,
180 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000181 }
182 }
183
Richard Smith0a3bdb62011-11-04 02:25:55 +0000184 void setInvalid() {
185 Invalid = true;
186 Entries.clear();
187 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000188
189 /// Determine whether this is a one-past-the-end pointer.
190 bool isOnePastTheEnd() const {
191 if (IsOnePastTheEnd)
192 return true;
193 if (MostDerivedArraySize &&
194 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
195 return true;
196 return false;
197 }
198
199 /// Check that this refers to a valid subobject.
200 bool isValidSubobject() const {
201 if (Invalid)
202 return false;
203 return !isOnePastTheEnd();
204 }
205 /// Check that this refers to a valid subobject, and if not, produce a
206 /// relevant diagnostic and set the designator as invalid.
207 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
208
209 /// Update this designator to refer to the first element within this array.
210 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000211 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000212 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000214
215 // This is a most-derived object.
216 MostDerivedType = CAT->getElementType();
217 MostDerivedArraySize = CAT->getSize().getZExtValue();
218 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 }
220 /// Update this designator to refer to the given base or member of this
221 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000224 APValue::BaseOrMemberType Value(D, Virtual);
225 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000227
228 // If this isn't a base class, it's a new most-derived object.
229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
230 MostDerivedType = FD->getType();
231 MostDerivedArraySize = 0;
232 MostDerivedPathLength = Entries.size();
233 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000236 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000238 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000239 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000240 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
242 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
243 setInvalid();
244 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 return;
246 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 // [expr.add]p4: For the purposes of these operators, a pointer to a
248 // nonarray object behaves the same as a pointer to the first element of
249 // an array of length one with the type of the object as its element type.
250 if (IsOnePastTheEnd && N == (uint64_t)-1)
251 IsOnePastTheEnd = false;
252 else if (!IsOnePastTheEnd && N == 1)
253 IsOnePastTheEnd = true;
254 else if (N != 0) {
255 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000256 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000257 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000258 }
259 };
260
Richard Smith47a1eed2011-10-29 20:57:55 +0000261 /// A core constant value. This can be the value of any constant expression,
262 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000263 ///
264 /// For an LValue, the base and offset are stored in the APValue subobject,
265 /// but the other information is stored in the SubobjectDesignator. For all
266 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000267 class CCValue : public APValue {
268 typedef llvm::APSInt APSInt;
269 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000270 /// If the value is a reference or pointer into a parameter or temporary,
271 /// this is the corresponding call stack frame.
272 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000273 /// If the value is a reference or pointer, this is a description of how the
274 /// subobject was specified.
275 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000276 public:
Richard Smith177dce72011-11-01 16:57:24 +0000277 struct GlobalValue {};
278
Richard Smith47a1eed2011-10-29 20:57:55 +0000279 CCValue() {}
280 explicit CCValue(const APSInt &I) : APValue(I) {}
281 explicit CCValue(const APFloat &F) : APValue(F) {}
282 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
283 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
284 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000285 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000286 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000287 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000288 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000289 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
290 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000291 CCValue(const ValueDecl *D, bool IsDerivedMember,
292 ArrayRef<const CXXRecordDecl*> Path) :
293 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000294 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
295 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000296
Richard Smith177dce72011-11-01 16:57:24 +0000297 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000298 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000299 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000300 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000301 SubobjectDesignator &getLValueDesignator() {
302 assert(getKind() == LValue);
303 return Designator;
304 }
305 const SubobjectDesignator &getLValueDesignator() const {
306 return const_cast<CCValue*>(this)->getLValueDesignator();
307 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000308 };
309
Richard Smithd0dccea2011-10-28 22:34:42 +0000310 /// A stack frame in the constexpr call stack.
311 struct CallStackFrame {
312 EvalInfo &Info;
313
314 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000315 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000316
Richard Smith08d6e032011-12-16 19:06:07 +0000317 /// CallLoc - The location of the call expression for this call.
318 SourceLocation CallLoc;
319
320 /// Callee - The function which was called.
321 const FunctionDecl *Callee;
322
Richard Smith180f4792011-11-10 06:34:14 +0000323 /// This - The binding for the this pointer in this call, if any.
324 const LValue *This;
325
Richard Smithd0dccea2011-10-28 22:34:42 +0000326 /// ParmBindings - Parameter bindings for this function call, indexed by
327 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000328 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000329
Richard Smithbd552ef2011-10-31 05:52:43 +0000330 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
331 typedef MapTy::const_iterator temp_iterator;
332 /// Temporaries - Temporary lvalues materialized within this stack frame.
333 MapTy Temporaries;
334
Richard Smith08d6e032011-12-16 19:06:07 +0000335 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
336 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000337 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000338 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000339 };
340
Richard Smithdd1f29b2011-12-12 09:28:41 +0000341 /// A partial diagnostic which we might know in advance that we are not going
342 /// to emit.
343 class OptionalDiagnostic {
344 PartialDiagnostic *Diag;
345
346 public:
347 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
348
349 template<typename T>
350 OptionalDiagnostic &operator<<(const T &v) {
351 if (Diag)
352 *Diag << v;
353 return *this;
354 }
Richard Smith789f9b62012-01-31 04:08:20 +0000355
356 OptionalDiagnostic &operator<<(const APSInt &I) {
357 if (Diag) {
358 llvm::SmallVector<char, 32> Buffer;
359 I.toString(Buffer);
360 *Diag << StringRef(Buffer.data(), Buffer.size());
361 }
362 return *this;
363 }
364
365 OptionalDiagnostic &operator<<(const APFloat &F) {
366 if (Diag) {
367 llvm::SmallVector<char, 32> Buffer;
368 F.toString(Buffer);
369 *Diag << StringRef(Buffer.data(), Buffer.size());
370 }
371 return *this;
372 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000373 };
374
Richard Smithbd552ef2011-10-31 05:52:43 +0000375 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000376 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000377
378 /// EvalStatus - Contains information about the evaluation.
379 Expr::EvalStatus &EvalStatus;
380
381 /// CurrentCall - The top of the constexpr call stack.
382 CallStackFrame *CurrentCall;
383
Richard Smithbd552ef2011-10-31 05:52:43 +0000384 /// CallStackDepth - The number of calls in the call stack right now.
385 unsigned CallStackDepth;
386
387 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
388 /// OpaqueValues - Values used as the common expression in a
389 /// BinaryConditionalOperator.
390 MapTy OpaqueValues;
391
392 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000393 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000394 CallStackFrame BottomFrame;
395
Richard Smith180f4792011-11-10 06:34:14 +0000396 /// EvaluatingDecl - This is the declaration whose initializer is being
397 /// evaluated, if any.
398 const VarDecl *EvaluatingDecl;
399
400 /// EvaluatingDeclValue - This is the value being constructed for the
401 /// declaration whose initializer is being evaluated, if any.
402 APValue *EvaluatingDeclValue;
403
Richard Smithc1c5f272011-12-13 06:39:58 +0000404 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
405 /// notes attached to it will also be stored, otherwise they will not be.
406 bool HasActiveDiagnostic;
407
Richard Smith745f5142012-01-27 01:14:48 +0000408 /// CheckingPotentialConstantExpression - Are we checking whether the
409 /// expression is a potential constant expression? If so, some diagnostics
410 /// are suppressed.
411 bool CheckingPotentialConstantExpression;
412
Richard Smithbd552ef2011-10-31 05:52:43 +0000413
414 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000415 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000416 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000417 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
418 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000419
Richard Smithbd552ef2011-10-31 05:52:43 +0000420 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
421 MapTy::const_iterator i = OpaqueValues.find(e);
422 if (i == OpaqueValues.end()) return 0;
423 return &i->second;
424 }
425
Richard Smith180f4792011-11-10 06:34:14 +0000426 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
427 EvaluatingDecl = VD;
428 EvaluatingDeclValue = &Value;
429 }
430
Richard Smithc18c4232011-11-21 19:36:32 +0000431 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
432
Richard Smithc1c5f272011-12-13 06:39:58 +0000433 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000434 // Don't perform any constexpr calls (other than the call we're checking)
435 // when checking a potential constant expression.
436 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
437 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000438 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439 return true;
440 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441 << getLangOpts().ConstexprCallDepth;
442 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000443 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000444
Richard Smithc1c5f272011-12-13 06:39:58 +0000445 private:
446 /// Add a diagnostic to the diagnostics list.
447 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
448 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
449 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
450 return EvalStatus.Diag->back().second;
451 }
452
Richard Smith08d6e032011-12-16 19:06:07 +0000453 /// Add notes containing a call stack to the current point of evaluation.
454 void addCallStack(unsigned Limit);
455
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000457 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000458 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
459 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000460 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000461 // If we have a prior diagnostic, it will be noting that the expression
462 // isn't a constant expression. This diagnostic is more important.
463 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000465 unsigned CallStackNotes = CallStackDepth - 1;
466 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
467 if (Limit)
468 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000469 if (CheckingPotentialConstantExpression)
470 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000471
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000474 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
475 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000476 if (!CheckingPotentialConstantExpression)
477 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000478 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000479 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000480 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000481 return OptionalDiagnostic();
482 }
483
484 /// Diagnose that the evaluation does not produce a C++11 core constant
485 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000486 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
487 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 // Don't override a previous diagnostic.
490 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
491 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000492 return Diag(Loc, DiagId, ExtraNotes);
493 }
494
495 /// Add a note to a prior diagnostic.
496 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
497 if (!HasActiveDiagnostic)
498 return OptionalDiagnostic();
499 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000500 }
Richard Smith099e7f62011-12-19 06:19:21 +0000501
502 /// Add a stack of notes to a prior diagnostic.
503 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
504 if (HasActiveDiagnostic) {
505 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
506 Diags.begin(), Diags.end());
507 }
508 }
Richard Smith745f5142012-01-27 01:14:48 +0000509
510 /// Should we continue evaluation as much as possible after encountering a
511 /// construct which can't be folded?
512 bool keepEvaluatingAfterFailure() {
513 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
514 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000515 };
Richard Smithf15fda02012-02-02 01:16:57 +0000516
517 /// Object used to treat all foldable expressions as constant expressions.
518 struct FoldConstant {
519 bool Enabled;
520
521 explicit FoldConstant(EvalInfo &Info)
522 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
523 !Info.EvalStatus.HasSideEffects) {
524 }
525 // Treat the value we've computed since this object was created as constant.
526 void Fold(EvalInfo &Info) {
527 if (Enabled && !Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects)
529 Info.EvalStatus.Diag->clear();
530 }
531 };
Richard Smith08d6e032011-12-16 19:06:07 +0000532}
Richard Smithbd552ef2011-10-31 05:52:43 +0000533
Richard Smithb4e85ed2012-01-06 16:39:00 +0000534bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
535 CheckSubobjectKind CSK) {
536 if (Invalid)
537 return false;
538 if (isOnePastTheEnd()) {
539 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
540 << CSK;
541 setInvalid();
542 return false;
543 }
544 return true;
545}
546
547void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
548 const Expr *E, uint64_t N) {
549 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
550 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
551 << static_cast<int>(N) << /*array*/ 0
552 << static_cast<unsigned>(MostDerivedArraySize);
553 else
554 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
555 << static_cast<int>(N) << /*non-array*/ 1;
556 setInvalid();
557}
558
Richard Smith08d6e032011-12-16 19:06:07 +0000559CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
560 const FunctionDecl *Callee, const LValue *This,
561 const CCValue *Arguments)
562 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
563 This(This), Arguments(Arguments) {
564 Info.CurrentCall = this;
565 ++Info.CallStackDepth;
566}
567
568CallStackFrame::~CallStackFrame() {
569 assert(Info.CurrentCall == this && "calls retired out of order");
570 --Info.CallStackDepth;
571 Info.CurrentCall = Caller;
572}
573
574/// Produce a string describing the given constexpr call.
575static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
576 unsigned ArgIndex = 0;
577 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000578 !isa<CXXConstructorDecl>(Frame->Callee) &&
579 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000580
581 if (!IsMemberCall)
582 Out << *Frame->Callee << '(';
583
584 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
585 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000586 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Out << ", ";
588
589 const ParmVarDecl *Param = *I;
590 const CCValue &Arg = Frame->Arguments[ArgIndex];
591 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
592 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
593 else {
594 // Deliberately slice off the frame to form an APValue we can print.
595 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
596 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000597 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000598 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
599 }
600
601 if (ArgIndex == 0 && IsMemberCall)
602 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000603 }
604
Richard Smith08d6e032011-12-16 19:06:07 +0000605 Out << ')';
606}
607
608void EvalInfo::addCallStack(unsigned Limit) {
609 // Determine which calls to skip, if any.
610 unsigned ActiveCalls = CallStackDepth - 1;
611 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
612 if (Limit && Limit < ActiveCalls) {
613 SkipStart = Limit / 2 + Limit % 2;
614 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000615 }
616
Richard Smith08d6e032011-12-16 19:06:07 +0000617 // Walk the call stack and add the diagnostics.
618 unsigned CallIdx = 0;
619 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
620 Frame = Frame->Caller, ++CallIdx) {
621 // Skip this call?
622 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
623 if (CallIdx == SkipStart) {
624 // Note that we're skipping calls.
625 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
626 << unsigned(ActiveCalls - Limit);
627 }
628 continue;
629 }
630
631 llvm::SmallVector<char, 128> Buffer;
632 llvm::raw_svector_ostream Out(Buffer);
633 describeCall(Frame, Out);
634 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
635 }
636}
637
638namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000639 struct ComplexValue {
640 private:
641 bool IsInt;
642
643 public:
644 APSInt IntReal, IntImag;
645 APFloat FloatReal, FloatImag;
646
647 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
648
649 void makeComplexFloat() { IsInt = false; }
650 bool isComplexFloat() const { return !IsInt; }
651 APFloat &getComplexFloatReal() { return FloatReal; }
652 APFloat &getComplexFloatImag() { return FloatImag; }
653
654 void makeComplexInt() { IsInt = true; }
655 bool isComplexInt() const { return IsInt; }
656 APSInt &getComplexIntReal() { return IntReal; }
657 APSInt &getComplexIntImag() { return IntImag; }
658
Richard Smith47a1eed2011-10-29 20:57:55 +0000659 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000660 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000661 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000662 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000663 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000664 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000665 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000666 assert(v.isComplexFloat() || v.isComplexInt());
667 if (v.isComplexFloat()) {
668 makeComplexFloat();
669 FloatReal = v.getComplexFloatReal();
670 FloatImag = v.getComplexFloatImag();
671 } else {
672 makeComplexInt();
673 IntReal = v.getComplexIntReal();
674 IntImag = v.getComplexIntImag();
675 }
676 }
John McCallf4cf1a12010-05-07 17:22:02 +0000677 };
John McCallefdb83e2010-05-07 21:00:08 +0000678
679 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000680 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000681 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000682 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000683 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000684
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000685 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000686 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000687 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000688 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000689 SubobjectDesignator &getLValueDesignator() { return Designator; }
690 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000691
Richard Smith47a1eed2011-10-29 20:57:55 +0000692 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000693 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000694 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000695 void setFrom(const CCValue &V) {
696 assert(V.isLValue());
697 Base = V.getLValueBase();
698 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000699 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000700 Designator = V.getLValueDesignator();
701 }
702
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000703 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
704 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000705 Offset = CharUnits::Zero();
706 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000707 Designator = SubobjectDesignator(getType(B));
708 }
709
710 // Check that this LValue is not based on a null pointer. If it is, produce
711 // a diagnostic and mark the designator as invalid.
712 bool checkNullPointer(EvalInfo &Info, const Expr *E,
713 CheckSubobjectKind CSK) {
714 if (Designator.Invalid)
715 return false;
716 if (!Base) {
717 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
718 << CSK;
719 Designator.setInvalid();
720 return false;
721 }
722 return true;
723 }
724
725 // Check this LValue refers to an object. If not, set the designator to be
726 // invalid and emit a diagnostic.
727 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
728 return checkNullPointer(Info, E, CSK) &&
729 Designator.checkSubobject(Info, E, CSK);
730 }
731
732 void addDecl(EvalInfo &Info, const Expr *E,
733 const Decl *D, bool Virtual = false) {
734 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
735 Designator.addDeclUnchecked(D, Virtual);
736 }
737 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
738 checkSubobject(Info, E, CSK_ArrayToPointer);
739 Designator.addArrayUnchecked(CAT);
740 }
741 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
742 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
743 return;
744 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000745 }
John McCallefdb83e2010-05-07 21:00:08 +0000746 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000747
748 struct MemberPtr {
749 MemberPtr() {}
750 explicit MemberPtr(const ValueDecl *Decl) :
751 DeclAndIsDerivedMember(Decl, false), Path() {}
752
753 /// The member or (direct or indirect) field referred to by this member
754 /// pointer, or 0 if this is a null member pointer.
755 const ValueDecl *getDecl() const {
756 return DeclAndIsDerivedMember.getPointer();
757 }
758 /// Is this actually a member of some type derived from the relevant class?
759 bool isDerivedMember() const {
760 return DeclAndIsDerivedMember.getInt();
761 }
762 /// Get the class which the declaration actually lives in.
763 const CXXRecordDecl *getContainingRecord() const {
764 return cast<CXXRecordDecl>(
765 DeclAndIsDerivedMember.getPointer()->getDeclContext());
766 }
767
768 void moveInto(CCValue &V) const {
769 V = CCValue(getDecl(), isDerivedMember(), Path);
770 }
771 void setFrom(const CCValue &V) {
772 assert(V.isMemberPointer());
773 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
774 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
775 Path.clear();
776 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
777 Path.insert(Path.end(), P.begin(), P.end());
778 }
779
780 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
781 /// whether the member is a member of some class derived from the class type
782 /// of the member pointer.
783 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
784 /// Path - The path of base/derived classes from the member declaration's
785 /// class (exclusive) to the class type of the member pointer (inclusive).
786 SmallVector<const CXXRecordDecl*, 4> Path;
787
788 /// Perform a cast towards the class of the Decl (either up or down the
789 /// hierarchy).
790 bool castBack(const CXXRecordDecl *Class) {
791 assert(!Path.empty());
792 const CXXRecordDecl *Expected;
793 if (Path.size() >= 2)
794 Expected = Path[Path.size() - 2];
795 else
796 Expected = getContainingRecord();
797 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
798 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
799 // if B does not contain the original member and is not a base or
800 // derived class of the class containing the original member, the result
801 // of the cast is undefined.
802 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
803 // (D::*). We consider that to be a language defect.
804 return false;
805 }
806 Path.pop_back();
807 return true;
808 }
809 /// Perform a base-to-derived member pointer cast.
810 bool castToDerived(const CXXRecordDecl *Derived) {
811 if (!getDecl())
812 return true;
813 if (!isDerivedMember()) {
814 Path.push_back(Derived);
815 return true;
816 }
817 if (!castBack(Derived))
818 return false;
819 if (Path.empty())
820 DeclAndIsDerivedMember.setInt(false);
821 return true;
822 }
823 /// Perform a derived-to-base member pointer cast.
824 bool castToBase(const CXXRecordDecl *Base) {
825 if (!getDecl())
826 return true;
827 if (Path.empty())
828 DeclAndIsDerivedMember.setInt(true);
829 if (isDerivedMember()) {
830 Path.push_back(Base);
831 return true;
832 }
833 return castBack(Base);
834 }
835 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000836
Richard Smithb02e4622012-02-01 01:42:44 +0000837 /// Compare two member pointers, which are assumed to be of the same type.
838 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
839 if (!LHS.getDecl() || !RHS.getDecl())
840 return !LHS.getDecl() && !RHS.getDecl();
841 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
842 return false;
843 return LHS.Path == RHS.Path;
844 }
845
Richard Smithc1c5f272011-12-13 06:39:58 +0000846 /// Kinds of constant expression checking, for diagnostics.
847 enum CheckConstantExpressionKind {
848 CCEK_Constant, ///< A normal constant.
849 CCEK_ReturnValue, ///< A constexpr function return value.
850 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
851 };
John McCallf4cf1a12010-05-07 17:22:02 +0000852}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000853
Richard Smith47a1eed2011-10-29 20:57:55 +0000854static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000855static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000856 const LValue &This, const Expr *E,
857 CheckConstantExpressionKind CCEK
Richard Smith7ca48502012-02-13 22:16:19 +0000858 = CCEK_Constant,
859 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000860static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
861static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000862static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
863 EvalInfo &Info);
864static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000865static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000866static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000867 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000868static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000869static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000870
871//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000872// Misc utilities
873//===----------------------------------------------------------------------===//
874
Richard Smith180f4792011-11-10 06:34:14 +0000875/// Should this call expression be treated as a string literal?
876static bool IsStringLiteralCall(const CallExpr *E) {
877 unsigned Builtin = E->isBuiltinCall();
878 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
879 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
880}
881
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000882static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000883 // C++11 [expr.const]p3 An address constant expression is a prvalue core
884 // constant expression of pointer type that evaluates to...
885
886 // ... a null pointer value, or a prvalue core constant expression of type
887 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000888 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000889
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000890 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
891 // ... the address of an object with static storage duration,
892 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
893 return VD->hasGlobalStorage();
894 // ... the address of a function,
895 return isa<FunctionDecl>(D);
896 }
897
898 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000899 switch (E->getStmtClass()) {
900 default:
901 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000902 case Expr::CompoundLiteralExprClass:
903 return cast<CompoundLiteralExpr>(E)->isFileScope();
904 // A string literal has static storage duration.
905 case Expr::StringLiteralClass:
906 case Expr::PredefinedExprClass:
907 case Expr::ObjCStringLiteralClass:
908 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000909 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000910 return true;
911 case Expr::CallExprClass:
912 return IsStringLiteralCall(cast<CallExpr>(E));
913 // For GCC compatibility, &&label has static storage duration.
914 case Expr::AddrLabelExprClass:
915 return true;
916 // A Block literal expression may be used as the initialization value for
917 // Block variables at global or local static scope.
918 case Expr::BlockExprClass:
919 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000920 case Expr::ImplicitValueInitExprClass:
921 // FIXME:
922 // We can never form an lvalue with an implicit value initialization as its
923 // base through expression evaluation, so these only appear in one case: the
924 // implicit variable declaration we invent when checking whether a constexpr
925 // constructor can produce a constant expression. We must assume that such
926 // an expression might be a global lvalue.
927 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000928 }
John McCall42c8f872010-05-10 23:27:23 +0000929}
930
Richard Smith9a17a682011-11-07 05:07:52 +0000931/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000932/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000933/// either LValue or CCValue. Return true if we can fold this expression,
934/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000935template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000936static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000937 const T &LVal, APValue &Value,
938 CheckConstantExpressionKind CCEK) {
939 APValue::LValueBase Base = LVal.getLValueBase();
940 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
941
942 if (!IsGlobalLValue(Base)) {
943 if (Info.getLangOpts().CPlusPlus0x) {
944 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
945 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
946 << E->isGLValue() << !Designator.Entries.empty()
947 << !!VD << CCEK << VD;
948 if (VD)
949 Info.Note(VD->getLocation(), diag::note_declared_at);
950 else
951 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
952 diag::note_constexpr_temporary_here);
953 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000954 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000955 }
Richard Smith61e61622012-01-12 06:08:57 +0000956 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000957 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000958 }
Richard Smith9a17a682011-11-07 05:07:52 +0000959
Richard Smithb4e85ed2012-01-06 16:39:00 +0000960 bool IsReferenceType = E->isGLValue();
961
962 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000963 // This is not a core constant expression. An appropriate diagnostic will
964 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000965 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
966 APValue::NoLValuePath());
967 return true;
968 }
969
Richard Smithb4e85ed2012-01-06 16:39:00 +0000970 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
971 Designator.Entries, Designator.IsOnePastTheEnd);
972
973 // Allow address constant expressions to be past-the-end pointers. This is
974 // an extension: the standard requires them to point to an object.
975 if (!IsReferenceType)
976 return true;
977
978 // A reference constant expression must refer to an object.
979 if (!Base) {
980 // FIXME: diagnostic
981 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000982 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000983 }
984
Richard Smithc1c5f272011-12-13 06:39:58 +0000985 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000986 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000987 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
988 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
989 << !Designator.Entries.empty() << !!VD << VD;
990 if (VD)
991 Info.Note(VD->getLocation(), diag::note_declared_at);
992 else
993 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
994 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000995 }
996
Richard Smith9a17a682011-11-07 05:07:52 +0000997 return true;
998}
999
Richard Smith51201882011-12-30 21:15:51 +00001000/// Check that this core constant expression is of literal type, and if not,
1001/// produce an appropriate diagnostic.
1002static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1003 if (!E->isRValue() || E->getType()->isLiteralType())
1004 return true;
1005
1006 // Prvalue constant expressions must be of literal types.
1007 if (Info.getLangOpts().CPlusPlus0x)
1008 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1009 << E->getType();
1010 else
1011 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1012 return false;
1013}
1014
Richard Smith47a1eed2011-10-29 20:57:55 +00001015/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +00001016/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +00001017/// If not, report an appropriate diagnostic. Does not check that the expression
1018/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +00001019static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001020 const CCValue &CCValue, APValue &Value,
1021 CheckConstantExpressionKind CCEK
1022 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001023 if (!CCValue.isLValue()) {
1024 Value = CCValue;
1025 return true;
1026 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001027 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001028}
1029
Richard Smith9e36b532011-10-31 05:11:32 +00001030const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001031 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001032}
1033
1034static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001035 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001036}
1037
Richard Smith65ac5982011-11-01 21:06:14 +00001038static bool IsWeakLValue(const LValue &Value) {
1039 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001040 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001041}
1042
Richard Smithe24f5fc2011-11-17 22:56:20 +00001043static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001044 // A null base expression indicates a null pointer. These are always
1045 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001046 if (!Value.getLValueBase()) {
1047 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001048 return true;
1049 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001050
Richard Smithe24f5fc2011-11-17 22:56:20 +00001051 // We have a non-null base. These are generally known to be true, but if it's
1052 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001053 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001054 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001055 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001056}
1057
Richard Smith47a1eed2011-10-29 20:57:55 +00001058static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001059 switch (Val.getKind()) {
1060 case APValue::Uninitialized:
1061 return false;
1062 case APValue::Int:
1063 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001064 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001065 case APValue::Float:
1066 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001067 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001068 case APValue::ComplexInt:
1069 Result = Val.getComplexIntReal().getBoolValue() ||
1070 Val.getComplexIntImag().getBoolValue();
1071 return true;
1072 case APValue::ComplexFloat:
1073 Result = !Val.getComplexFloatReal().isZero() ||
1074 !Val.getComplexFloatImag().isZero();
1075 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001076 case APValue::LValue:
1077 return EvalPointerValueAsBool(Val, Result);
1078 case APValue::MemberPointer:
1079 Result = Val.getMemberPointerDecl();
1080 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001081 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001082 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001083 case APValue::Struct:
1084 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001085 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001086 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001087 }
1088
Richard Smithc49bd112011-10-28 17:51:58 +00001089 llvm_unreachable("unknown APValue kind");
1090}
1091
1092static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1093 EvalInfo &Info) {
1094 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001095 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001096 if (!Evaluate(Val, Info, E))
1097 return false;
1098 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001099}
1100
Richard Smithc1c5f272011-12-13 06:39:58 +00001101template<typename T>
1102static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1103 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001104 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001105 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001106 return false;
1107}
1108
1109static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1110 QualType SrcType, const APFloat &Value,
1111 QualType DestType, APSInt &Result) {
1112 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001113 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001114 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Richard Smithc1c5f272011-12-13 06:39:58 +00001116 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001117 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001118 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1119 & APFloat::opInvalidOp)
1120 return HandleOverflow(Info, E, Value, DestType);
1121 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001122}
1123
Richard Smithc1c5f272011-12-13 06:39:58 +00001124static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1125 QualType SrcType, QualType DestType,
1126 APFloat &Result) {
1127 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001128 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001129 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1130 APFloat::rmNearestTiesToEven, &ignored)
1131 & APFloat::opOverflow)
1132 return HandleOverflow(Info, E, Value, DestType);
1133 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001134}
1135
Richard Smithf72fccf2012-01-30 22:27:01 +00001136static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1137 QualType DestType, QualType SrcType,
1138 APSInt &Value) {
1139 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001140 APSInt Result = Value;
1141 // Figure out if this is a truncate, extend or noop cast.
1142 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001143 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001144 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001145 return Result;
1146}
1147
Richard Smithc1c5f272011-12-13 06:39:58 +00001148static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1149 QualType SrcType, const APSInt &Value,
1150 QualType DestType, APFloat &Result) {
1151 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1152 if (Result.convertFromAPInt(Value, Value.isSigned(),
1153 APFloat::rmNearestTiesToEven)
1154 & APFloat::opOverflow)
1155 return HandleOverflow(Info, E, Value, DestType);
1156 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001157}
1158
Eli Friedmane6a24e82011-12-22 03:51:45 +00001159static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1160 llvm::APInt &Res) {
1161 CCValue SVal;
1162 if (!Evaluate(SVal, Info, E))
1163 return false;
1164 if (SVal.isInt()) {
1165 Res = SVal.getInt();
1166 return true;
1167 }
1168 if (SVal.isFloat()) {
1169 Res = SVal.getFloat().bitcastToAPInt();
1170 return true;
1171 }
1172 if (SVal.isVector()) {
1173 QualType VecTy = E->getType();
1174 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1175 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1176 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1177 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1178 Res = llvm::APInt::getNullValue(VecSize);
1179 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1180 APValue &Elt = SVal.getVectorElt(i);
1181 llvm::APInt EltAsInt;
1182 if (Elt.isInt()) {
1183 EltAsInt = Elt.getInt();
1184 } else if (Elt.isFloat()) {
1185 EltAsInt = Elt.getFloat().bitcastToAPInt();
1186 } else {
1187 // Don't try to handle vectors of anything other than int or float
1188 // (not sure if it's possible to hit this case).
1189 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1190 return false;
1191 }
1192 unsigned BaseEltSize = EltAsInt.getBitWidth();
1193 if (BigEndian)
1194 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1195 else
1196 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1197 }
1198 return true;
1199 }
1200 // Give up if the input isn't an int, float, or vector. For example, we
1201 // reject "(v4i16)(intptr_t)&a".
1202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1203 return false;
1204}
1205
Richard Smithb4e85ed2012-01-06 16:39:00 +00001206/// Cast an lvalue referring to a base subobject to a derived class, by
1207/// truncating the lvalue's path to the given length.
1208static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1209 const RecordDecl *TruncatedType,
1210 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001211 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001212
1213 // Check we actually point to a derived class object.
1214 if (TruncatedElements == D.Entries.size())
1215 return true;
1216 assert(TruncatedElements >= D.MostDerivedPathLength &&
1217 "not casting to a derived class");
1218 if (!Result.checkSubobject(Info, E, CSK_Derived))
1219 return false;
1220
1221 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001222 const RecordDecl *RD = TruncatedType;
1223 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001224 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1225 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001226 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001227 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001228 else
Richard Smith180f4792011-11-10 06:34:14 +00001229 Result.Offset -= Layout.getBaseClassOffset(Base);
1230 RD = Base;
1231 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001232 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001233 return true;
1234}
1235
Richard Smithb4e85ed2012-01-06 16:39:00 +00001236static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001237 const CXXRecordDecl *Derived,
1238 const CXXRecordDecl *Base,
1239 const ASTRecordLayout *RL = 0) {
1240 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1241 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001242 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001243}
1244
Richard Smithb4e85ed2012-01-06 16:39:00 +00001245static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001246 const CXXRecordDecl *DerivedDecl,
1247 const CXXBaseSpecifier *Base) {
1248 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1249
1250 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001251 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001252 return true;
1253 }
1254
Richard Smithb4e85ed2012-01-06 16:39:00 +00001255 SubobjectDesignator &D = Obj.Designator;
1256 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001257 return false;
1258
Richard Smithb4e85ed2012-01-06 16:39:00 +00001259 // Extract most-derived object and corresponding type.
1260 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1261 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1262 return false;
1263
1264 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001265 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1266 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001267 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001268 return true;
1269}
1270
1271/// Update LVal to refer to the given field, which must be a member of the type
1272/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001274 const FieldDecl *FD,
1275 const ASTRecordLayout *RL = 0) {
1276 if (!RL)
1277 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1278
1279 unsigned I = FD->getFieldIndex();
1280 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001281 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001282}
1283
Richard Smithd9b02e72012-01-25 22:15:11 +00001284/// Update LVal to refer to the given indirect field.
1285static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1286 LValue &LVal,
1287 const IndirectFieldDecl *IFD) {
1288 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1289 CE = IFD->chain_end(); C != CE; ++C)
1290 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1291}
1292
Richard Smith180f4792011-11-10 06:34:14 +00001293/// Get the size of the given type in char units.
1294static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1295 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1296 // extension.
1297 if (Type->isVoidType() || Type->isFunctionType()) {
1298 Size = CharUnits::One();
1299 return true;
1300 }
1301
1302 if (!Type->isConstantSizeType()) {
1303 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001304 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001305 return false;
1306 }
1307
1308 Size = Info.Ctx.getTypeSizeInChars(Type);
1309 return true;
1310}
1311
1312/// Update a pointer value to model pointer arithmetic.
1313/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001314/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001315/// \param LVal - The pointer value to be updated.
1316/// \param EltTy - The pointee type represented by LVal.
1317/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1319 LValue &LVal, QualType EltTy,
1320 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001321 CharUnits SizeOfPointee;
1322 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1323 return false;
1324
1325 // Compute the new offset in the appropriate width.
1326 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001328 return true;
1329}
1330
Richard Smith03f96112011-10-24 17:54:18 +00001331/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001332static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1333 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001334 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001335 // If this is a parameter to an active constexpr function call, perform
1336 // argument substitution.
1337 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001338 // Assume arguments of a potential constant expression are unknown
1339 // constant expressions.
1340 if (Info.CheckingPotentialConstantExpression)
1341 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001342 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001343 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001344 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001345 }
Richard Smith177dce72011-11-01 16:57:24 +00001346 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1347 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001348 }
Richard Smith03f96112011-10-24 17:54:18 +00001349
Richard Smith099e7f62011-12-19 06:19:21 +00001350 // Dig out the initializer, and use the declaration which it's attached to.
1351 const Expr *Init = VD->getAnyInitializer(VD);
1352 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001353 // If we're checking a potential constant expression, the variable could be
1354 // initialized later.
1355 if (!Info.CheckingPotentialConstantExpression)
1356 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001357 return false;
1358 }
1359
Richard Smith180f4792011-11-10 06:34:14 +00001360 // If we're currently evaluating the initializer of this declaration, use that
1361 // in-flight value.
1362 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001363 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1364 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001365 return !Result.isUninit();
1366 }
1367
Richard Smith65ac5982011-11-01 21:06:14 +00001368 // Never evaluate the initializer of a weak variable. We can't be sure that
1369 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001370 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001371 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001372 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001373 }
Richard Smith65ac5982011-11-01 21:06:14 +00001374
Richard Smith099e7f62011-12-19 06:19:21 +00001375 // Check that we can fold the initializer. In C++, we will have already done
1376 // this in the cases where it matters for conformance.
1377 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1378 if (!VD->evaluateValue(Notes)) {
1379 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1380 Notes.size() + 1) << VD;
1381 Info.Note(VD->getLocation(), diag::note_declared_at);
1382 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001383 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001384 } else if (!VD->checkInitIsICE()) {
1385 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1386 Notes.size() + 1) << VD;
1387 Info.Note(VD->getLocation(), diag::note_declared_at);
1388 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001389 }
Richard Smith03f96112011-10-24 17:54:18 +00001390
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001392 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001393}
1394
Richard Smithc49bd112011-10-28 17:51:58 +00001395static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001396 Qualifiers Quals = T.getQualifiers();
1397 return Quals.hasConst() && !Quals.hasVolatile();
1398}
1399
Richard Smith59efe262011-11-11 04:05:33 +00001400/// Get the base index of the given base class within an APValue representing
1401/// the given derived class.
1402static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1403 const CXXRecordDecl *Base) {
1404 Base = Base->getCanonicalDecl();
1405 unsigned Index = 0;
1406 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1407 E = Derived->bases_end(); I != E; ++I, ++Index) {
1408 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1409 return Index;
1410 }
1411
1412 llvm_unreachable("base class missing from derived class's bases list");
1413}
1414
Richard Smithcc5d4f62011-11-07 09:22:26 +00001415/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001416static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1417 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001418 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001419 if (Sub.Invalid)
1420 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001421 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001422 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001423 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001424 (unsigned)diag::note_constexpr_read_past_end :
1425 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001426 return false;
1427 }
Richard Smithf64699e2011-11-11 08:28:03 +00001428 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001429 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001430 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1431 // This object might be initialized later.
1432 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001433
1434 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1435 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001436 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001437 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001438 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001439 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001440 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001441 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001442 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001444 // Note, it should not be possible to form a pointer with a valid
1445 // designator which points more than one past the end of the array.
1446 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001447 (unsigned)diag::note_constexpr_read_past_end :
1448 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001449 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001450 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001451 if (O->getArrayInitializedElts() > Index)
1452 O = &O->getArrayInitializedElt(Index);
1453 else
1454 O = &O->getArrayFiller();
1455 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001456 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001457 if (Field->isMutable()) {
1458 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1459 << Field;
1460 Info.Note(Field->getLocation(), diag::note_declared_at);
1461 return false;
1462 }
1463
Richard Smith180f4792011-11-10 06:34:14 +00001464 // Next subobject is a class, struct or union field.
1465 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1466 if (RD->isUnion()) {
1467 const FieldDecl *UnionField = O->getUnionField();
1468 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001469 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001470 Info.Diag(E->getExprLoc(),
1471 diag::note_constexpr_read_inactive_union_member)
1472 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001473 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001474 }
Richard Smith180f4792011-11-10 06:34:14 +00001475 O = &O->getUnionValue();
1476 } else
1477 O = &O->getStructField(Field->getFieldIndex());
1478 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001479
1480 if (ObjType.isVolatileQualified()) {
1481 if (Info.getLangOpts().CPlusPlus) {
1482 // FIXME: Include a description of the path to the volatile subobject.
1483 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1484 << 2 << Field;
1485 Info.Note(Field->getLocation(), diag::note_declared_at);
1486 } else {
1487 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1488 }
1489 return false;
1490 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001491 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001492 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001493 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1494 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1495 O = &O->getStructBase(getBaseIndex(Derived, Base));
1496 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001497 }
Richard Smith180f4792011-11-10 06:34:14 +00001498
Richard Smithf48fdb02011-12-09 22:58:01 +00001499 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001500 if (!Info.CheckingPotentialConstantExpression)
1501 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001502 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001503 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001504 }
1505
Richard Smithb4e85ed2012-01-06 16:39:00 +00001506 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001507 return true;
1508}
1509
Richard Smithf15fda02012-02-02 01:16:57 +00001510/// Find the position where two subobject designators diverge, or equivalently
1511/// the length of the common initial subsequence.
1512static unsigned FindDesignatorMismatch(QualType ObjType,
1513 const SubobjectDesignator &A,
1514 const SubobjectDesignator &B,
1515 bool &WasArrayIndex) {
1516 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1517 for (/**/; I != N; ++I) {
1518 if (!ObjType.isNull() && ObjType->isArrayType()) {
1519 // Next subobject is an array element.
1520 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1521 WasArrayIndex = true;
1522 return I;
1523 }
1524 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1525 } else {
1526 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1527 WasArrayIndex = false;
1528 return I;
1529 }
1530 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1531 // Next subobject is a field.
1532 ObjType = FD->getType();
1533 else
1534 // Next subobject is a base class.
1535 ObjType = QualType();
1536 }
1537 }
1538 WasArrayIndex = false;
1539 return I;
1540}
1541
1542/// Determine whether the given subobject designators refer to elements of the
1543/// same array object.
1544static bool AreElementsOfSameArray(QualType ObjType,
1545 const SubobjectDesignator &A,
1546 const SubobjectDesignator &B) {
1547 if (A.Entries.size() != B.Entries.size())
1548 return false;
1549
1550 bool IsArray = A.MostDerivedArraySize != 0;
1551 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1552 // A is a subobject of the array element.
1553 return false;
1554
1555 // If A (and B) designates an array element, the last entry will be the array
1556 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1557 // of length 1' case, and the entire path must match.
1558 bool WasArrayIndex;
1559 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1560 return CommonLength >= A.Entries.size() - IsArray;
1561}
1562
Richard Smith180f4792011-11-10 06:34:14 +00001563/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1564/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1565/// for looking up the glvalue referred to by an entity of reference type.
1566///
1567/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001568/// \param Conv - The expression for which we are performing the conversion.
1569/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001570/// \param Type - The type we expect this conversion to produce, before
1571/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001572/// \param LVal - The glvalue on which we are attempting to perform this action.
1573/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001574static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1575 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001576 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001577 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1578 if (!Info.getLangOpts().CPlusPlus)
1579 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1580
Richard Smithb4e85ed2012-01-06 16:39:00 +00001581 if (LVal.Designator.Invalid)
1582 // A diagnostic will have already been produced.
1583 return false;
1584
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001585 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001586 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001587 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001588
Richard Smithf48fdb02011-12-09 22:58:01 +00001589 if (!LVal.Base) {
1590 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001591 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1592 return false;
1593 }
1594
1595 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1596 // is not a constant expression (even if the object is non-volatile). We also
1597 // apply this rule to C++98, in order to conform to the expected 'volatile'
1598 // semantics.
1599 if (Type.isVolatileQualified()) {
1600 if (Info.getLangOpts().CPlusPlus)
1601 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1602 else
1603 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001604 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001605 }
Richard Smithc49bd112011-10-28 17:51:58 +00001606
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001607 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001608 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1609 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001610 // expressions are constant expressions too. Inside constexpr functions,
1611 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001612 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001613 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001614 if (const VarDecl *VDef = VD->getDefinition())
1615 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001616 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001617 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001618 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001619 }
1620
Richard Smith7098cbd2011-12-21 05:04:46 +00001621 // DR1313: If the object is volatile-qualified but the glvalue was not,
1622 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001623 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001624 if (VT.isVolatileQualified()) {
1625 if (Info.getLangOpts().CPlusPlus) {
1626 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1627 Info.Note(VD->getLocation(), diag::note_declared_at);
1628 } else {
1629 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001630 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001631 return false;
1632 }
1633
1634 if (!isa<ParmVarDecl>(VD)) {
1635 if (VD->isConstexpr()) {
1636 // OK, we can read this variable.
1637 } else if (VT->isIntegralOrEnumerationType()) {
1638 if (!VT.isConstQualified()) {
1639 if (Info.getLangOpts().CPlusPlus) {
1640 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1641 Info.Note(VD->getLocation(), diag::note_declared_at);
1642 } else {
1643 Info.Diag(Loc);
1644 }
1645 return false;
1646 }
1647 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1648 // We support folding of const floating-point types, in order to make
1649 // static const data members of such types (supported as an extension)
1650 // more useful.
1651 if (Info.getLangOpts().CPlusPlus0x) {
1652 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1653 Info.Note(VD->getLocation(), diag::note_declared_at);
1654 } else {
1655 Info.CCEDiag(Loc);
1656 }
1657 } else {
1658 // FIXME: Allow folding of values of any literal type in all languages.
1659 if (Info.getLangOpts().CPlusPlus0x) {
1660 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1661 Info.Note(VD->getLocation(), diag::note_declared_at);
1662 } else {
1663 Info.Diag(Loc);
1664 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001665 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001666 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001667 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001668
Richard Smithf48fdb02011-12-09 22:58:01 +00001669 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001670 return false;
1671
Richard Smith47a1eed2011-10-29 20:57:55 +00001672 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001673 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001674
1675 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1676 // conversion. This happens when the declaration and the lvalue should be
1677 // considered synonymous, for instance when initializing an array of char
1678 // from a string literal. Continue as if the initializer lvalue was the
1679 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001680 assert(RVal.getLValueOffset().isZero() &&
1681 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001682 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001683 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001684 }
1685
Richard Smith7098cbd2011-12-21 05:04:46 +00001686 // Volatile temporary objects cannot be read in constant expressions.
1687 if (Base->getType().isVolatileQualified()) {
1688 if (Info.getLangOpts().CPlusPlus) {
1689 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1690 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1691 } else {
1692 Info.Diag(Loc);
1693 }
1694 return false;
1695 }
1696
Richard Smith0a3bdb62011-11-04 02:25:55 +00001697 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1698 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1699 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001700 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001701 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001702 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001703 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001704
1705 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001706 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001707 const ConstantArrayType *CAT =
1708 Info.Ctx.getAsConstantArrayType(S->getType());
1709 if (Index >= CAT->getSize().getZExtValue()) {
1710 // Note, it should not be possible to form a pointer which points more
1711 // than one past the end of the array without producing a prior const expr
1712 // diagnostic.
1713 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001714 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001715 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001716 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1717 Type->isUnsignedIntegerType());
1718 if (Index < S->getLength())
1719 Value = S->getCodeUnit(Index);
1720 RVal = CCValue(Value);
1721 return true;
1722 }
1723
Richard Smithcc5d4f62011-11-07 09:22:26 +00001724 if (Frame) {
1725 // If this is a temporary expression with a nontrivial initializer, grab the
1726 // value from the relevant stack frame.
1727 RVal = Frame->Temporaries[Base];
1728 } else if (const CompoundLiteralExpr *CLE
1729 = dyn_cast<CompoundLiteralExpr>(Base)) {
1730 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1731 // initializer until now for such expressions. Such an expression can't be
1732 // an ICE in C, so this only matters for fold.
1733 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1734 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1735 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001736 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001737 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001738 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001739 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001740
Richard Smithf48fdb02011-12-09 22:58:01 +00001741 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1742 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001743}
1744
Richard Smith59efe262011-11-11 04:05:33 +00001745/// Build an lvalue for the object argument of a member function call.
1746static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1747 LValue &This) {
1748 if (Object->getType()->isPointerType())
1749 return EvaluatePointer(Object, This, Info);
1750
1751 if (Object->isGLValue())
1752 return EvaluateLValue(Object, This, Info);
1753
Richard Smithe24f5fc2011-11-17 22:56:20 +00001754 if (Object->getType()->isLiteralType())
1755 return EvaluateTemporary(Object, This, Info);
1756
1757 return false;
1758}
1759
1760/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1761/// lvalue referring to the result.
1762///
1763/// \param Info - Information about the ongoing evaluation.
1764/// \param BO - The member pointer access operation.
1765/// \param LV - Filled in with a reference to the resulting object.
1766/// \param IncludeMember - Specifies whether the member itself is included in
1767/// the resulting LValue subobject designator. This is not possible when
1768/// creating a bound member function.
1769/// \return The field or method declaration to which the member pointer refers,
1770/// or 0 if evaluation fails.
1771static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1772 const BinaryOperator *BO,
1773 LValue &LV,
1774 bool IncludeMember = true) {
1775 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1776
Richard Smith745f5142012-01-27 01:14:48 +00001777 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1778 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001779 return 0;
1780
1781 MemberPtr MemPtr;
1782 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1783 return 0;
1784
1785 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1786 // member value, the behavior is undefined.
1787 if (!MemPtr.getDecl())
1788 return 0;
1789
Richard Smith745f5142012-01-27 01:14:48 +00001790 if (!EvalObjOK)
1791 return 0;
1792
Richard Smithe24f5fc2011-11-17 22:56:20 +00001793 if (MemPtr.isDerivedMember()) {
1794 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001795 // The end of the derived-to-base path for the base object must match the
1796 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001797 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001798 LV.Designator.Entries.size())
1799 return 0;
1800 unsigned PathLengthToMember =
1801 LV.Designator.Entries.size() - MemPtr.Path.size();
1802 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1803 const CXXRecordDecl *LVDecl = getAsBaseClass(
1804 LV.Designator.Entries[PathLengthToMember + I]);
1805 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1806 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1807 return 0;
1808 }
1809
1810 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001811 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1812 PathLengthToMember))
1813 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001814 } else if (!MemPtr.Path.empty()) {
1815 // Extend the LValue path with the member pointer's path.
1816 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1817 MemPtr.Path.size() + IncludeMember);
1818
1819 // Walk down to the appropriate base class.
1820 QualType LVType = BO->getLHS()->getType();
1821 if (const PointerType *PT = LVType->getAs<PointerType>())
1822 LVType = PT->getPointeeType();
1823 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1824 assert(RD && "member pointer access on non-class-type expression");
1825 // The first class in the path is that of the lvalue.
1826 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1827 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001828 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001829 RD = Base;
1830 }
1831 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001832 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001833 }
1834
1835 // Add the member. Note that we cannot build bound member functions here.
1836 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001837 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1838 HandleLValueMember(Info, BO, LV, FD);
1839 else if (const IndirectFieldDecl *IFD =
1840 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1841 HandleLValueIndirectMember(Info, BO, LV, IFD);
1842 else
1843 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001844 }
1845
1846 return MemPtr.getDecl();
1847}
1848
1849/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1850/// the provided lvalue, which currently refers to the base object.
1851static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1852 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001853 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001854 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001855 return false;
1856
Richard Smithb4e85ed2012-01-06 16:39:00 +00001857 QualType TargetQT = E->getType();
1858 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1859 TargetQT = PT->getPointeeType();
1860
1861 // Check this cast lands within the final derived-to-base subobject path.
1862 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1863 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1864 << D.MostDerivedType << TargetQT;
1865 return false;
1866 }
1867
Richard Smithe24f5fc2011-11-17 22:56:20 +00001868 // Check the type of the final cast. We don't need to check the path,
1869 // since a cast can only be formed if the path is unique.
1870 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001871 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1872 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001873 if (NewEntriesSize == D.MostDerivedPathLength)
1874 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1875 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001876 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001877 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1878 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1879 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001880 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001881 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001882
1883 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001884 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001885}
1886
Mike Stumpc4c90452009-10-27 22:09:17 +00001887namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001888enum EvalStmtResult {
1889 /// Evaluation failed.
1890 ESR_Failed,
1891 /// Hit a 'return' statement.
1892 ESR_Returned,
1893 /// Evaluation succeeded.
1894 ESR_Succeeded
1895};
1896}
1897
1898// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001899static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001900 const Stmt *S) {
1901 switch (S->getStmtClass()) {
1902 default:
1903 return ESR_Failed;
1904
1905 case Stmt::NullStmtClass:
1906 case Stmt::DeclStmtClass:
1907 return ESR_Succeeded;
1908
Richard Smithc1c5f272011-12-13 06:39:58 +00001909 case Stmt::ReturnStmtClass: {
1910 CCValue CCResult;
1911 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1912 if (!Evaluate(CCResult, Info, RetExpr) ||
1913 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1914 CCEK_ReturnValue))
1915 return ESR_Failed;
1916 return ESR_Returned;
1917 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001918
1919 case Stmt::CompoundStmtClass: {
1920 const CompoundStmt *CS = cast<CompoundStmt>(S);
1921 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1922 BE = CS->body_end(); BI != BE; ++BI) {
1923 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1924 if (ESR != ESR_Succeeded)
1925 return ESR;
1926 }
1927 return ESR_Succeeded;
1928 }
1929 }
1930}
1931
Richard Smith61802452011-12-22 02:22:31 +00001932/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1933/// default constructor. If so, we'll fold it whether or not it's marked as
1934/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1935/// so we need special handling.
1936static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001937 const CXXConstructorDecl *CD,
1938 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001939 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1940 return false;
1941
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001942 // Value-initialization does not call a trivial default constructor, so such a
1943 // call is a core constant expression whether or not the constructor is
1944 // constexpr.
1945 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001946 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001947 // FIXME: If DiagDecl is an implicitly-declared special member function,
1948 // we should be much more explicit about why it's not constexpr.
1949 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1950 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1951 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001952 } else {
1953 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1954 }
1955 }
1956 return true;
1957}
1958
Richard Smithc1c5f272011-12-13 06:39:58 +00001959/// CheckConstexprFunction - Check that a function can be called in a constant
1960/// expression.
1961static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1962 const FunctionDecl *Declaration,
1963 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001964 // Potential constant expressions can contain calls to declared, but not yet
1965 // defined, constexpr functions.
1966 if (Info.CheckingPotentialConstantExpression && !Definition &&
1967 Declaration->isConstexpr())
1968 return false;
1969
Richard Smithc1c5f272011-12-13 06:39:58 +00001970 // Can we evaluate this function call?
1971 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1972 return true;
1973
1974 if (Info.getLangOpts().CPlusPlus0x) {
1975 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001976 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1977 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001978 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1979 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1980 << DiagDecl;
1981 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1982 } else {
1983 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1984 }
1985 return false;
1986}
1987
Richard Smith180f4792011-11-10 06:34:14 +00001988namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001989typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001990}
1991
1992/// EvaluateArgs - Evaluate the arguments to a function call.
1993static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1994 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001995 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001996 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001997 I != E; ++I) {
1998 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1999 // If we're checking for a potential constant expression, evaluate all
2000 // initializers even if some of them fail.
2001 if (!Info.keepEvaluatingAfterFailure())
2002 return false;
2003 Success = false;
2004 }
2005 }
2006 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002007}
2008
Richard Smithd0dccea2011-10-28 22:34:42 +00002009/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002010static bool HandleFunctionCall(SourceLocation CallLoc,
2011 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002012 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00002013 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002014 ArgVector ArgValues(Args.size());
2015 if (!EvaluateArgs(Args, ArgValues, Info))
2016 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002017
Richard Smith745f5142012-01-27 01:14:48 +00002018 if (!Info.CheckCallLimit(CallLoc))
2019 return false;
2020
2021 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002022 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2023}
2024
Richard Smith180f4792011-11-10 06:34:14 +00002025/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002026static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002027 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002028 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002029 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002030 ArgVector ArgValues(Args.size());
2031 if (!EvaluateArgs(Args, ArgValues, Info))
2032 return false;
2033
Richard Smith745f5142012-01-27 01:14:48 +00002034 if (!Info.CheckCallLimit(CallLoc))
2035 return false;
2036
Richard Smith86c3ae42012-02-13 03:54:03 +00002037 const CXXRecordDecl *RD = Definition->getParent();
2038 if (RD->getNumVBases()) {
2039 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2040 return false;
2041 }
2042
Richard Smith745f5142012-01-27 01:14:48 +00002043 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002044
2045 // If it's a delegating constructor, just delegate.
2046 if (Definition->isDelegatingConstructor()) {
2047 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2048 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2049 }
2050
Richard Smith610a60c2012-01-10 04:32:03 +00002051 // For a trivial copy or move constructor, perform an APValue copy. This is
2052 // essential for unions, where the operations performed by the constructor
2053 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002054 if (Definition->isDefaulted() &&
2055 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2056 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2057 LValue RHS;
2058 RHS.setFrom(ArgValues[0]);
2059 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002060 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2061 RHS, Value))
2062 return false;
2063 assert((Value.isStruct() || Value.isUnion()) &&
2064 "trivial copy/move from non-class type?");
2065 // Any CCValue of class type must already be a constant expression.
2066 Result = Value;
2067 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002068 }
2069
2070 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002071 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002072 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2073 std::distance(RD->field_begin(), RD->field_end()));
2074
2075 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2076
Richard Smith745f5142012-01-27 01:14:48 +00002077 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002078 unsigned BasesSeen = 0;
2079#ifndef NDEBUG
2080 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2081#endif
2082 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2083 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002084 LValue Subobject = This;
2085 APValue *Value = &Result;
2086
2087 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002088 if ((*I)->isBaseInitializer()) {
2089 QualType BaseType((*I)->getBaseClass(), 0);
2090#ifndef NDEBUG
2091 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002092 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002093 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2094 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2095 "base class initializers not in expected order");
2096 ++BaseIt;
2097#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002098 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002099 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002100 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002101 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002102 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002103 if (RD->isUnion()) {
2104 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002105 Value = &Result.getUnionValue();
2106 } else {
2107 Value = &Result.getStructField(FD->getFieldIndex());
2108 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002109 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002110 // Walk the indirect field decl's chain to find the object to initialize,
2111 // and make sure we've initialized every step along it.
2112 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2113 CE = IFD->chain_end();
2114 C != CE; ++C) {
2115 FieldDecl *FD = cast<FieldDecl>(*C);
2116 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2117 // Switch the union field if it differs. This happens if we had
2118 // preceding zero-initialization, and we're now initializing a union
2119 // subobject other than the first.
2120 // FIXME: In this case, the values of the other subobjects are
2121 // specified, since zero-initialization sets all padding bits to zero.
2122 if (Value->isUninit() ||
2123 (Value->isUnion() && Value->getUnionField() != FD)) {
2124 if (CD->isUnion())
2125 *Value = APValue(FD);
2126 else
2127 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2128 std::distance(CD->field_begin(), CD->field_end()));
2129 }
Richard Smith745f5142012-01-27 01:14:48 +00002130 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002131 if (CD->isUnion())
2132 Value = &Value->getUnionValue();
2133 else
2134 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002135 }
Richard Smith180f4792011-11-10 06:34:14 +00002136 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002137 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002138 }
Richard Smith745f5142012-01-27 01:14:48 +00002139
2140 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2141 (*I)->isBaseInitializer()
2142 ? CCEK_Constant : CCEK_MemberInit)) {
2143 // If we're checking for a potential constant expression, evaluate all
2144 // initializers even if some of them fail.
2145 if (!Info.keepEvaluatingAfterFailure())
2146 return false;
2147 Success = false;
2148 }
Richard Smith180f4792011-11-10 06:34:14 +00002149 }
2150
Richard Smith745f5142012-01-27 01:14:48 +00002151 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002152}
2153
Richard Smithd0dccea2011-10-28 22:34:42 +00002154namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002155class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002156 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002157 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002158public:
2159
Richard Smith1e12c592011-10-16 21:26:27 +00002160 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002161
2162 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002163 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002164 return true;
2165 }
2166
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002167 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2168 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002169 return Visit(E->getResultExpr());
2170 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002171 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002172 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002173 return true;
2174 return false;
2175 }
John McCallf85e1932011-06-15 23:02:42 +00002176 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002177 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002178 return true;
2179 return false;
2180 }
2181 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002182 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002183 return true;
2184 return false;
2185 }
2186
Mike Stumpc4c90452009-10-27 22:09:17 +00002187 // We don't want to evaluate BlockExprs multiple times, as they generate
2188 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2190 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2191 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002192 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002193 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2194 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2195 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2196 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2197 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2198 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002199 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002200 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002201 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002202 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002203 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002204 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2205 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2206 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2207 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002208 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002209 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2210 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2211 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2212 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2213 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002214 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002215 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002216 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002217 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002218 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002219
2220 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002221 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002222 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2223 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002224 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002225 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002226 return false;
2227 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002229 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002230};
2231
John McCall56ca35d2011-02-17 10:25:35 +00002232class OpaqueValueEvaluation {
2233 EvalInfo &info;
2234 OpaqueValueExpr *opaqueValue;
2235
2236public:
2237 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2238 Expr *value)
2239 : info(info), opaqueValue(opaqueValue) {
2240
2241 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002242 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002243 this->opaqueValue = 0;
2244 return;
2245 }
John McCall56ca35d2011-02-17 10:25:35 +00002246 }
2247
2248 bool hasError() const { return opaqueValue == 0; }
2249
2250 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002251 // FIXME: This will not work for recursive constexpr functions using opaque
2252 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002253 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2254 }
2255};
2256
Mike Stumpc4c90452009-10-27 22:09:17 +00002257} // end anonymous namespace
2258
Eli Friedman4efaa272008-11-12 09:44:48 +00002259//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260// Generic Evaluation
2261//===----------------------------------------------------------------------===//
2262namespace {
2263
Richard Smithf48fdb02011-12-09 22:58:01 +00002264// FIXME: RetTy is always bool. Remove it.
2265template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266class ExprEvaluatorBase
2267 : public ConstStmtVisitor<Derived, RetTy> {
2268private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002269 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002270 return static_cast<Derived*>(this)->Success(V, E);
2271 }
Richard Smith51201882011-12-30 21:15:51 +00002272 RetTy DerivedZeroInitialization(const Expr *E) {
2273 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002274 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275
2276protected:
2277 EvalInfo &Info;
2278 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2279 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2280
Richard Smithdd1f29b2011-12-12 09:28:41 +00002281 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002282 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002283 }
2284
2285 /// Report an evaluation error. This should only be called when an error is
2286 /// first discovered. When propagating an error, just return false.
2287 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002288 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002289 return false;
2290 }
2291 bool Error(const Expr *E) {
2292 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2293 }
2294
Richard Smith51201882011-12-30 21:15:51 +00002295 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002296
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002297public:
2298 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2299
2300 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002301 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002302 }
2303 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002304 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 }
2306
2307 RetTy VisitParenExpr(const ParenExpr *E)
2308 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2309 RetTy VisitUnaryExtension(const UnaryOperator *E)
2310 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2311 RetTy VisitUnaryPlus(const UnaryOperator *E)
2312 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2313 RetTy VisitChooseExpr(const ChooseExpr *E)
2314 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2315 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2316 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002317 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2318 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002319 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2320 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002321 // We cannot create any objects for which cleanups are required, so there is
2322 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2323 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2324 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002325
Richard Smithc216a012011-12-12 12:46:16 +00002326 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2327 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2328 return static_cast<Derived*>(this)->VisitCastExpr(E);
2329 }
2330 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2331 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2332 return static_cast<Derived*>(this)->VisitCastExpr(E);
2333 }
2334
Richard Smithe24f5fc2011-11-17 22:56:20 +00002335 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2336 switch (E->getOpcode()) {
2337 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002338 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002339
2340 case BO_Comma:
2341 VisitIgnoredValue(E->getLHS());
2342 return StmtVisitorTy::Visit(E->getRHS());
2343
2344 case BO_PtrMemD:
2345 case BO_PtrMemI: {
2346 LValue Obj;
2347 if (!HandleMemberPointerAccess(Info, E, Obj))
2348 return false;
2349 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002350 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002351 return false;
2352 return DerivedSuccess(Result, E);
2353 }
2354 }
2355 }
2356
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002357 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2358 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2359 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002361
2362 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002363 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002364 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002365
2366 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2367 }
2368
2369 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002370 bool IsBcpCall = false;
2371 // If the condition (ignoring parens) is a __builtin_constant_p call,
2372 // the result is a constant expression if it can be folded without
2373 // side-effects. This is an important GNU extension. See GCC PR38377
2374 // for discussion.
2375 if (const CallExpr *CallCE =
2376 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2377 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2378 IsBcpCall = true;
2379
2380 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2381 // constant expression; we can't check whether it's potentially foldable.
2382 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2383 return false;
2384
2385 FoldConstant Fold(Info);
2386
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002388 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002389 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002390
Richard Smithc49bd112011-10-28 17:51:58 +00002391 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002392 if (!StmtVisitorTy::Visit(EvalExpr))
2393 return false;
2394
2395 if (IsBcpCall)
2396 Fold.Fold(Info);
2397
2398 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002399 }
2400
2401 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002402 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002403 if (!Value) {
2404 const Expr *Source = E->getSourceExpr();
2405 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002406 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002407 if (Source == E) { // sanity checking.
2408 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002409 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002410 }
2411 return StmtVisitorTy::Visit(Source);
2412 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002413 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002414 }
Richard Smithf10d9172011-10-11 21:43:33 +00002415
Richard Smithd0dccea2011-10-28 22:34:42 +00002416 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002417 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002418 QualType CalleeType = Callee->getType();
2419
Richard Smithd0dccea2011-10-28 22:34:42 +00002420 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002421 LValue *This = 0, ThisVal;
2422 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002423 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002424
Richard Smith59efe262011-11-11 04:05:33 +00002425 // Extract function decl and 'this' pointer from the callee.
2426 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002427 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002428 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2429 // Explicit bound member calls, such as x.f() or p->g();
2430 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002431 return false;
2432 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002433 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002434 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002435 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2436 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002437 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2438 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002439 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002440 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return Error(Callee);
2442
2443 FD = dyn_cast<FunctionDecl>(Member);
2444 if (!FD)
2445 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002446 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002447 LValue Call;
2448 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002449 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002450
Richard Smithb4e85ed2012-01-06 16:39:00 +00002451 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002452 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002453 FD = dyn_cast_or_null<FunctionDecl>(
2454 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002455 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002456 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002457
2458 // Overloaded operator calls to member functions are represented as normal
2459 // calls with '*this' as the first argument.
2460 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2461 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002462 // FIXME: When selecting an implicit conversion for an overloaded
2463 // operator delete, we sometimes try to evaluate calls to conversion
2464 // operators without a 'this' parameter!
2465 if (Args.empty())
2466 return Error(E);
2467
Richard Smith59efe262011-11-11 04:05:33 +00002468 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2469 return false;
2470 This = &ThisVal;
2471 Args = Args.slice(1);
2472 }
2473
2474 // Don't call function pointers which have been cast to some other type.
2475 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002476 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002477 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002478 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002479
Richard Smithb04035a2012-02-01 02:39:43 +00002480 if (This && !This->checkSubobject(Info, E, CSK_This))
2481 return false;
2482
Richard Smith86c3ae42012-02-13 03:54:03 +00002483 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2484 // calls to such functions in constant expressions.
2485 if (This && !HasQualifier &&
2486 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2487 return Error(E, diag::note_constexpr_virtual_call);
2488
Richard Smithc1c5f272011-12-13 06:39:58 +00002489 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002490 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002491 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002492
Richard Smithc1c5f272011-12-13 06:39:58 +00002493 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002494 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2495 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002496 return false;
2497
Richard Smithb4e85ed2012-01-06 16:39:00 +00002498 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002499 }
2500
Richard Smithc49bd112011-10-28 17:51:58 +00002501 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2502 return StmtVisitorTy::Visit(E->getInitializer());
2503 }
Richard Smithf10d9172011-10-11 21:43:33 +00002504 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002505 if (E->getNumInits() == 0)
2506 return DerivedZeroInitialization(E);
2507 if (E->getNumInits() == 1)
2508 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002509 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002510 }
2511 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002512 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002513 }
2514 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002515 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002516 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002517 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002518 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002519 }
Richard Smithf10d9172011-10-11 21:43:33 +00002520
Richard Smith180f4792011-11-10 06:34:14 +00002521 /// A member expression where the object is a prvalue is itself a prvalue.
2522 RetTy VisitMemberExpr(const MemberExpr *E) {
2523 assert(!E->isArrow() && "missing call to bound member function?");
2524
2525 CCValue Val;
2526 if (!Evaluate(Val, Info, E->getBase()))
2527 return false;
2528
2529 QualType BaseTy = E->getBase()->getType();
2530
2531 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002532 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002533 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2534 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2535 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2536
Richard Smithb4e85ed2012-01-06 16:39:00 +00002537 SubobjectDesignator Designator(BaseTy);
2538 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002539
Richard Smithf48fdb02011-12-09 22:58:01 +00002540 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002541 DerivedSuccess(Val, E);
2542 }
2543
Richard Smithc49bd112011-10-28 17:51:58 +00002544 RetTy VisitCastExpr(const CastExpr *E) {
2545 switch (E->getCastKind()) {
2546 default:
2547 break;
2548
David Chisnall7a7ee302012-01-16 17:27:18 +00002549 case CK_AtomicToNonAtomic:
2550 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002551 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002552 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002553 return StmtVisitorTy::Visit(E->getSubExpr());
2554
2555 case CK_LValueToRValue: {
2556 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002557 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2558 return false;
2559 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002560 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2561 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2562 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002563 return false;
2564 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002565 }
2566 }
2567
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002569 }
2570
Richard Smith8327fad2011-10-24 18:44:57 +00002571 /// Visit a value which is evaluated, but whose value is ignored.
2572 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002573 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002574 if (!Evaluate(Scratch, Info, E))
2575 Info.EvalStatus.HasSideEffects = true;
2576 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002577};
2578
2579}
2580
2581//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582// Common base class for lvalue and temporary evaluation.
2583//===----------------------------------------------------------------------===//
2584namespace {
2585template<class Derived>
2586class LValueExprEvaluatorBase
2587 : public ExprEvaluatorBase<Derived, bool> {
2588protected:
2589 LValue &Result;
2590 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2591 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2592
2593 bool Success(APValue::LValueBase B) {
2594 Result.set(B);
2595 return true;
2596 }
2597
2598public:
2599 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2600 ExprEvaluatorBaseTy(Info), Result(Result) {}
2601
2602 bool Success(const CCValue &V, const Expr *E) {
2603 Result.setFrom(V);
2604 return true;
2605 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002606
Richard Smithe24f5fc2011-11-17 22:56:20 +00002607 bool VisitMemberExpr(const MemberExpr *E) {
2608 // Handle non-static data members.
2609 QualType BaseTy;
2610 if (E->isArrow()) {
2611 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2612 return false;
2613 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002614 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002615 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002616 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2617 return false;
2618 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002619 } else {
2620 if (!this->Visit(E->getBase()))
2621 return false;
2622 BaseTy = E->getBase()->getType();
2623 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002624
Richard Smithd9b02e72012-01-25 22:15:11 +00002625 const ValueDecl *MD = E->getMemberDecl();
2626 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2627 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2628 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2629 (void)BaseTy;
2630 HandleLValueMember(this->Info, E, Result, FD);
2631 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2632 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2633 } else
2634 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002635
Richard Smithd9b02e72012-01-25 22:15:11 +00002636 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002637 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002638 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002639 RefValue))
2640 return false;
2641 return Success(RefValue, E);
2642 }
2643 return true;
2644 }
2645
2646 bool VisitBinaryOperator(const BinaryOperator *E) {
2647 switch (E->getOpcode()) {
2648 default:
2649 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2650
2651 case BO_PtrMemD:
2652 case BO_PtrMemI:
2653 return HandleMemberPointerAccess(this->Info, E, Result);
2654 }
2655 }
2656
2657 bool VisitCastExpr(const CastExpr *E) {
2658 switch (E->getCastKind()) {
2659 default:
2660 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2661
2662 case CK_DerivedToBase:
2663 case CK_UncheckedDerivedToBase: {
2664 if (!this->Visit(E->getSubExpr()))
2665 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002666
2667 // Now figure out the necessary offset to add to the base LV to get from
2668 // the derived class to the base class.
2669 QualType Type = E->getSubExpr()->getType();
2670
2671 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2672 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002673 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002674 *PathI))
2675 return false;
2676 Type = (*PathI)->getType();
2677 }
2678
2679 return true;
2680 }
2681 }
2682 }
2683};
2684}
2685
2686//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002687// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002688//
2689// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2690// function designators (in C), decl references to void objects (in C), and
2691// temporaries (if building with -Wno-address-of-temporary).
2692//
2693// LValue evaluation produces values comprising a base expression of one of the
2694// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002695// - Declarations
2696// * VarDecl
2697// * FunctionDecl
2698// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002699// * CompoundLiteralExpr in C
2700// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002701// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002702// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002703// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002704// * ObjCEncodeExpr
2705// * AddrLabelExpr
2706// * BlockExpr
2707// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002708// - Locals and temporaries
2709// * Any Expr, with a Frame indicating the function in which the temporary was
2710// evaluated.
2711// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002712//===----------------------------------------------------------------------===//
2713namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002714class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002715 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002716public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002717 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2718 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Richard Smithc49bd112011-10-28 17:51:58 +00002720 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2721
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002722 bool VisitDeclRefExpr(const DeclRefExpr *E);
2723 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002724 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002725 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2726 bool VisitMemberExpr(const MemberExpr *E);
2727 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2728 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002729 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002730 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2731 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002732
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002733 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002734 switch (E->getCastKind()) {
2735 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002736 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002737
Eli Friedmandb924222011-10-11 00:13:24 +00002738 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002739 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002740 if (!Visit(E->getSubExpr()))
2741 return false;
2742 Result.Designator.setInvalid();
2743 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002744
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002746 if (!Visit(E->getSubExpr()))
2747 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002749 }
2750 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002751
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002752 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002753
Eli Friedman4efaa272008-11-12 09:44:48 +00002754};
2755} // end anonymous namespace
2756
Richard Smithc49bd112011-10-28 17:51:58 +00002757/// Evaluate an expression as an lvalue. This can be legitimately called on
2758/// expressions which are not glvalues, in a few cases:
2759/// * function designators in C,
2760/// * "extern void" objects,
2761/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002762static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002763 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2764 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2765 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002766 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002767}
2768
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002769bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002770 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2771 return Success(FD);
2772 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002773 return VisitVarDecl(E, VD);
2774 return Error(E);
2775}
Richard Smith436c8892011-10-24 23:14:33 +00002776
Richard Smithc49bd112011-10-28 17:51:58 +00002777bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002778 if (!VD->getType()->isReferenceType()) {
2779 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002780 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002781 return true;
2782 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002783 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002784 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002785
Richard Smith47a1eed2011-10-29 20:57:55 +00002786 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002787 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2788 return false;
2789 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002790}
2791
Richard Smithbd552ef2011-10-31 05:52:43 +00002792bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2793 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002794 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002795 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002796 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2797
2798 Result.set(E, Info.CurrentCall);
2799 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2800 Result, E->GetTemporaryExpr());
2801 }
2802
2803 // Materialization of an lvalue temporary occurs when we need to force a copy
2804 // (for instance, if it's a bitfield).
2805 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2806 if (!Visit(E->GetTemporaryExpr()))
2807 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002808 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002809 Info.CurrentCall->Temporaries[E]))
2810 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002811 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002812 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002813}
2814
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002815bool
2816LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002817 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2818 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2819 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002820 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002821}
2822
Richard Smith47d21452011-12-27 12:18:28 +00002823bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2824 if (E->isTypeOperand())
2825 return Success(E);
2826 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2827 if (RD && RD->isPolymorphic()) {
2828 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2829 << E->getExprOperand()->getType()
2830 << E->getExprOperand()->getSourceRange();
2831 return false;
2832 }
2833 return Success(E);
2834}
2835
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002836bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002837 // Handle static data members.
2838 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2839 VisitIgnoredValue(E->getBase());
2840 return VisitVarDecl(E, VD);
2841 }
2842
Richard Smithd0dccea2011-10-28 22:34:42 +00002843 // Handle static member functions.
2844 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2845 if (MD->isStatic()) {
2846 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002847 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002848 }
2849 }
2850
Richard Smith180f4792011-11-10 06:34:14 +00002851 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002853}
2854
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002855bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002856 // FIXME: Deal with vectors as array subscript bases.
2857 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002858 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002859
Anders Carlsson3068d112008-11-16 19:01:22 +00002860 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002861 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Anders Carlsson3068d112008-11-16 19:01:22 +00002863 APSInt Index;
2864 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002865 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002866 int64_t IndexValue
2867 = Index.isSigned() ? Index.getSExtValue()
2868 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002869
Richard Smithb4e85ed2012-01-06 16:39:00 +00002870 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002871}
Eli Friedman4efaa272008-11-12 09:44:48 +00002872
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002873bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002874 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002875}
2876
Eli Friedman4efaa272008-11-12 09:44:48 +00002877//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002878// Pointer Evaluation
2879//===----------------------------------------------------------------------===//
2880
Anders Carlssonc754aa62008-07-08 05:13:58 +00002881namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002882class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002883 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002884 LValue &Result;
2885
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002886 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002887 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002888 return true;
2889 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002890public:
Mike Stump1eb44332009-09-09 15:08:12 +00002891
John McCallefdb83e2010-05-07 21:00:08 +00002892 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002893 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002894
Richard Smith47a1eed2011-10-29 20:57:55 +00002895 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002896 Result.setFrom(V);
2897 return true;
2898 }
Richard Smith51201882011-12-30 21:15:51 +00002899 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002900 return Success((Expr*)0);
2901 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002902
John McCallefdb83e2010-05-07 21:00:08 +00002903 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002904 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002905 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002906 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002907 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002908 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002909 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002910 bool VisitCallExpr(const CallExpr *E);
2911 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002912 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002913 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002914 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002915 }
Richard Smith180f4792011-11-10 06:34:14 +00002916 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2917 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002918 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002919 Result = *Info.CurrentCall->This;
2920 return true;
2921 }
John McCall56ca35d2011-02-17 10:25:35 +00002922
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002923 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002924};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002925} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002926
John McCallefdb83e2010-05-07 21:00:08 +00002927static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002928 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002929 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002930}
2931
John McCallefdb83e2010-05-07 21:00:08 +00002932bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002933 if (E->getOpcode() != BO_Add &&
2934 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002935 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002937 const Expr *PExp = E->getLHS();
2938 const Expr *IExp = E->getRHS();
2939 if (IExp->getType()->isPointerType())
2940 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Richard Smith745f5142012-01-27 01:14:48 +00002942 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2943 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002944 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002945
John McCallefdb83e2010-05-07 21:00:08 +00002946 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002947 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002948 return false;
2949 int64_t AdditionalOffset
2950 = Offset.isSigned() ? Offset.getSExtValue()
2951 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002952 if (E->getOpcode() == BO_Sub)
2953 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002954
Richard Smith180f4792011-11-10 06:34:14 +00002955 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002956 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2957 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002958}
Eli Friedman4efaa272008-11-12 09:44:48 +00002959
John McCallefdb83e2010-05-07 21:00:08 +00002960bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2961 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002962}
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002964bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2965 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002966
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002967 switch (E->getCastKind()) {
2968 default:
2969 break;
2970
John McCall2de56d12010-08-25 11:45:40 +00002971 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002972 case CK_CPointerToObjCPointerCast:
2973 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002974 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002975 if (!Visit(SubExpr))
2976 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002977 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2978 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2979 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002980 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002981 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002982 if (SubExpr->getType()->isVoidPointerType())
2983 CCEDiag(E, diag::note_constexpr_invalid_cast)
2984 << 3 << SubExpr->getType();
2985 else
2986 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2987 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002988 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002989
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002990 case CK_DerivedToBase:
2991 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002992 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002993 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002994 if (!Result.Base && Result.Offset.isZero())
2995 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002996
Richard Smith180f4792011-11-10 06:34:14 +00002997 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002998 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002999 QualType Type =
3000 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003001
Richard Smith180f4792011-11-10 06:34:14 +00003002 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003003 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003004 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3005 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003006 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003007 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003008 }
3009
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003010 return true;
3011 }
3012
Richard Smithe24f5fc2011-11-17 22:56:20 +00003013 case CK_BaseToDerived:
3014 if (!Visit(E->getSubExpr()))
3015 return false;
3016 if (!Result.Base && Result.Offset.isZero())
3017 return true;
3018 return HandleBaseToDerivedCast(Info, E, Result);
3019
Richard Smith47a1eed2011-10-29 20:57:55 +00003020 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003021 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003022
John McCall2de56d12010-08-25 11:45:40 +00003023 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003024 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3025
Richard Smith47a1eed2011-10-29 20:57:55 +00003026 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003027 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003028 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003029
John McCallefdb83e2010-05-07 21:00:08 +00003030 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003031 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3032 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003033 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003034 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00003035 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003036 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003037 return true;
3038 } else {
3039 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003040 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003041 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003042 }
3043 }
John McCall2de56d12010-08-25 11:45:40 +00003044 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003045 if (SubExpr->isGLValue()) {
3046 if (!EvaluateLValue(SubExpr, Result, Info))
3047 return false;
3048 } else {
3049 Result.set(SubExpr, Info.CurrentCall);
3050 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3051 Info, Result, SubExpr))
3052 return false;
3053 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003054 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003055 if (const ConstantArrayType *CAT
3056 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3057 Result.addArray(Info, E, CAT);
3058 else
3059 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003060 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003061
John McCall2de56d12010-08-25 11:45:40 +00003062 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003063 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003064 }
3065
Richard Smithc49bd112011-10-28 17:51:58 +00003066 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003067}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003068
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003069bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003070 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003071 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003072
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003073 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003074}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003075
3076//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003077// Member Pointer Evaluation
3078//===----------------------------------------------------------------------===//
3079
3080namespace {
3081class MemberPointerExprEvaluator
3082 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3083 MemberPtr &Result;
3084
3085 bool Success(const ValueDecl *D) {
3086 Result = MemberPtr(D);
3087 return true;
3088 }
3089public:
3090
3091 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3092 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3093
3094 bool Success(const CCValue &V, const Expr *E) {
3095 Result.setFrom(V);
3096 return true;
3097 }
Richard Smith51201882011-12-30 21:15:51 +00003098 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003099 return Success((const ValueDecl*)0);
3100 }
3101
3102 bool VisitCastExpr(const CastExpr *E);
3103 bool VisitUnaryAddrOf(const UnaryOperator *E);
3104};
3105} // end anonymous namespace
3106
3107static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3108 EvalInfo &Info) {
3109 assert(E->isRValue() && E->getType()->isMemberPointerType());
3110 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3111}
3112
3113bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3114 switch (E->getCastKind()) {
3115 default:
3116 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3117
3118 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003119 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003120
3121 case CK_BaseToDerivedMemberPointer: {
3122 if (!Visit(E->getSubExpr()))
3123 return false;
3124 if (E->path_empty())
3125 return true;
3126 // Base-to-derived member pointer casts store the path in derived-to-base
3127 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3128 // the wrong end of the derived->base arc, so stagger the path by one class.
3129 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3130 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3131 PathI != PathE; ++PathI) {
3132 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3133 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3134 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003135 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003136 }
3137 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3138 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003139 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003140 return true;
3141 }
3142
3143 case CK_DerivedToBaseMemberPointer:
3144 if (!Visit(E->getSubExpr()))
3145 return false;
3146 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3147 PathE = E->path_end(); PathI != PathE; ++PathI) {
3148 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3149 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3150 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003151 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003152 }
3153 return true;
3154 }
3155}
3156
3157bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3158 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3159 // member can be formed.
3160 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3161}
3162
3163//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003164// Record Evaluation
3165//===----------------------------------------------------------------------===//
3166
3167namespace {
3168 class RecordExprEvaluator
3169 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3170 const LValue &This;
3171 APValue &Result;
3172 public:
3173
3174 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3175 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3176
3177 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003178 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003179 }
Richard Smith51201882011-12-30 21:15:51 +00003180 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003181
Richard Smith59efe262011-11-11 04:05:33 +00003182 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003183 bool VisitInitListExpr(const InitListExpr *E);
3184 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3185 };
3186}
3187
Richard Smith51201882011-12-30 21:15:51 +00003188/// Perform zero-initialization on an object of non-union class type.
3189/// C++11 [dcl.init]p5:
3190/// To zero-initialize an object or reference of type T means:
3191/// [...]
3192/// -- if T is a (possibly cv-qualified) non-union class type,
3193/// each non-static data member and each base-class subobject is
3194/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003195static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3196 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003197 const LValue &This, APValue &Result) {
3198 assert(!RD->isUnion() && "Expected non-union class type");
3199 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3200 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3201 std::distance(RD->field_begin(), RD->field_end()));
3202
3203 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3204
3205 if (CD) {
3206 unsigned Index = 0;
3207 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003208 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003209 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3210 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003211 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3212 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003213 Result.getStructBase(Index)))
3214 return false;
3215 }
3216 }
3217
Richard Smithb4e85ed2012-01-06 16:39:00 +00003218 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3219 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003220 // -- if T is a reference type, no initialization is performed.
3221 if ((*I)->getType()->isReferenceType())
3222 continue;
3223
3224 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003225 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003226
3227 ImplicitValueInitExpr VIE((*I)->getType());
3228 if (!EvaluateConstantExpression(
3229 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3230 return false;
3231 }
3232
3233 return true;
3234}
3235
3236bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3237 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3238 if (RD->isUnion()) {
3239 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3240 // object's first non-static named data member is zero-initialized
3241 RecordDecl::field_iterator I = RD->field_begin();
3242 if (I == RD->field_end()) {
3243 Result = APValue((const FieldDecl*)0);
3244 return true;
3245 }
3246
3247 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003248 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003249 Result = APValue(*I);
3250 ImplicitValueInitExpr VIE((*I)->getType());
3251 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3252 Subobject, &VIE);
3253 }
3254
Richard Smithb4e85ed2012-01-06 16:39:00 +00003255 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003256}
3257
Richard Smith59efe262011-11-11 04:05:33 +00003258bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3259 switch (E->getCastKind()) {
3260 default:
3261 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3262
3263 case CK_ConstructorConversion:
3264 return Visit(E->getSubExpr());
3265
3266 case CK_DerivedToBase:
3267 case CK_UncheckedDerivedToBase: {
3268 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003269 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003270 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003271 if (!DerivedObject.isStruct())
3272 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003273
3274 // Derived-to-base rvalue conversion: just slice off the derived part.
3275 APValue *Value = &DerivedObject;
3276 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3277 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3278 PathE = E->path_end(); PathI != PathE; ++PathI) {
3279 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3280 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3281 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3282 RD = Base;
3283 }
3284 Result = *Value;
3285 return true;
3286 }
3287 }
3288}
3289
Richard Smith180f4792011-11-10 06:34:14 +00003290bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3291 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3292 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3293
3294 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003295 const FieldDecl *Field = E->getInitializedFieldInUnion();
3296 Result = APValue(Field);
3297 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003298 return true;
Richard Smithec789162012-01-12 18:54:33 +00003299
3300 // If the initializer list for a union does not contain any elements, the
3301 // first element of the union is value-initialized.
3302 ImplicitValueInitExpr VIE(Field->getType());
3303 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3304
Richard Smith180f4792011-11-10 06:34:14 +00003305 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003306 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003307 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003308 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003309 }
3310
3311 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3312 "initializer list for class with base classes");
3313 Result = APValue(APValue::UninitStruct(), 0,
3314 std::distance(RD->field_begin(), RD->field_end()));
3315 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003316 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003317 for (RecordDecl::field_iterator Field = RD->field_begin(),
3318 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3319 // Anonymous bit-fields are not considered members of the class for
3320 // purposes of aggregate initialization.
3321 if (Field->isUnnamedBitfield())
3322 continue;
3323
3324 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003325
Richard Smith745f5142012-01-27 01:14:48 +00003326 bool HaveInit = ElementNo < E->getNumInits();
3327
3328 // FIXME: Diagnostics here should point to the end of the initializer
3329 // list, not the start.
3330 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3331 *Field, &Layout);
3332
3333 // Perform an implicit value-initialization for members beyond the end of
3334 // the initializer list.
3335 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3336
3337 if (!EvaluateConstantExpression(
3338 Result.getStructField((*Field)->getFieldIndex()),
3339 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3340 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003341 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003342 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003343 }
3344 }
3345
Richard Smith745f5142012-01-27 01:14:48 +00003346 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003347}
3348
3349bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3350 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003351 bool ZeroInit = E->requiresZeroInitialization();
3352 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003353 // If we've already performed zero-initialization, we're already done.
3354 if (!Result.isUninit())
3355 return true;
3356
Richard Smith51201882011-12-30 21:15:51 +00003357 if (ZeroInit)
3358 return ZeroInitialization(E);
3359
Richard Smith61802452011-12-22 02:22:31 +00003360 const CXXRecordDecl *RD = FD->getParent();
3361 if (RD->isUnion())
3362 Result = APValue((FieldDecl*)0);
3363 else
3364 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3365 std::distance(RD->field_begin(), RD->field_end()));
3366 return true;
3367 }
3368
Richard Smith180f4792011-11-10 06:34:14 +00003369 const FunctionDecl *Definition = 0;
3370 FD->getBody(Definition);
3371
Richard Smithc1c5f272011-12-13 06:39:58 +00003372 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3373 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003374
Richard Smith610a60c2012-01-10 04:32:03 +00003375 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003376 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003377 if (const MaterializeTemporaryExpr *ME
3378 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3379 return Visit(ME->GetTemporaryExpr());
3380
Richard Smith51201882011-12-30 21:15:51 +00003381 if (ZeroInit && !ZeroInitialization(E))
3382 return false;
3383
Richard Smith180f4792011-11-10 06:34:14 +00003384 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003385 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003386 cast<CXXConstructorDecl>(Definition), Info,
3387 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003388}
3389
3390static bool EvaluateRecord(const Expr *E, const LValue &This,
3391 APValue &Result, EvalInfo &Info) {
3392 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003393 "can't evaluate expression as a record rvalue");
3394 return RecordExprEvaluator(Info, This, Result).Visit(E);
3395}
3396
3397//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003398// Temporary Evaluation
3399//
3400// Temporaries are represented in the AST as rvalues, but generally behave like
3401// lvalues. The full-object of which the temporary is a subobject is implicitly
3402// materialized so that a reference can bind to it.
3403//===----------------------------------------------------------------------===//
3404namespace {
3405class TemporaryExprEvaluator
3406 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3407public:
3408 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3409 LValueExprEvaluatorBaseTy(Info, Result) {}
3410
3411 /// Visit an expression which constructs the value of this temporary.
3412 bool VisitConstructExpr(const Expr *E) {
3413 Result.set(E, Info.CurrentCall);
3414 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3415 Result, E);
3416 }
3417
3418 bool VisitCastExpr(const CastExpr *E) {
3419 switch (E->getCastKind()) {
3420 default:
3421 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3422
3423 case CK_ConstructorConversion:
3424 return VisitConstructExpr(E->getSubExpr());
3425 }
3426 }
3427 bool VisitInitListExpr(const InitListExpr *E) {
3428 return VisitConstructExpr(E);
3429 }
3430 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3431 return VisitConstructExpr(E);
3432 }
3433 bool VisitCallExpr(const CallExpr *E) {
3434 return VisitConstructExpr(E);
3435 }
3436};
3437} // end anonymous namespace
3438
3439/// Evaluate an expression of record type as a temporary.
3440static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003441 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003442 return TemporaryExprEvaluator(Info, Result).Visit(E);
3443}
3444
3445//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003446// Vector Evaluation
3447//===----------------------------------------------------------------------===//
3448
3449namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003450 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003451 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3452 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003453 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Richard Smith07fc6572011-10-22 21:10:00 +00003455 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3456 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Richard Smith07fc6572011-10-22 21:10:00 +00003458 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3459 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3460 // FIXME: remove this APValue copy.
3461 Result = APValue(V.data(), V.size());
3462 return true;
3463 }
Richard Smith69c2c502011-11-04 05:33:44 +00003464 bool Success(const CCValue &V, const Expr *E) {
3465 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003466 Result = V;
3467 return true;
3468 }
Richard Smith51201882011-12-30 21:15:51 +00003469 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Richard Smith07fc6572011-10-22 21:10:00 +00003471 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003472 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003473 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003474 bool VisitInitListExpr(const InitListExpr *E);
3475 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003476 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003477 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003478 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003479 };
3480} // end anonymous namespace
3481
3482static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003483 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003484 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003485}
3486
Richard Smith07fc6572011-10-22 21:10:00 +00003487bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3488 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003489 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Richard Smithd62ca372011-12-06 22:44:34 +00003491 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003492 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003493
Eli Friedman46a52322011-03-25 00:43:55 +00003494 switch (E->getCastKind()) {
3495 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003496 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003497 if (SETy->isIntegerType()) {
3498 APSInt IntResult;
3499 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003500 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003501 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003502 } else if (SETy->isRealFloatingType()) {
3503 APFloat F(0.0);
3504 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003505 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003506 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003507 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003508 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003509 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003510
3511 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003512 SmallVector<APValue, 4> Elts(NElts, Val);
3513 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003514 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003515 case CK_BitCast: {
3516 // Evaluate the operand into an APInt we can extract from.
3517 llvm::APInt SValInt;
3518 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3519 return false;
3520 // Extract the elements
3521 QualType EltTy = VTy->getElementType();
3522 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3523 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3524 SmallVector<APValue, 4> Elts;
3525 if (EltTy->isRealFloatingType()) {
3526 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3527 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3528 unsigned FloatEltSize = EltSize;
3529 if (&Sem == &APFloat::x87DoubleExtended)
3530 FloatEltSize = 80;
3531 for (unsigned i = 0; i < NElts; i++) {
3532 llvm::APInt Elt;
3533 if (BigEndian)
3534 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3535 else
3536 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3537 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3538 }
3539 } else if (EltTy->isIntegerType()) {
3540 for (unsigned i = 0; i < NElts; i++) {
3541 llvm::APInt Elt;
3542 if (BigEndian)
3543 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3544 else
3545 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3546 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3547 }
3548 } else {
3549 return Error(E);
3550 }
3551 return Success(Elts, E);
3552 }
Eli Friedman46a52322011-03-25 00:43:55 +00003553 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003554 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003555 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003556}
3557
Richard Smith07fc6572011-10-22 21:10:00 +00003558bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003559VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003560 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003561 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003562 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Nate Begeman59b5da62009-01-18 03:20:47 +00003564 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003565 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003566
Eli Friedman3edd5a92012-01-03 23:24:20 +00003567 // The number of initializers can be less than the number of
3568 // vector elements. For OpenCL, this can be due to nested vector
3569 // initialization. For GCC compatibility, missing trailing elements
3570 // should be initialized with zeroes.
3571 unsigned CountInits = 0, CountElts = 0;
3572 while (CountElts < NumElements) {
3573 // Handle nested vector initialization.
3574 if (CountInits < NumInits
3575 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3576 APValue v;
3577 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3578 return Error(E);
3579 unsigned vlen = v.getVectorLength();
3580 for (unsigned j = 0; j < vlen; j++)
3581 Elements.push_back(v.getVectorElt(j));
3582 CountElts += vlen;
3583 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003584 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003585 if (CountInits < NumInits) {
3586 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3587 return Error(E);
3588 } else // trailing integer zero.
3589 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3590 Elements.push_back(APValue(sInt));
3591 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003592 } else {
3593 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003594 if (CountInits < NumInits) {
3595 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3596 return Error(E);
3597 } else // trailing float zero.
3598 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3599 Elements.push_back(APValue(f));
3600 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003601 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003602 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003603 }
Richard Smith07fc6572011-10-22 21:10:00 +00003604 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003605}
3606
Richard Smith07fc6572011-10-22 21:10:00 +00003607bool
Richard Smith51201882011-12-30 21:15:51 +00003608VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003609 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003610 QualType EltTy = VT->getElementType();
3611 APValue ZeroElement;
3612 if (EltTy->isIntegerType())
3613 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3614 else
3615 ZeroElement =
3616 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3617
Chris Lattner5f9e2722011-07-23 10:55:15 +00003618 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003619 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003620}
3621
Richard Smith07fc6572011-10-22 21:10:00 +00003622bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003623 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003624 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003625}
3626
Nate Begeman59b5da62009-01-18 03:20:47 +00003627//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003628// Array Evaluation
3629//===----------------------------------------------------------------------===//
3630
3631namespace {
3632 class ArrayExprEvaluator
3633 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003634 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003635 APValue &Result;
3636 public:
3637
Richard Smith180f4792011-11-10 06:34:14 +00003638 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3639 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003640
3641 bool Success(const APValue &V, const Expr *E) {
3642 assert(V.isArray() && "Expected array type");
3643 Result = V;
3644 return true;
3645 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003646
Richard Smith51201882011-12-30 21:15:51 +00003647 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003648 const ConstantArrayType *CAT =
3649 Info.Ctx.getAsConstantArrayType(E->getType());
3650 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003651 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003652
3653 Result = APValue(APValue::UninitArray(), 0,
3654 CAT->getSize().getZExtValue());
3655 if (!Result.hasArrayFiller()) return true;
3656
Richard Smith51201882011-12-30 21:15:51 +00003657 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003658 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003659 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003660 ImplicitValueInitExpr VIE(CAT->getElementType());
3661 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3662 Subobject, &VIE);
3663 }
3664
Richard Smithcc5d4f62011-11-07 09:22:26 +00003665 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003666 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003667 };
3668} // end anonymous namespace
3669
Richard Smith180f4792011-11-10 06:34:14 +00003670static bool EvaluateArray(const Expr *E, const LValue &This,
3671 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003672 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003673 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003674}
3675
3676bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3677 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3678 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003679 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003680
Richard Smith974c5f92011-12-22 01:07:19 +00003681 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3682 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003683 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003684 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3685 LValue LV;
3686 if (!EvaluateLValue(E->getInit(0), LV, Info))
3687 return false;
3688 uint64_t NumElements = CAT->getSize().getZExtValue();
3689 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3690
3691 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003692 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003693 for (uint64_t I = 0; I < NumElements; ++I) {
3694 CCValue Char;
3695 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003696 CAT->getElementType(), LV, Char) ||
3697 !CheckConstantExpression(Info, E->getInit(0), Char,
3698 Result.getArrayInitializedElt(I)) ||
3699 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003700 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003701 return false;
3702 }
3703 return true;
3704 }
3705
Richard Smith745f5142012-01-27 01:14:48 +00003706 bool Success = true;
3707
Richard Smithcc5d4f62011-11-07 09:22:26 +00003708 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3709 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003710 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003711 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003712 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003713 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003714 I != End; ++I, ++Index) {
3715 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003716 Info, Subobject, cast<Expr>(*I)) ||
3717 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3718 CAT->getElementType(), 1)) {
3719 if (!Info.keepEvaluatingAfterFailure())
3720 return false;
3721 Success = false;
3722 }
Richard Smith180f4792011-11-10 06:34:14 +00003723 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003724
Richard Smith745f5142012-01-27 01:14:48 +00003725 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003726 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003727 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3728 // but sometimes does:
3729 // struct S { constexpr S() : p(&p) {} void *p; };
3730 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003731 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003732 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003733}
3734
Richard Smithe24f5fc2011-11-17 22:56:20 +00003735bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3736 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3737 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003738 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003739
Richard Smithec789162012-01-12 18:54:33 +00003740 bool HadZeroInit = !Result.isUninit();
3741 if (!HadZeroInit)
3742 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003743 if (!Result.hasArrayFiller())
3744 return true;
3745
3746 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003747
Richard Smith51201882011-12-30 21:15:51 +00003748 bool ZeroInit = E->requiresZeroInitialization();
3749 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003750 if (HadZeroInit)
3751 return true;
3752
Richard Smith51201882011-12-30 21:15:51 +00003753 if (ZeroInit) {
3754 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003755 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003756 ImplicitValueInitExpr VIE(CAT->getElementType());
3757 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3758 Subobject, &VIE);
3759 }
3760
Richard Smith61802452011-12-22 02:22:31 +00003761 const CXXRecordDecl *RD = FD->getParent();
3762 if (RD->isUnion())
3763 Result.getArrayFiller() = APValue((FieldDecl*)0);
3764 else
3765 Result.getArrayFiller() =
3766 APValue(APValue::UninitStruct(), RD->getNumBases(),
3767 std::distance(RD->field_begin(), RD->field_end()));
3768 return true;
3769 }
3770
Richard Smithe24f5fc2011-11-17 22:56:20 +00003771 const FunctionDecl *Definition = 0;
3772 FD->getBody(Definition);
3773
Richard Smithc1c5f272011-12-13 06:39:58 +00003774 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3775 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003776
3777 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3778 // but sometimes does:
3779 // struct S { constexpr S() : p(&p) {} void *p; };
3780 // S s[10];
3781 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003782 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003783
Richard Smithec789162012-01-12 18:54:33 +00003784 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003785 ImplicitValueInitExpr VIE(CAT->getElementType());
3786 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3787 &VIE))
3788 return false;
3789 }
3790
Richard Smithe24f5fc2011-11-17 22:56:20 +00003791 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003792 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003793 cast<CXXConstructorDecl>(Definition),
3794 Info, Result.getArrayFiller());
3795}
3796
Richard Smithcc5d4f62011-11-07 09:22:26 +00003797//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003798// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003799//
3800// As a GNU extension, we support casting pointers to sufficiently-wide integer
3801// types and back in constant folding. Integer values are thus represented
3802// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003803//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003804
3805namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003806class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003807 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003808 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003809public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003810 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003811 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003812
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003813 bool Success(const llvm::APSInt &SI, const Expr *E) {
3814 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003815 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003816 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003817 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003818 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003819 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003820 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003821 return true;
3822 }
3823
Daniel Dunbar131eb432009-02-19 09:06:44 +00003824 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003825 assert(E->getType()->isIntegralOrEnumerationType() &&
3826 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003827 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003828 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003829 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003830 Result.getInt().setIsUnsigned(
3831 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003832 return true;
3833 }
3834
3835 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003836 assert(E->getType()->isIntegralOrEnumerationType() &&
3837 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003838 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003839 return true;
3840 }
3841
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003842 bool Success(CharUnits Size, const Expr *E) {
3843 return Success(Size.getQuantity(), E);
3844 }
3845
Richard Smith47a1eed2011-10-29 20:57:55 +00003846 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003847 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003848 Result = V;
3849 return true;
3850 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003851 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003852 }
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Richard Smith51201882011-12-30 21:15:51 +00003854 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003855
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003856 //===--------------------------------------------------------------------===//
3857 // Visitor Methods
3858 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003859
Chris Lattner4c4867e2008-07-12 00:38:25 +00003860 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003861 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003862 }
3863 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003864 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003865 }
Eli Friedman04309752009-11-24 05:28:59 +00003866
3867 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3868 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003869 if (CheckReferencedDecl(E, E->getDecl()))
3870 return true;
3871
3872 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003873 }
3874 bool VisitMemberExpr(const MemberExpr *E) {
3875 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003876 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003877 return true;
3878 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003879
3880 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003881 }
3882
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003883 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003884 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003885 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003886 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003887
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003888 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003889 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003890
Anders Carlsson3068d112008-11-16 19:01:22 +00003891 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003892 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003893 }
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Richard Smithf10d9172011-10-11 21:43:33 +00003895 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003896 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003897 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003898 }
3899
Sebastian Redl64b45f72009-01-05 20:52:13 +00003900 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003901 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003902 }
3903
Francois Pichet6ad6f282010-12-07 00:08:36 +00003904 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3905 return Success(E->getValue(), E);
3906 }
3907
John Wiegley21ff2e52011-04-28 00:16:57 +00003908 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3909 return Success(E->getValue(), E);
3910 }
3911
John Wiegley55262202011-04-25 06:54:41 +00003912 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3913 return Success(E->getValue(), E);
3914 }
3915
Eli Friedman722c7172009-02-28 03:59:05 +00003916 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003917 bool VisitUnaryImag(const UnaryOperator *E);
3918
Sebastian Redl295995c2010-09-10 20:55:47 +00003919 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003920 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003921
Chris Lattnerfcee0012008-07-11 21:24:13 +00003922private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003923 CharUnits GetAlignOfExpr(const Expr *E);
3924 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003925 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003926 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003927 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003928};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003929} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003930
Richard Smithc49bd112011-10-28 17:51:58 +00003931/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3932/// produce either the integer value or a pointer.
3933///
3934/// GCC has a heinous extension which folds casts between pointer types and
3935/// pointer-sized integral types. We support this by allowing the evaluation of
3936/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3937/// Some simple arithmetic on such values is supported (they are treated much
3938/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003939static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003940 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003941 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003942 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003943}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003944
Richard Smithf48fdb02011-12-09 22:58:01 +00003945static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003946 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003947 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003948 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003949 if (!Val.isInt()) {
3950 // FIXME: It would be better to produce the diagnostic for casting
3951 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003952 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003953 return false;
3954 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003955 Result = Val.getInt();
3956 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003957}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003958
Richard Smithf48fdb02011-12-09 22:58:01 +00003959/// Check whether the given declaration can be directly converted to an integral
3960/// rvalue. If not, no diagnostic is produced; there are other things we can
3961/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003962bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003963 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003964 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003965 // Check for signedness/width mismatches between E type and ECD value.
3966 bool SameSign = (ECD->getInitVal().isSigned()
3967 == E->getType()->isSignedIntegerOrEnumerationType());
3968 bool SameWidth = (ECD->getInitVal().getBitWidth()
3969 == Info.Ctx.getIntWidth(E->getType()));
3970 if (SameSign && SameWidth)
3971 return Success(ECD->getInitVal(), E);
3972 else {
3973 // Get rid of mismatch (otherwise Success assertions will fail)
3974 // by computing a new value matching the type of E.
3975 llvm::APSInt Val = ECD->getInitVal();
3976 if (!SameSign)
3977 Val.setIsSigned(!ECD->getInitVal().isSigned());
3978 if (!SameWidth)
3979 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3980 return Success(Val, E);
3981 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003982 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003983 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003984}
3985
Chris Lattnera4d55d82008-10-06 06:40:35 +00003986/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3987/// as GCC.
3988static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3989 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003990 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003991 enum gcc_type_class {
3992 no_type_class = -1,
3993 void_type_class, integer_type_class, char_type_class,
3994 enumeral_type_class, boolean_type_class,
3995 pointer_type_class, reference_type_class, offset_type_class,
3996 real_type_class, complex_type_class,
3997 function_type_class, method_type_class,
3998 record_type_class, union_type_class,
3999 array_type_class, string_type_class,
4000 lang_type_class
4001 };
Mike Stump1eb44332009-09-09 15:08:12 +00004002
4003 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004004 // ideal, however it is what gcc does.
4005 if (E->getNumArgs() == 0)
4006 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Chris Lattnera4d55d82008-10-06 06:40:35 +00004008 QualType ArgTy = E->getArg(0)->getType();
4009 if (ArgTy->isVoidType())
4010 return void_type_class;
4011 else if (ArgTy->isEnumeralType())
4012 return enumeral_type_class;
4013 else if (ArgTy->isBooleanType())
4014 return boolean_type_class;
4015 else if (ArgTy->isCharType())
4016 return string_type_class; // gcc doesn't appear to use char_type_class
4017 else if (ArgTy->isIntegerType())
4018 return integer_type_class;
4019 else if (ArgTy->isPointerType())
4020 return pointer_type_class;
4021 else if (ArgTy->isReferenceType())
4022 return reference_type_class;
4023 else if (ArgTy->isRealType())
4024 return real_type_class;
4025 else if (ArgTy->isComplexType())
4026 return complex_type_class;
4027 else if (ArgTy->isFunctionType())
4028 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004029 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004030 return record_type_class;
4031 else if (ArgTy->isUnionType())
4032 return union_type_class;
4033 else if (ArgTy->isArrayType())
4034 return array_type_class;
4035 else if (ArgTy->isUnionType())
4036 return union_type_class;
4037 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004038 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004039}
4040
Richard Smith80d4b552011-12-28 19:48:30 +00004041/// EvaluateBuiltinConstantPForLValue - Determine the result of
4042/// __builtin_constant_p when applied to the given lvalue.
4043///
4044/// An lvalue is only "constant" if it is a pointer or reference to the first
4045/// character of a string literal.
4046template<typename LValue>
4047static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4048 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4049 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4050}
4051
4052/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4053/// GCC as we can manage.
4054static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4055 QualType ArgType = Arg->getType();
4056
4057 // __builtin_constant_p always has one operand. The rules which gcc follows
4058 // are not precisely documented, but are as follows:
4059 //
4060 // - If the operand is of integral, floating, complex or enumeration type,
4061 // and can be folded to a known value of that type, it returns 1.
4062 // - If the operand and can be folded to a pointer to the first character
4063 // of a string literal (or such a pointer cast to an integral type), it
4064 // returns 1.
4065 //
4066 // Otherwise, it returns 0.
4067 //
4068 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4069 // its support for this does not currently work.
4070 if (ArgType->isIntegralOrEnumerationType()) {
4071 Expr::EvalResult Result;
4072 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4073 return false;
4074
4075 APValue &V = Result.Val;
4076 if (V.getKind() == APValue::Int)
4077 return true;
4078
4079 return EvaluateBuiltinConstantPForLValue(V);
4080 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4081 return Arg->isEvaluatable(Ctx);
4082 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4083 LValue LV;
4084 Expr::EvalStatus Status;
4085 EvalInfo Info(Ctx, Status);
4086 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4087 : EvaluatePointer(Arg, LV, Info)) &&
4088 !Status.HasSideEffects)
4089 return EvaluateBuiltinConstantPForLValue(LV);
4090 }
4091
4092 // Anything else isn't considered to be sufficiently constant.
4093 return false;
4094}
4095
John McCall42c8f872010-05-10 23:27:23 +00004096/// Retrieves the "underlying object type" of the given expression,
4097/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004098QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4099 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4100 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004101 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004102 } else if (const Expr *E = B.get<const Expr*>()) {
4103 if (isa<CompoundLiteralExpr>(E))
4104 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004105 }
4106
4107 return QualType();
4108}
4109
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004110bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004111 // TODO: Perhaps we should let LLVM lower this?
4112 LValue Base;
4113 if (!EvaluatePointer(E->getArg(0), Base, Info))
4114 return false;
4115
4116 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004117 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004118
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004119 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004120 if (T.isNull() ||
4121 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004122 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004123 T->isVariablyModifiedType() ||
4124 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004125 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004126
4127 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4128 CharUnits Offset = Base.getLValueOffset();
4129
4130 if (!Offset.isNegative() && Offset <= Size)
4131 Size -= Offset;
4132 else
4133 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004134 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004135}
4136
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004137bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004138 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004139 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004140 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004141
4142 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004143 if (TryEvaluateBuiltinObjectSize(E))
4144 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004145
Eric Christopherb2aaf512010-01-19 22:58:35 +00004146 // If evaluating the argument has side-effects we can't determine
4147 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004148 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004149 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004150 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004151 return Success(0, E);
4152 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004153
Richard Smithf48fdb02011-12-09 22:58:01 +00004154 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004155 }
4156
Chris Lattner019f4e82008-10-06 05:28:25 +00004157 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004158 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Richard Smith80d4b552011-12-28 19:48:30 +00004160 case Builtin::BI__builtin_constant_p:
4161 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004162
Chris Lattner21fb98e2009-09-23 06:06:36 +00004163 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004164 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004165 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004166 return Success(Operand, E);
4167 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004168
4169 case Builtin::BI__builtin_expect:
4170 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004171
Douglas Gregor5726d402010-09-10 06:27:15 +00004172 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004173 // A call to strlen is not a constant expression.
4174 if (Info.getLangOpts().CPlusPlus0x)
4175 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4176 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4177 else
4178 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4179 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004180 case Builtin::BI__builtin_strlen:
4181 // As an extension, we support strlen() and __builtin_strlen() as constant
4182 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004183 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004184 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4185 // The string literal may have embedded null characters. Find the first
4186 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004187 StringRef Str = S->getString();
4188 StringRef::size_type Pos = Str.find(0);
4189 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004190 Str = Str.substr(0, Pos);
4191
4192 return Success(Str.size(), E);
4193 }
4194
Richard Smithf48fdb02011-12-09 22:58:01 +00004195 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004196
4197 case Builtin::BI__atomic_is_lock_free: {
4198 APSInt SizeVal;
4199 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4200 return false;
4201
4202 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4203 // of two less than the maximum inline atomic width, we know it is
4204 // lock-free. If the size isn't a power of two, or greater than the
4205 // maximum alignment where we promote atomics, we know it is not lock-free
4206 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4207 // the answer can only be determined at runtime; for example, 16-byte
4208 // atomics have lock-free implementations on some, but not all,
4209 // x86-64 processors.
4210
4211 // Check power-of-two.
4212 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4213 if (!Size.isPowerOfTwo())
4214#if 0
4215 // FIXME: Suppress this folding until the ABI for the promotion width
4216 // settles.
4217 return Success(0, E);
4218#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004219 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004220#endif
4221
4222#if 0
4223 // Check against promotion width.
4224 // FIXME: Suppress this folding until the ABI for the promotion width
4225 // settles.
4226 unsigned PromoteWidthBits =
4227 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4228 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4229 return Success(0, E);
4230#endif
4231
4232 // Check against inlining width.
4233 unsigned InlineWidthBits =
4234 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4235 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4236 return Success(1, E);
4237
Richard Smithf48fdb02011-12-09 22:58:01 +00004238 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004239 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004240 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004241}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004242
Richard Smith625b8072011-10-31 01:37:14 +00004243static bool HasSameBase(const LValue &A, const LValue &B) {
4244 if (!A.getLValueBase())
4245 return !B.getLValueBase();
4246 if (!B.getLValueBase())
4247 return false;
4248
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004249 if (A.getLValueBase().getOpaqueValue() !=
4250 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004251 const Decl *ADecl = GetLValueBaseDecl(A);
4252 if (!ADecl)
4253 return false;
4254 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004255 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004256 return false;
4257 }
4258
4259 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004260 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004261}
4262
Richard Smith7b48a292012-02-01 05:53:12 +00004263/// Perform the given integer operation, which is known to need at most BitWidth
4264/// bits, and check for overflow in the original type (if that type was not an
4265/// unsigned type).
4266template<typename Operation>
4267static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4268 const APSInt &LHS, const APSInt &RHS,
4269 unsigned BitWidth, Operation Op) {
4270 if (LHS.isUnsigned())
4271 return Op(LHS, RHS);
4272
4273 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4274 APSInt Result = Value.trunc(LHS.getBitWidth());
4275 if (Result.extend(BitWidth) != Value)
4276 HandleOverflow(Info, E, Value, E->getType());
4277 return Result;
4278}
4279
Chris Lattnerb542afe2008-07-11 19:10:17 +00004280bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004281 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004282 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004283
John McCall2de56d12010-08-25 11:45:40 +00004284 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004285 VisitIgnoredValue(E->getLHS());
4286 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004287 }
4288
4289 if (E->isLogicalOp()) {
4290 // These need to be handled specially because the operands aren't
4291 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004292 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004293
Richard Smithc49bd112011-10-28 17:51:58 +00004294 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004295 // We were able to evaluate the LHS, see if we can get away with not
4296 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004297 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004298 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004299
Richard Smithc49bd112011-10-28 17:51:58 +00004300 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004301 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004302 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004303 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004304 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004305 }
4306 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004307 // FIXME: If both evaluations fail, we should produce the diagnostic from
4308 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4309 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004310 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004311 // We can't evaluate the LHS; however, sometimes the result
4312 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004313 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004314 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004315 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004316 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004317
4318 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004319 }
4320 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004321 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004322
Eli Friedmana6afa762008-11-13 06:09:17 +00004323 return false;
4324 }
4325
Anders Carlsson286f85e2008-11-16 07:17:21 +00004326 QualType LHSTy = E->getLHS()->getType();
4327 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004328
4329 if (LHSTy->isAnyComplexType()) {
4330 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004331 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004332
Richard Smith745f5142012-01-27 01:14:48 +00004333 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4334 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004335 return false;
4336
Richard Smith745f5142012-01-27 01:14:48 +00004337 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004338 return false;
4339
4340 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004341 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004342 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004343 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004344 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4345
John McCall2de56d12010-08-25 11:45:40 +00004346 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004347 return Success((CR_r == APFloat::cmpEqual &&
4348 CR_i == APFloat::cmpEqual), E);
4349 else {
John McCall2de56d12010-08-25 11:45:40 +00004350 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004351 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004352 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004353 CR_r == APFloat::cmpLessThan ||
4354 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004355 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004356 CR_i == APFloat::cmpLessThan ||
4357 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004358 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004359 } else {
John McCall2de56d12010-08-25 11:45:40 +00004360 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004361 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4362 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4363 else {
John McCall2de56d12010-08-25 11:45:40 +00004364 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004365 "Invalid compex comparison.");
4366 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4367 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4368 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004369 }
4370 }
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Anders Carlsson286f85e2008-11-16 07:17:21 +00004372 if (LHSTy->isRealFloatingType() &&
4373 RHSTy->isRealFloatingType()) {
4374 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Richard Smith745f5142012-01-27 01:14:48 +00004376 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4377 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004378 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Richard Smith745f5142012-01-27 01:14:48 +00004380 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004381 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Anders Carlsson286f85e2008-11-16 07:17:21 +00004383 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004384
Anders Carlsson286f85e2008-11-16 07:17:21 +00004385 switch (E->getOpcode()) {
4386 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004387 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004388 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004389 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004390 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004391 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004392 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004393 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004394 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004395 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004396 E);
John McCall2de56d12010-08-25 11:45:40 +00004397 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004398 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004399 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004400 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004401 || CR == APFloat::cmpLessThan
4402 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004403 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004404 }
Mike Stump1eb44332009-09-09 15:08:12 +00004405
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004406 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004407 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004408 LValue LHSValue, RHSValue;
4409
4410 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4411 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004412 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004413
Richard Smith745f5142012-01-27 01:14:48 +00004414 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004415 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004416
Richard Smith625b8072011-10-31 01:37:14 +00004417 // Reject differing bases from the normal codepath; we special-case
4418 // comparisons to null.
4419 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004420 if (E->getOpcode() == BO_Sub) {
4421 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004422 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4423 return false;
4424 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4425 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4426 if (!LHSExpr || !RHSExpr)
4427 return false;
4428 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4429 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4430 if (!LHSAddrExpr || !RHSAddrExpr)
4431 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004432 // Make sure both labels come from the same function.
4433 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4434 RHSAddrExpr->getLabel()->getDeclContext())
4435 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004436 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4437 return true;
4438 }
Richard Smith9e36b532011-10-31 05:11:32 +00004439 // Inequalities and subtractions between unrelated pointers have
4440 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004441 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004442 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004443 // A constant address may compare equal to the address of a symbol.
4444 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004445 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004446 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4447 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004448 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004449 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004450 // distinct addresses. In clang, the result of such a comparison is
4451 // unspecified, so it is not a constant expression. However, we do know
4452 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004453 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4454 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004455 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004456 // We can't tell whether weak symbols will end up pointing to the same
4457 // object.
4458 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004459 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004460 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004461 // (Note that clang defaults to -fmerge-all-constants, which can
4462 // lead to inconsistent results for comparisons involving the address
4463 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004464 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004465 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004466
Richard Smith15efc4d2012-02-01 08:10:20 +00004467 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4468 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4469
Richard Smithf15fda02012-02-02 01:16:57 +00004470 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4471 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4472
John McCall2de56d12010-08-25 11:45:40 +00004473 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004474 // C++11 [expr.add]p6:
4475 // Unless both pointers point to elements of the same array object, or
4476 // one past the last element of the array object, the behavior is
4477 // undefined.
4478 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4479 !AreElementsOfSameArray(getType(LHSValue.Base),
4480 LHSDesignator, RHSDesignator))
4481 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4482
Chris Lattner4992bdd2010-04-20 17:13:14 +00004483 QualType Type = E->getLHS()->getType();
4484 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004485
Richard Smith180f4792011-11-10 06:34:14 +00004486 CharUnits ElementSize;
4487 if (!HandleSizeof(Info, ElementType, ElementSize))
4488 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004489
Richard Smith15efc4d2012-02-01 08:10:20 +00004490 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4491 // and produce incorrect results when it overflows. Such behavior
4492 // appears to be non-conforming, but is common, so perhaps we should
4493 // assume the standard intended for such cases to be undefined behavior
4494 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004495
Richard Smith15efc4d2012-02-01 08:10:20 +00004496 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4497 // overflow in the final conversion to ptrdiff_t.
4498 APSInt LHS(
4499 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4500 APSInt RHS(
4501 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4502 APSInt ElemSize(
4503 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4504 APSInt TrueResult = (LHS - RHS) / ElemSize;
4505 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4506
4507 if (Result.extend(65) != TrueResult)
4508 HandleOverflow(Info, E, TrueResult, E->getType());
4509 return Success(Result, E);
4510 }
Richard Smith82f28582012-01-31 06:41:30 +00004511
4512 // C++11 [expr.rel]p3:
4513 // Pointers to void (after pointer conversions) can be compared, with a
4514 // result defined as follows: If both pointers represent the same
4515 // address or are both the null pointer value, the result is true if the
4516 // operator is <= or >= and false otherwise; otherwise the result is
4517 // unspecified.
4518 // We interpret this as applying to pointers to *cv* void.
4519 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004520 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004521 CCEDiag(E, diag::note_constexpr_void_comparison);
4522
Richard Smithf15fda02012-02-02 01:16:57 +00004523 // C++11 [expr.rel]p2:
4524 // - If two pointers point to non-static data members of the same object,
4525 // or to subobjects or array elements fo such members, recursively, the
4526 // pointer to the later declared member compares greater provided the
4527 // two members have the same access control and provided their class is
4528 // not a union.
4529 // [...]
4530 // - Otherwise pointer comparisons are unspecified.
4531 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4532 E->isRelationalOp()) {
4533 bool WasArrayIndex;
4534 unsigned Mismatch =
4535 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4536 RHSDesignator, WasArrayIndex);
4537 // At the point where the designators diverge, the comparison has a
4538 // specified value if:
4539 // - we are comparing array indices
4540 // - we are comparing fields of a union, or fields with the same access
4541 // Otherwise, the result is unspecified and thus the comparison is not a
4542 // constant expression.
4543 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4544 Mismatch < RHSDesignator.Entries.size()) {
4545 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4546 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4547 if (!LF && !RF)
4548 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4549 else if (!LF)
4550 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4551 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4552 << RF->getParent() << RF;
4553 else if (!RF)
4554 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4555 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4556 << LF->getParent() << LF;
4557 else if (!LF->getParent()->isUnion() &&
4558 LF->getAccess() != RF->getAccess())
4559 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4560 << LF << LF->getAccess() << RF << RF->getAccess()
4561 << LF->getParent();
4562 }
4563 }
4564
Richard Smith625b8072011-10-31 01:37:14 +00004565 switch (E->getOpcode()) {
4566 default: llvm_unreachable("missing comparison operator");
4567 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4568 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4569 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4570 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4571 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4572 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004573 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004574 }
4575 }
Richard Smithb02e4622012-02-01 01:42:44 +00004576
4577 if (LHSTy->isMemberPointerType()) {
4578 assert(E->isEqualityOp() && "unexpected member pointer operation");
4579 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4580
4581 MemberPtr LHSValue, RHSValue;
4582
4583 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4584 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4585 return false;
4586
4587 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4588 return false;
4589
4590 // C++11 [expr.eq]p2:
4591 // If both operands are null, they compare equal. Otherwise if only one is
4592 // null, they compare unequal.
4593 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4594 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4595 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4596 }
4597
4598 // Otherwise if either is a pointer to a virtual member function, the
4599 // result is unspecified.
4600 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4601 if (MD->isVirtual())
4602 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4603 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4604 if (MD->isVirtual())
4605 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4606
4607 // Otherwise they compare equal if and only if they would refer to the
4608 // same member of the same most derived object or the same subobject if
4609 // they were dereferenced with a hypothetical object of the associated
4610 // class type.
4611 bool Equal = LHSValue == RHSValue;
4612 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4613 }
4614
Richard Smith26f2cac2012-02-14 22:35:28 +00004615 if (LHSTy->isNullPtrType()) {
4616 assert(E->isComparisonOp() && "unexpected nullptr operation");
4617 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4618 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4619 // are compared, the result is true of the operator is <=, >= or ==, and
4620 // false otherwise.
4621 BinaryOperator::Opcode Opcode = E->getOpcode();
4622 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4623 }
4624
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004625 if (!LHSTy->isIntegralOrEnumerationType() ||
4626 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004627 // We can't continue from here for non-integral types.
4628 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004629 }
4630
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004631 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004632 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004633
4634 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4635 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004636 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004637
Richard Smith745f5142012-01-27 01:14:48 +00004638 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004639 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004640
Richard Smith47a1eed2011-10-29 20:57:55 +00004641 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004642
4643 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004644 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004645 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4646 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004647 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004648 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004649 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004650 LHSVal.getLValueOffset() -= AdditionalOffset;
4651 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004652 return true;
4653 }
4654
4655 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004656 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004657 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004658 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4659 LHSVal.getInt().getZExtValue());
4660 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004661 return true;
4662 }
4663
Eli Friedman65639282012-01-04 23:13:47 +00004664 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4665 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004666 if (!LHSVal.getLValueOffset().isZero() ||
4667 !RHSVal.getLValueOffset().isZero())
4668 return false;
4669 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4670 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4671 if (!LHSExpr || !RHSExpr)
4672 return false;
4673 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4674 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4675 if (!LHSAddrExpr || !RHSAddrExpr)
4676 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004677 // Make sure both labels come from the same function.
4678 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4679 RHSAddrExpr->getLabel()->getDeclContext())
4680 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004681 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4682 return true;
4683 }
4684
Eli Friedman42edd0d2009-03-24 01:14:50 +00004685 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004686 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004687 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004688
Richard Smithc49bd112011-10-28 17:51:58 +00004689 APSInt &LHS = LHSVal.getInt();
4690 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004691
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004692 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004693 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004694 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004695 case BO_Mul:
4696 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4697 LHS.getBitWidth() * 2,
4698 std::multiplies<APSInt>()), E);
4699 case BO_Add:
4700 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4701 LHS.getBitWidth() + 1,
4702 std::plus<APSInt>()), E);
4703 case BO_Sub:
4704 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4705 LHS.getBitWidth() + 1,
4706 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004707 case BO_And: return Success(LHS & RHS, E);
4708 case BO_Xor: return Success(LHS ^ RHS, E);
4709 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004710 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004711 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004712 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004713 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004714 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4715 // actually undefined behavior in C++11 due to a language defect.
4716 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4717 LHS.isSigned() && LHS.isMinSignedValue())
4718 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4719 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004720 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004721 // During constant-folding, a negative shift is an opposite shift. Such a
4722 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004723 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004724 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004725 RHS = -RHS;
4726 goto shift_right;
4727 }
4728
4729 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004730 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4731 // shifted type.
4732 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4733 if (SA != RHS) {
4734 CCEDiag(E, diag::note_constexpr_large_shift)
4735 << RHS << E->getType() << LHS.getBitWidth();
4736 } else if (LHS.isSigned()) {
4737 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004738 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004739 if (LHS.isNegative())
4740 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004741 else if (LHS.countLeadingZeros() < SA)
4742 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004743 }
4744
Richard Smithc49bd112011-10-28 17:51:58 +00004745 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004746 }
John McCall2de56d12010-08-25 11:45:40 +00004747 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004748 // During constant-folding, a negative shift is an opposite shift. Such a
4749 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004750 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004751 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004752 RHS = -RHS;
4753 goto shift_left;
4754 }
4755
4756 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004757 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4758 // shifted type.
4759 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4760 if (SA != RHS)
4761 CCEDiag(E, diag::note_constexpr_large_shift)
4762 << RHS << E->getType() << LHS.getBitWidth();
4763
Richard Smithc49bd112011-10-28 17:51:58 +00004764 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004765 }
Mike Stump1eb44332009-09-09 15:08:12 +00004766
Richard Smithc49bd112011-10-28 17:51:58 +00004767 case BO_LT: return Success(LHS < RHS, E);
4768 case BO_GT: return Success(LHS > RHS, E);
4769 case BO_LE: return Success(LHS <= RHS, E);
4770 case BO_GE: return Success(LHS >= RHS, E);
4771 case BO_EQ: return Success(LHS == RHS, E);
4772 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004773 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004774}
4775
Ken Dyck8b752f12010-01-27 17:10:57 +00004776CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004777 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4778 // the result is the size of the referenced type."
4779 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4780 // result shall be the alignment of the referenced type."
4781 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4782 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004783
4784 // __alignof is defined to return the preferred alignment.
4785 return Info.Ctx.toCharUnitsFromBits(
4786 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004787}
4788
Ken Dyck8b752f12010-01-27 17:10:57 +00004789CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004790 E = E->IgnoreParens();
4791
4792 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004793 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004794 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004795 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4796 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004797
Chris Lattneraf707ab2009-01-24 21:53:27 +00004798 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004799 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4800 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004801
Chris Lattnere9feb472009-01-24 21:09:06 +00004802 return GetAlignOfType(E->getType());
4803}
4804
4805
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004806/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4807/// a result as the expression's type.
4808bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4809 const UnaryExprOrTypeTraitExpr *E) {
4810 switch(E->getKind()) {
4811 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004812 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004813 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004814 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004815 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004816 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004817
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004818 case UETT_VecStep: {
4819 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004820
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004821 if (Ty->isVectorType()) {
4822 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004823
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004824 // The vec_step built-in functions that take a 3-component
4825 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4826 if (n == 3)
4827 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004828
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004829 return Success(n, E);
4830 } else
4831 return Success(1, E);
4832 }
4833
4834 case UETT_SizeOf: {
4835 QualType SrcTy = E->getTypeOfArgument();
4836 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4837 // the result is the size of the referenced type."
4838 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4839 // result shall be the alignment of the referenced type."
4840 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4841 SrcTy = Ref->getPointeeType();
4842
Richard Smith180f4792011-11-10 06:34:14 +00004843 CharUnits Sizeof;
4844 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004845 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004846 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004847 }
4848 }
4849
4850 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004851}
4852
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004853bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004854 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004855 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004856 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004857 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004858 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004859 for (unsigned i = 0; i != n; ++i) {
4860 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4861 switch (ON.getKind()) {
4862 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004863 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004864 APSInt IdxResult;
4865 if (!EvaluateInteger(Idx, IdxResult, Info))
4866 return false;
4867 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4868 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004869 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004870 CurrentType = AT->getElementType();
4871 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4872 Result += IdxResult.getSExtValue() * ElementSize;
4873 break;
4874 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004875
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004876 case OffsetOfExpr::OffsetOfNode::Field: {
4877 FieldDecl *MemberDecl = ON.getField();
4878 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004879 if (!RT)
4880 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004881 RecordDecl *RD = RT->getDecl();
4882 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004883 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004884 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004885 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004886 CurrentType = MemberDecl->getType().getNonReferenceType();
4887 break;
4888 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004889
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004890 case OffsetOfExpr::OffsetOfNode::Identifier:
4891 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004892
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004893 case OffsetOfExpr::OffsetOfNode::Base: {
4894 CXXBaseSpecifier *BaseSpec = ON.getBase();
4895 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004896 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004897
4898 // Find the layout of the class whose base we are looking into.
4899 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004900 if (!RT)
4901 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004902 RecordDecl *RD = RT->getDecl();
4903 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4904
4905 // Find the base class itself.
4906 CurrentType = BaseSpec->getType();
4907 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4908 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004909 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004910
4911 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004912 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004913 break;
4914 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004915 }
4916 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004917 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004918}
4919
Chris Lattnerb542afe2008-07-11 19:10:17 +00004920bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004921 switch (E->getOpcode()) {
4922 default:
4923 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4924 // See C99 6.6p3.
4925 return Error(E);
4926 case UO_Extension:
4927 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4928 // If so, we could clear the diagnostic ID.
4929 return Visit(E->getSubExpr());
4930 case UO_Plus:
4931 // The result is just the value.
4932 return Visit(E->getSubExpr());
4933 case UO_Minus: {
4934 if (!Visit(E->getSubExpr()))
4935 return false;
4936 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004937 const APSInt &Value = Result.getInt();
4938 if (Value.isSigned() && Value.isMinSignedValue())
4939 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4940 E->getType());
4941 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004942 }
4943 case UO_Not: {
4944 if (!Visit(E->getSubExpr()))
4945 return false;
4946 if (!Result.isInt()) return Error(E);
4947 return Success(~Result.getInt(), E);
4948 }
4949 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004950 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004951 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004952 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004953 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004954 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004955 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004956}
Mike Stump1eb44332009-09-09 15:08:12 +00004957
Chris Lattner732b2232008-07-12 01:15:53 +00004958/// HandleCast - This is used to evaluate implicit or explicit casts where the
4959/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004960bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4961 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004962 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004963 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004964
Eli Friedman46a52322011-03-25 00:43:55 +00004965 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004966 case CK_BaseToDerived:
4967 case CK_DerivedToBase:
4968 case CK_UncheckedDerivedToBase:
4969 case CK_Dynamic:
4970 case CK_ToUnion:
4971 case CK_ArrayToPointerDecay:
4972 case CK_FunctionToPointerDecay:
4973 case CK_NullToPointer:
4974 case CK_NullToMemberPointer:
4975 case CK_BaseToDerivedMemberPointer:
4976 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00004977 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00004978 case CK_ConstructorConversion:
4979 case CK_IntegralToPointer:
4980 case CK_ToVoid:
4981 case CK_VectorSplat:
4982 case CK_IntegralToFloating:
4983 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004984 case CK_CPointerToObjCPointerCast:
4985 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004986 case CK_AnyPointerToBlockPointerCast:
4987 case CK_ObjCObjectLValueCast:
4988 case CK_FloatingRealToComplex:
4989 case CK_FloatingComplexToReal:
4990 case CK_FloatingComplexCast:
4991 case CK_FloatingComplexToIntegralComplex:
4992 case CK_IntegralRealToComplex:
4993 case CK_IntegralComplexCast:
4994 case CK_IntegralComplexToFloatingComplex:
4995 llvm_unreachable("invalid cast kind for integral value");
4996
Eli Friedmane50c2972011-03-25 19:07:11 +00004997 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004998 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004999 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005000 case CK_ARCProduceObject:
5001 case CK_ARCConsumeObject:
5002 case CK_ARCReclaimReturnedObject:
5003 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005004 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005005
Richard Smith7d580a42012-01-17 21:17:26 +00005006 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005007 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005008 case CK_AtomicToNonAtomic:
5009 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005010 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005011 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005012
5013 case CK_MemberPointerToBoolean:
5014 case CK_PointerToBoolean:
5015 case CK_IntegralToBoolean:
5016 case CK_FloatingToBoolean:
5017 case CK_FloatingComplexToBoolean:
5018 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005019 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005020 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005021 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005022 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005023 }
5024
Eli Friedman46a52322011-03-25 00:43:55 +00005025 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005026 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005027 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005028
Eli Friedmanbe265702009-02-20 01:15:07 +00005029 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005030 // Allow casts of address-of-label differences if they are no-ops
5031 // or narrowing. (The narrowing case isn't actually guaranteed to
5032 // be constant-evaluatable except in some narrow cases which are hard
5033 // to detect here. We let it through on the assumption the user knows
5034 // what they are doing.)
5035 if (Result.isAddrLabelDiff())
5036 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005037 // Only allow casts of lvalues if they are lossless.
5038 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5039 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005040
Richard Smithf72fccf2012-01-30 22:27:01 +00005041 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5042 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005043 }
Mike Stump1eb44332009-09-09 15:08:12 +00005044
Eli Friedman46a52322011-03-25 00:43:55 +00005045 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005046 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5047
John McCallefdb83e2010-05-07 21:00:08 +00005048 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005049 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005050 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005051
Daniel Dunbardd211642009-02-19 22:24:01 +00005052 if (LV.getLValueBase()) {
5053 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005054 // FIXME: Allow a larger integer size than the pointer size, and allow
5055 // narrowing back down to pointer width in subsequent integral casts.
5056 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005057 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005058 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005059
Richard Smithb755a9d2011-11-16 07:18:12 +00005060 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005061 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005062 return true;
5063 }
5064
Ken Dycka7305832010-01-15 12:37:54 +00005065 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5066 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005067 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005068 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005069
Eli Friedman46a52322011-03-25 00:43:55 +00005070 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005071 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005072 if (!EvaluateComplex(SubExpr, C, Info))
5073 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005074 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005075 }
Eli Friedman2217c872009-02-22 11:46:18 +00005076
Eli Friedman46a52322011-03-25 00:43:55 +00005077 case CK_FloatingToIntegral: {
5078 APFloat F(0.0);
5079 if (!EvaluateFloat(SubExpr, F, Info))
5080 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005081
Richard Smithc1c5f272011-12-13 06:39:58 +00005082 APSInt Value;
5083 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5084 return false;
5085 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005086 }
5087 }
Mike Stump1eb44332009-09-09 15:08:12 +00005088
Eli Friedman46a52322011-03-25 00:43:55 +00005089 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005090}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005091
Eli Friedman722c7172009-02-28 03:59:05 +00005092bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5093 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005094 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005095 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5096 return false;
5097 if (!LV.isComplexInt())
5098 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005099 return Success(LV.getComplexIntReal(), E);
5100 }
5101
5102 return Visit(E->getSubExpr());
5103}
5104
Eli Friedman664a1042009-02-27 04:45:43 +00005105bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005106 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005107 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005108 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5109 return false;
5110 if (!LV.isComplexInt())
5111 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005112 return Success(LV.getComplexIntImag(), E);
5113 }
5114
Richard Smith8327fad2011-10-24 18:44:57 +00005115 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005116 return Success(0, E);
5117}
5118
Douglas Gregoree8aff02011-01-04 17:33:58 +00005119bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5120 return Success(E->getPackLength(), E);
5121}
5122
Sebastian Redl295995c2010-09-10 20:55:47 +00005123bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5124 return Success(E->getValue(), E);
5125}
5126
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005127//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005128// Float Evaluation
5129//===----------------------------------------------------------------------===//
5130
5131namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005132class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005133 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005134 APFloat &Result;
5135public:
5136 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005137 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005138
Richard Smith47a1eed2011-10-29 20:57:55 +00005139 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005140 Result = V.getFloat();
5141 return true;
5142 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005143
Richard Smith51201882011-12-30 21:15:51 +00005144 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005145 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5146 return true;
5147 }
5148
Chris Lattner019f4e82008-10-06 05:28:25 +00005149 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005150
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005151 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005152 bool VisitBinaryOperator(const BinaryOperator *E);
5153 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005154 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005155
John McCallabd3a852010-05-07 22:08:54 +00005156 bool VisitUnaryReal(const UnaryOperator *E);
5157 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005158
Richard Smith51201882011-12-30 21:15:51 +00005159 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005160};
5161} // end anonymous namespace
5162
5163static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005164 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005165 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005166}
5167
Jay Foad4ba2a172011-01-12 09:06:06 +00005168static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005169 QualType ResultTy,
5170 const Expr *Arg,
5171 bool SNaN,
5172 llvm::APFloat &Result) {
5173 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5174 if (!S) return false;
5175
5176 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5177
5178 llvm::APInt fill;
5179
5180 // Treat empty strings as if they were zero.
5181 if (S->getString().empty())
5182 fill = llvm::APInt(32, 0);
5183 else if (S->getString().getAsInteger(0, fill))
5184 return false;
5185
5186 if (SNaN)
5187 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5188 else
5189 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5190 return true;
5191}
5192
Chris Lattner019f4e82008-10-06 05:28:25 +00005193bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005194 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005195 default:
5196 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5197
Chris Lattner019f4e82008-10-06 05:28:25 +00005198 case Builtin::BI__builtin_huge_val:
5199 case Builtin::BI__builtin_huge_valf:
5200 case Builtin::BI__builtin_huge_vall:
5201 case Builtin::BI__builtin_inf:
5202 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005203 case Builtin::BI__builtin_infl: {
5204 const llvm::fltSemantics &Sem =
5205 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005206 Result = llvm::APFloat::getInf(Sem);
5207 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005208 }
Mike Stump1eb44332009-09-09 15:08:12 +00005209
John McCalldb7b72a2010-02-28 13:00:19 +00005210 case Builtin::BI__builtin_nans:
5211 case Builtin::BI__builtin_nansf:
5212 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005213 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5214 true, Result))
5215 return Error(E);
5216 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005217
Chris Lattner9e621712008-10-06 06:31:58 +00005218 case Builtin::BI__builtin_nan:
5219 case Builtin::BI__builtin_nanf:
5220 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005221 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005222 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005223 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5224 false, Result))
5225 return Error(E);
5226 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005227
5228 case Builtin::BI__builtin_fabs:
5229 case Builtin::BI__builtin_fabsf:
5230 case Builtin::BI__builtin_fabsl:
5231 if (!EvaluateFloat(E->getArg(0), Result, Info))
5232 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005234 if (Result.isNegative())
5235 Result.changeSign();
5236 return true;
5237
Mike Stump1eb44332009-09-09 15:08:12 +00005238 case Builtin::BI__builtin_copysign:
5239 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005240 case Builtin::BI__builtin_copysignl: {
5241 APFloat RHS(0.);
5242 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5243 !EvaluateFloat(E->getArg(1), RHS, Info))
5244 return false;
5245 Result.copySign(RHS);
5246 return true;
5247 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005248 }
5249}
5250
John McCallabd3a852010-05-07 22:08:54 +00005251bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005252 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5253 ComplexValue CV;
5254 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5255 return false;
5256 Result = CV.FloatReal;
5257 return true;
5258 }
5259
5260 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005261}
5262
5263bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005264 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5265 ComplexValue CV;
5266 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5267 return false;
5268 Result = CV.FloatImag;
5269 return true;
5270 }
5271
Richard Smith8327fad2011-10-24 18:44:57 +00005272 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005273 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5274 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005275 return true;
5276}
5277
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005278bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005279 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005280 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005281 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005282 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005283 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005284 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5285 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005286 Result.changeSign();
5287 return true;
5288 }
5289}
Chris Lattner019f4e82008-10-06 05:28:25 +00005290
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005291bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005292 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5293 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005294
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005295 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005296 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5297 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005298 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005299 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005300 return false;
5301
5302 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005303 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005304 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005305 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005306 break;
John McCall2de56d12010-08-25 11:45:40 +00005307 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005308 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005309 break;
John McCall2de56d12010-08-25 11:45:40 +00005310 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005311 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005312 break;
John McCall2de56d12010-08-25 11:45:40 +00005313 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005314 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005315 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005316 }
Richard Smith7b48a292012-02-01 05:53:12 +00005317
5318 if (Result.isInfinity() || Result.isNaN())
5319 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5320 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005321}
5322
5323bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5324 Result = E->getValue();
5325 return true;
5326}
5327
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005328bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5329 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Eli Friedman2a523ee2011-03-25 00:54:52 +00005331 switch (E->getCastKind()) {
5332 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005333 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005334
5335 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005336 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005337 return EvaluateInteger(SubExpr, IntResult, Info) &&
5338 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5339 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005340 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005341
5342 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005343 if (!Visit(SubExpr))
5344 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005345 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5346 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005347 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005348
Eli Friedman2a523ee2011-03-25 00:54:52 +00005349 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005350 ComplexValue V;
5351 if (!EvaluateComplex(SubExpr, V, Info))
5352 return false;
5353 Result = V.getComplexFloatReal();
5354 return true;
5355 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005356 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005357}
5358
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005359//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005360// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005361//===----------------------------------------------------------------------===//
5362
5363namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005364class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005365 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005366 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005367
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005368public:
John McCallf4cf1a12010-05-07 17:22:02 +00005369 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005370 : ExprEvaluatorBaseTy(info), Result(Result) {}
5371
Richard Smith47a1eed2011-10-29 20:57:55 +00005372 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005373 Result.setFrom(V);
5374 return true;
5375 }
Mike Stump1eb44332009-09-09 15:08:12 +00005376
Eli Friedman7ead5c72012-01-10 04:58:17 +00005377 bool ZeroInitialization(const Expr *E);
5378
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005379 //===--------------------------------------------------------------------===//
5380 // Visitor Methods
5381 //===--------------------------------------------------------------------===//
5382
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005383 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005384 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005385 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005386 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005387 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005388};
5389} // end anonymous namespace
5390
John McCallf4cf1a12010-05-07 17:22:02 +00005391static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5392 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005393 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005394 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005395}
5396
Eli Friedman7ead5c72012-01-10 04:58:17 +00005397bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005398 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005399 if (ElemTy->isRealFloatingType()) {
5400 Result.makeComplexFloat();
5401 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5402 Result.FloatReal = Zero;
5403 Result.FloatImag = Zero;
5404 } else {
5405 Result.makeComplexInt();
5406 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5407 Result.IntReal = Zero;
5408 Result.IntImag = Zero;
5409 }
5410 return true;
5411}
5412
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005413bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5414 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005415
5416 if (SubExpr->getType()->isRealFloatingType()) {
5417 Result.makeComplexFloat();
5418 APFloat &Imag = Result.FloatImag;
5419 if (!EvaluateFloat(SubExpr, Imag, Info))
5420 return false;
5421
5422 Result.FloatReal = APFloat(Imag.getSemantics());
5423 return true;
5424 } else {
5425 assert(SubExpr->getType()->isIntegerType() &&
5426 "Unexpected imaginary literal.");
5427
5428 Result.makeComplexInt();
5429 APSInt &Imag = Result.IntImag;
5430 if (!EvaluateInteger(SubExpr, Imag, Info))
5431 return false;
5432
5433 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5434 return true;
5435 }
5436}
5437
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005438bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005439
John McCall8786da72010-12-14 17:51:41 +00005440 switch (E->getCastKind()) {
5441 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005442 case CK_BaseToDerived:
5443 case CK_DerivedToBase:
5444 case CK_UncheckedDerivedToBase:
5445 case CK_Dynamic:
5446 case CK_ToUnion:
5447 case CK_ArrayToPointerDecay:
5448 case CK_FunctionToPointerDecay:
5449 case CK_NullToPointer:
5450 case CK_NullToMemberPointer:
5451 case CK_BaseToDerivedMemberPointer:
5452 case CK_DerivedToBaseMemberPointer:
5453 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005454 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005455 case CK_ConstructorConversion:
5456 case CK_IntegralToPointer:
5457 case CK_PointerToIntegral:
5458 case CK_PointerToBoolean:
5459 case CK_ToVoid:
5460 case CK_VectorSplat:
5461 case CK_IntegralCast:
5462 case CK_IntegralToBoolean:
5463 case CK_IntegralToFloating:
5464 case CK_FloatingToIntegral:
5465 case CK_FloatingToBoolean:
5466 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005467 case CK_CPointerToObjCPointerCast:
5468 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005469 case CK_AnyPointerToBlockPointerCast:
5470 case CK_ObjCObjectLValueCast:
5471 case CK_FloatingComplexToReal:
5472 case CK_FloatingComplexToBoolean:
5473 case CK_IntegralComplexToReal:
5474 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005475 case CK_ARCProduceObject:
5476 case CK_ARCConsumeObject:
5477 case CK_ARCReclaimReturnedObject:
5478 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005479 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005480
John McCall8786da72010-12-14 17:51:41 +00005481 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005482 case CK_AtomicToNonAtomic:
5483 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005484 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005485 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005486
5487 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005488 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005489 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005490 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005491
5492 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005493 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005494 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005495 return false;
5496
John McCall8786da72010-12-14 17:51:41 +00005497 Result.makeComplexFloat();
5498 Result.FloatImag = APFloat(Real.getSemantics());
5499 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005500 }
5501
John McCall8786da72010-12-14 17:51:41 +00005502 case CK_FloatingComplexCast: {
5503 if (!Visit(E->getSubExpr()))
5504 return false;
5505
5506 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5507 QualType From
5508 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5509
Richard Smithc1c5f272011-12-13 06:39:58 +00005510 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5511 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005512 }
5513
5514 case CK_FloatingComplexToIntegralComplex: {
5515 if (!Visit(E->getSubExpr()))
5516 return false;
5517
5518 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5519 QualType From
5520 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5521 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005522 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5523 To, Result.IntReal) &&
5524 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5525 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005526 }
5527
5528 case CK_IntegralRealToComplex: {
5529 APSInt &Real = Result.IntReal;
5530 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5531 return false;
5532
5533 Result.makeComplexInt();
5534 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5535 return true;
5536 }
5537
5538 case CK_IntegralComplexCast: {
5539 if (!Visit(E->getSubExpr()))
5540 return false;
5541
5542 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5543 QualType From
5544 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5545
Richard Smithf72fccf2012-01-30 22:27:01 +00005546 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5547 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005548 return true;
5549 }
5550
5551 case CK_IntegralComplexToFloatingComplex: {
5552 if (!Visit(E->getSubExpr()))
5553 return false;
5554
5555 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5556 QualType From
5557 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5558 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005559 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5560 To, Result.FloatReal) &&
5561 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5562 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005563 }
5564 }
5565
5566 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005567}
5568
John McCallf4cf1a12010-05-07 17:22:02 +00005569bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005570 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005571 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5572
Richard Smith745f5142012-01-27 01:14:48 +00005573 bool LHSOK = Visit(E->getLHS());
5574 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005575 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005576
John McCallf4cf1a12010-05-07 17:22:02 +00005577 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005578 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005579 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005580
Daniel Dunbar3f279872009-01-29 01:32:56 +00005581 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5582 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005583 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005584 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005585 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005586 if (Result.isComplexFloat()) {
5587 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5588 APFloat::rmNearestTiesToEven);
5589 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5590 APFloat::rmNearestTiesToEven);
5591 } else {
5592 Result.getComplexIntReal() += RHS.getComplexIntReal();
5593 Result.getComplexIntImag() += RHS.getComplexIntImag();
5594 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005595 break;
John McCall2de56d12010-08-25 11:45:40 +00005596 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005597 if (Result.isComplexFloat()) {
5598 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5599 APFloat::rmNearestTiesToEven);
5600 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5601 APFloat::rmNearestTiesToEven);
5602 } else {
5603 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5604 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5605 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005606 break;
John McCall2de56d12010-08-25 11:45:40 +00005607 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005608 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005609 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005610 APFloat &LHS_r = LHS.getComplexFloatReal();
5611 APFloat &LHS_i = LHS.getComplexFloatImag();
5612 APFloat &RHS_r = RHS.getComplexFloatReal();
5613 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Daniel Dunbar3f279872009-01-29 01:32:56 +00005615 APFloat Tmp = LHS_r;
5616 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5617 Result.getComplexFloatReal() = Tmp;
5618 Tmp = LHS_i;
5619 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5620 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5621
5622 Tmp = LHS_r;
5623 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5624 Result.getComplexFloatImag() = Tmp;
5625 Tmp = LHS_i;
5626 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5627 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5628 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005629 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005630 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005631 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5632 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005633 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005634 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5635 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5636 }
5637 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005638 case BO_Div:
5639 if (Result.isComplexFloat()) {
5640 ComplexValue LHS = Result;
5641 APFloat &LHS_r = LHS.getComplexFloatReal();
5642 APFloat &LHS_i = LHS.getComplexFloatImag();
5643 APFloat &RHS_r = RHS.getComplexFloatReal();
5644 APFloat &RHS_i = RHS.getComplexFloatImag();
5645 APFloat &Res_r = Result.getComplexFloatReal();
5646 APFloat &Res_i = Result.getComplexFloatImag();
5647
5648 APFloat Den = RHS_r;
5649 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5650 APFloat Tmp = RHS_i;
5651 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5652 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5653
5654 Res_r = LHS_r;
5655 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5656 Tmp = LHS_i;
5657 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5658 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5659 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5660
5661 Res_i = LHS_i;
5662 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5663 Tmp = LHS_r;
5664 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5665 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5666 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5667 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005668 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5669 return Error(E, diag::note_expr_divide_by_zero);
5670
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005671 ComplexValue LHS = Result;
5672 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5673 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5674 Result.getComplexIntReal() =
5675 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5676 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5677 Result.getComplexIntImag() =
5678 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5679 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5680 }
5681 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005682 }
5683
John McCallf4cf1a12010-05-07 17:22:02 +00005684 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005685}
5686
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005687bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5688 // Get the operand value into 'Result'.
5689 if (!Visit(E->getSubExpr()))
5690 return false;
5691
5692 switch (E->getOpcode()) {
5693 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005694 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005695 case UO_Extension:
5696 return true;
5697 case UO_Plus:
5698 // The result is always just the subexpr.
5699 return true;
5700 case UO_Minus:
5701 if (Result.isComplexFloat()) {
5702 Result.getComplexFloatReal().changeSign();
5703 Result.getComplexFloatImag().changeSign();
5704 }
5705 else {
5706 Result.getComplexIntReal() = -Result.getComplexIntReal();
5707 Result.getComplexIntImag() = -Result.getComplexIntImag();
5708 }
5709 return true;
5710 case UO_Not:
5711 if (Result.isComplexFloat())
5712 Result.getComplexFloatImag().changeSign();
5713 else
5714 Result.getComplexIntImag() = -Result.getComplexIntImag();
5715 return true;
5716 }
5717}
5718
Eli Friedman7ead5c72012-01-10 04:58:17 +00005719bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5720 if (E->getNumInits() == 2) {
5721 if (E->getType()->isComplexType()) {
5722 Result.makeComplexFloat();
5723 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5724 return false;
5725 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5726 return false;
5727 } else {
5728 Result.makeComplexInt();
5729 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5730 return false;
5731 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5732 return false;
5733 }
5734 return true;
5735 }
5736 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5737}
5738
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005739//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005740// Void expression evaluation, primarily for a cast to void on the LHS of a
5741// comma operator
5742//===----------------------------------------------------------------------===//
5743
5744namespace {
5745class VoidExprEvaluator
5746 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5747public:
5748 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5749
5750 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005751
5752 bool VisitCastExpr(const CastExpr *E) {
5753 switch (E->getCastKind()) {
5754 default:
5755 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5756 case CK_ToVoid:
5757 VisitIgnoredValue(E->getSubExpr());
5758 return true;
5759 }
5760 }
5761};
5762} // end anonymous namespace
5763
5764static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5765 assert(E->isRValue() && E->getType()->isVoidType());
5766 return VoidExprEvaluator(Info).Visit(E);
5767}
5768
5769//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005770// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005771//===----------------------------------------------------------------------===//
5772
Richard Smith47a1eed2011-10-29 20:57:55 +00005773static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005774 // In C, function designators are not lvalues, but we evaluate them as if they
5775 // are.
5776 if (E->isGLValue() || E->getType()->isFunctionType()) {
5777 LValue LV;
5778 if (!EvaluateLValue(E, LV, Info))
5779 return false;
5780 LV.moveInto(Result);
5781 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005782 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005783 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005784 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005785 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005786 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005787 } else if (E->getType()->hasPointerRepresentation()) {
5788 LValue LV;
5789 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005790 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005791 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005792 } else if (E->getType()->isRealFloatingType()) {
5793 llvm::APFloat F(0.0);
5794 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005795 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005796 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005797 } else if (E->getType()->isAnyComplexType()) {
5798 ComplexValue C;
5799 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005800 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005801 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005802 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005803 MemberPtr P;
5804 if (!EvaluateMemberPointer(E, P, Info))
5805 return false;
5806 P.moveInto(Result);
5807 return true;
Richard Smith51201882011-12-30 21:15:51 +00005808 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005809 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005810 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005811 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005812 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005813 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005814 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005815 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005816 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005817 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5818 return false;
5819 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005820 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005821 if (Info.getLangOpts().CPlusPlus0x)
5822 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5823 << E->getType();
5824 else
5825 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005826 if (!EvaluateVoid(E, Info))
5827 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005828 } else if (Info.getLangOpts().CPlusPlus0x) {
5829 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5830 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005831 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005832 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005833 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005834 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005835
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005836 return true;
5837}
5838
Richard Smith69c2c502011-11-04 05:33:44 +00005839/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5840/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5841/// since later initializers for an object can indirectly refer to subobjects
5842/// which were initialized earlier.
5843static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005844 const LValue &This, const Expr *E,
Richard Smith7ca48502012-02-13 22:16:19 +00005845 CheckConstantExpressionKind CCEK,
5846 bool AllowNonLiteralTypes) {
5847 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005848 return false;
5849
5850 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005851 // Evaluate arrays and record types in-place, so that later initializers can
5852 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005853 if (E->getType()->isArrayType())
5854 return EvaluateArray(E, This, Result, Info);
5855 else if (E->getType()->isRecordType())
5856 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005857 }
5858
5859 // For any other type, in-place evaluation is unimportant.
5860 CCValue CoreConstResult;
5861 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005862 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005863}
5864
Richard Smithf48fdb02011-12-09 22:58:01 +00005865/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5866/// lvalue-to-rvalue cast if it is an lvalue.
5867static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005868 if (!CheckLiteralType(Info, E))
5869 return false;
5870
Richard Smithf48fdb02011-12-09 22:58:01 +00005871 CCValue Value;
5872 if (!::Evaluate(Value, Info, E))
5873 return false;
5874
5875 if (E->isGLValue()) {
5876 LValue LV;
5877 LV.setFrom(Value);
5878 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5879 return false;
5880 }
5881
5882 // Check this core constant expression is a constant expression, and if so,
5883 // convert it to one.
5884 return CheckConstantExpression(Info, E, Value, Result);
5885}
Richard Smithc49bd112011-10-28 17:51:58 +00005886
Richard Smith51f47082011-10-29 00:50:52 +00005887/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005888/// any crazy technique (that has nothing to do with language standards) that
5889/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005890/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5891/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005892bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005893 // Fast-path evaluations of integer literals, since we sometimes see files
5894 // containing vast quantities of these.
5895 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5896 Result.Val = APValue(APSInt(L->getValue(),
5897 L->getType()->isUnsignedIntegerType()));
5898 return true;
5899 }
5900
Richard Smith2d6a5672012-01-14 04:30:29 +00005901 // FIXME: Evaluating values of large array and record types can cause
5902 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005903 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5904 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005905 return false;
5906
Richard Smithf48fdb02011-12-09 22:58:01 +00005907 EvalInfo Info(Ctx, Result);
5908 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005909}
5910
Jay Foad4ba2a172011-01-12 09:06:06 +00005911bool Expr::EvaluateAsBooleanCondition(bool &Result,
5912 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005913 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005914 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005915 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5916 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005917 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005918}
5919
Richard Smith80d4b552011-12-28 19:48:30 +00005920bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5921 SideEffectsKind AllowSideEffects) const {
5922 if (!getType()->isIntegralOrEnumerationType())
5923 return false;
5924
Richard Smithc49bd112011-10-28 17:51:58 +00005925 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005926 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5927 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005928 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005929
Richard Smithc49bd112011-10-28 17:51:58 +00005930 Result = ExprResult.Val.getInt();
5931 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005932}
5933
Jay Foad4ba2a172011-01-12 09:06:06 +00005934bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005935 EvalInfo Info(Ctx, Result);
5936
John McCallefdb83e2010-05-07 21:00:08 +00005937 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005938 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005939 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5940 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005941}
5942
Richard Smith099e7f62011-12-19 06:19:21 +00005943bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5944 const VarDecl *VD,
5945 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005946 // FIXME: Evaluating initializers for large array and record types can cause
5947 // performance problems. Only do so in C++11 for now.
5948 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5949 !Ctx.getLangOptions().CPlusPlus0x)
5950 return false;
5951
Richard Smith099e7f62011-12-19 06:19:21 +00005952 Expr::EvalStatus EStatus;
5953 EStatus.Diag = &Notes;
5954
5955 EvalInfo InitInfo(Ctx, EStatus);
5956 InitInfo.setEvaluatingDecl(VD, Value);
5957
5958 LValue LVal;
5959 LVal.set(VD);
5960
Richard Smith51201882011-12-30 21:15:51 +00005961 // C++11 [basic.start.init]p2:
5962 // Variables with static storage duration or thread storage duration shall be
5963 // zero-initialized before any other initialization takes place.
5964 // This behavior is not present in C.
5965 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5966 !VD->getType()->isReferenceType()) {
5967 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7ca48502012-02-13 22:16:19 +00005968 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE, CCEK_Constant,
5969 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00005970 return false;
5971 }
5972
Richard Smith7ca48502012-02-13 22:16:19 +00005973 return EvaluateConstantExpression(Value, InitInfo, LVal, this, CCEK_Constant,
5974 /*AllowNonLiteralTypes=*/true) &&
Richard Smith099e7f62011-12-19 06:19:21 +00005975 !EStatus.HasSideEffects;
5976}
5977
Richard Smith51f47082011-10-29 00:50:52 +00005978/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5979/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005980bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005981 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005982 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005983}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005984
Jay Foad4ba2a172011-01-12 09:06:06 +00005985bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005986 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005987}
5988
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005989APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005990 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005991 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005992 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005993 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005994 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005995
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005996 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005997}
John McCalld905f5a2010-05-07 05:32:02 +00005998
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005999 bool Expr::EvalResult::isGlobalLValue() const {
6000 assert(Val.isLValue());
6001 return IsGlobalLValue(Val.getLValueBase());
6002 }
6003
6004
John McCalld905f5a2010-05-07 05:32:02 +00006005/// isIntegerConstantExpr - this recursive routine will test if an expression is
6006/// an integer constant expression.
6007
6008/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6009/// comma, etc
6010///
6011/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6012/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6013/// cast+dereference.
6014
6015// CheckICE - This function does the fundamental ICE checking: the returned
6016// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6017// Note that to reduce code duplication, this helper does no evaluation
6018// itself; the caller checks whether the expression is evaluatable, and
6019// in the rare cases where CheckICE actually cares about the evaluated
6020// value, it calls into Evalute.
6021//
6022// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006023// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006024// 1: This expression is not an ICE, but if it isn't evaluated, it's
6025// a legal subexpression for an ICE. This return value is used to handle
6026// the comma operator in C99 mode.
6027// 2: This expression is not an ICE, and is not a legal subexpression for one.
6028
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006029namespace {
6030
John McCalld905f5a2010-05-07 05:32:02 +00006031struct ICEDiag {
6032 unsigned Val;
6033 SourceLocation Loc;
6034
6035 public:
6036 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6037 ICEDiag() : Val(0) {}
6038};
6039
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006040}
6041
6042static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006043
6044static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6045 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006046 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006047 !EVResult.Val.isInt()) {
6048 return ICEDiag(2, E->getLocStart());
6049 }
6050 return NoDiag();
6051}
6052
6053static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6054 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006055 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006056 return ICEDiag(2, E->getLocStart());
6057 }
6058
6059 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006060#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006061#define STMT(Node, Base) case Expr::Node##Class:
6062#define EXPR(Node, Base)
6063#include "clang/AST/StmtNodes.inc"
6064 case Expr::PredefinedExprClass:
6065 case Expr::FloatingLiteralClass:
6066 case Expr::ImaginaryLiteralClass:
6067 case Expr::StringLiteralClass:
6068 case Expr::ArraySubscriptExprClass:
6069 case Expr::MemberExprClass:
6070 case Expr::CompoundAssignOperatorClass:
6071 case Expr::CompoundLiteralExprClass:
6072 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006073 case Expr::DesignatedInitExprClass:
6074 case Expr::ImplicitValueInitExprClass:
6075 case Expr::ParenListExprClass:
6076 case Expr::VAArgExprClass:
6077 case Expr::AddrLabelExprClass:
6078 case Expr::StmtExprClass:
6079 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006080 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006081 case Expr::CXXDynamicCastExprClass:
6082 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006083 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006084 case Expr::CXXNullPtrLiteralExprClass:
6085 case Expr::CXXThisExprClass:
6086 case Expr::CXXThrowExprClass:
6087 case Expr::CXXNewExprClass:
6088 case Expr::CXXDeleteExprClass:
6089 case Expr::CXXPseudoDestructorExprClass:
6090 case Expr::UnresolvedLookupExprClass:
6091 case Expr::DependentScopeDeclRefExprClass:
6092 case Expr::CXXConstructExprClass:
6093 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006094 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006095 case Expr::CXXTemporaryObjectExprClass:
6096 case Expr::CXXUnresolvedConstructExprClass:
6097 case Expr::CXXDependentScopeMemberExprClass:
6098 case Expr::UnresolvedMemberExprClass:
6099 case Expr::ObjCStringLiteralClass:
6100 case Expr::ObjCEncodeExprClass:
6101 case Expr::ObjCMessageExprClass:
6102 case Expr::ObjCSelectorExprClass:
6103 case Expr::ObjCProtocolExprClass:
6104 case Expr::ObjCIvarRefExprClass:
6105 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006106 case Expr::ObjCIsaExprClass:
6107 case Expr::ShuffleVectorExprClass:
6108 case Expr::BlockExprClass:
6109 case Expr::BlockDeclRefExprClass:
6110 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006111 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006112 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006113 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006114 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006115 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006116 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006117 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006118 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006119 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006120 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006121 return ICEDiag(2, E->getLocStart());
6122
Douglas Gregoree8aff02011-01-04 17:33:58 +00006123 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006124 case Expr::GNUNullExprClass:
6125 // GCC considers the GNU __null value to be an integral constant expression.
6126 return NoDiag();
6127
John McCall91a57552011-07-15 05:09:51 +00006128 case Expr::SubstNonTypeTemplateParmExprClass:
6129 return
6130 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6131
John McCalld905f5a2010-05-07 05:32:02 +00006132 case Expr::ParenExprClass:
6133 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006134 case Expr::GenericSelectionExprClass:
6135 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006136 case Expr::IntegerLiteralClass:
6137 case Expr::CharacterLiteralClass:
6138 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006139 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006140 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006141 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006142 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006143 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006144 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006145 return NoDiag();
6146 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006147 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006148 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6149 // constant expressions, but they can never be ICEs because an ICE cannot
6150 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006151 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006152 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006153 return CheckEvalInICE(E, Ctx);
6154 return ICEDiag(2, E->getLocStart());
6155 }
6156 case Expr::DeclRefExprClass:
6157 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6158 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006159 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006160 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6161
6162 // Parameter variables are never constants. Without this check,
6163 // getAnyInitializer() can find a default argument, which leads
6164 // to chaos.
6165 if (isa<ParmVarDecl>(D))
6166 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6167
6168 // C++ 7.1.5.1p2
6169 // A variable of non-volatile const-qualified integral or enumeration
6170 // type initialized by an ICE can be used in ICEs.
6171 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006172 if (!Dcl->getType()->isIntegralOrEnumerationType())
6173 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6174
Richard Smith099e7f62011-12-19 06:19:21 +00006175 const VarDecl *VD;
6176 // Look for a declaration of this variable that has an initializer, and
6177 // check whether it is an ICE.
6178 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6179 return NoDiag();
6180 else
6181 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006182 }
6183 }
6184 return ICEDiag(2, E->getLocStart());
6185 case Expr::UnaryOperatorClass: {
6186 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6187 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006188 case UO_PostInc:
6189 case UO_PostDec:
6190 case UO_PreInc:
6191 case UO_PreDec:
6192 case UO_AddrOf:
6193 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006194 // C99 6.6/3 allows increment and decrement within unevaluated
6195 // subexpressions of constant expressions, but they can never be ICEs
6196 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006197 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006198 case UO_Extension:
6199 case UO_LNot:
6200 case UO_Plus:
6201 case UO_Minus:
6202 case UO_Not:
6203 case UO_Real:
6204 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006205 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006206 }
6207
6208 // OffsetOf falls through here.
6209 }
6210 case Expr::OffsetOfExprClass: {
6211 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006212 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006213 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006214 // compliance: we should warn earlier for offsetof expressions with
6215 // array subscripts that aren't ICEs, and if the array subscripts
6216 // are ICEs, the value of the offsetof must be an integer constant.
6217 return CheckEvalInICE(E, Ctx);
6218 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006219 case Expr::UnaryExprOrTypeTraitExprClass: {
6220 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6221 if ((Exp->getKind() == UETT_SizeOf) &&
6222 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006223 return ICEDiag(2, E->getLocStart());
6224 return NoDiag();
6225 }
6226 case Expr::BinaryOperatorClass: {
6227 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6228 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006229 case BO_PtrMemD:
6230 case BO_PtrMemI:
6231 case BO_Assign:
6232 case BO_MulAssign:
6233 case BO_DivAssign:
6234 case BO_RemAssign:
6235 case BO_AddAssign:
6236 case BO_SubAssign:
6237 case BO_ShlAssign:
6238 case BO_ShrAssign:
6239 case BO_AndAssign:
6240 case BO_XorAssign:
6241 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006242 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6243 // constant expressions, but they can never be ICEs because an ICE cannot
6244 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006245 return ICEDiag(2, E->getLocStart());
6246
John McCall2de56d12010-08-25 11:45:40 +00006247 case BO_Mul:
6248 case BO_Div:
6249 case BO_Rem:
6250 case BO_Add:
6251 case BO_Sub:
6252 case BO_Shl:
6253 case BO_Shr:
6254 case BO_LT:
6255 case BO_GT:
6256 case BO_LE:
6257 case BO_GE:
6258 case BO_EQ:
6259 case BO_NE:
6260 case BO_And:
6261 case BO_Xor:
6262 case BO_Or:
6263 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006264 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6265 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006266 if (Exp->getOpcode() == BO_Div ||
6267 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006268 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006269 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006270 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006271 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006272 if (REval == 0)
6273 return ICEDiag(1, E->getLocStart());
6274 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006275 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006276 if (LEval.isMinSignedValue())
6277 return ICEDiag(1, E->getLocStart());
6278 }
6279 }
6280 }
John McCall2de56d12010-08-25 11:45:40 +00006281 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006282 if (Ctx.getLangOptions().C99) {
6283 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6284 // if it isn't evaluated.
6285 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6286 return ICEDiag(1, E->getLocStart());
6287 } else {
6288 // In both C89 and C++, commas in ICEs are illegal.
6289 return ICEDiag(2, E->getLocStart());
6290 }
6291 }
6292 if (LHSResult.Val >= RHSResult.Val)
6293 return LHSResult;
6294 return RHSResult;
6295 }
John McCall2de56d12010-08-25 11:45:40 +00006296 case BO_LAnd:
6297 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006298 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6299 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6300 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6301 // Rare case where the RHS has a comma "side-effect"; we need
6302 // to actually check the condition to see whether the side
6303 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006304 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006305 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006306 return RHSResult;
6307 return NoDiag();
6308 }
6309
6310 if (LHSResult.Val >= RHSResult.Val)
6311 return LHSResult;
6312 return RHSResult;
6313 }
6314 }
6315 }
6316 case Expr::ImplicitCastExprClass:
6317 case Expr::CStyleCastExprClass:
6318 case Expr::CXXFunctionalCastExprClass:
6319 case Expr::CXXStaticCastExprClass:
6320 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006321 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006322 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006323 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006324 if (isa<ExplicitCastExpr>(E)) {
6325 if (const FloatingLiteral *FL
6326 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6327 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6328 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6329 APSInt IgnoredVal(DestWidth, !DestSigned);
6330 bool Ignored;
6331 // If the value does not fit in the destination type, the behavior is
6332 // undefined, so we are not required to treat it as a constant
6333 // expression.
6334 if (FL->getValue().convertToInteger(IgnoredVal,
6335 llvm::APFloat::rmTowardZero,
6336 &Ignored) & APFloat::opInvalidOp)
6337 return ICEDiag(2, E->getLocStart());
6338 return NoDiag();
6339 }
6340 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006341 switch (cast<CastExpr>(E)->getCastKind()) {
6342 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006343 case CK_AtomicToNonAtomic:
6344 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006345 case CK_NoOp:
6346 case CK_IntegralToBoolean:
6347 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006348 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006349 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006350 return ICEDiag(2, E->getLocStart());
6351 }
John McCalld905f5a2010-05-07 05:32:02 +00006352 }
John McCall56ca35d2011-02-17 10:25:35 +00006353 case Expr::BinaryConditionalOperatorClass: {
6354 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6355 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6356 if (CommonResult.Val == 2) return CommonResult;
6357 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6358 if (FalseResult.Val == 2) return FalseResult;
6359 if (CommonResult.Val == 1) return CommonResult;
6360 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006361 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006362 return FalseResult;
6363 }
John McCalld905f5a2010-05-07 05:32:02 +00006364 case Expr::ConditionalOperatorClass: {
6365 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6366 // If the condition (ignoring parens) is a __builtin_constant_p call,
6367 // then only the true side is actually considered in an integer constant
6368 // expression, and it is fully evaluated. This is an important GNU
6369 // extension. See GCC PR38377 for discussion.
6370 if (const CallExpr *CallCE
6371 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006372 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6373 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006374 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006375 if (CondResult.Val == 2)
6376 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006377
Richard Smithf48fdb02011-12-09 22:58:01 +00006378 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6379 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006380
John McCalld905f5a2010-05-07 05:32:02 +00006381 if (TrueResult.Val == 2)
6382 return TrueResult;
6383 if (FalseResult.Val == 2)
6384 return FalseResult;
6385 if (CondResult.Val == 1)
6386 return CondResult;
6387 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6388 return NoDiag();
6389 // Rare case where the diagnostics depend on which side is evaluated
6390 // Note that if we get here, CondResult is 0, and at least one of
6391 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006392 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006393 return FalseResult;
6394 }
6395 return TrueResult;
6396 }
6397 case Expr::CXXDefaultArgExprClass:
6398 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6399 case Expr::ChooseExprClass: {
6400 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6401 }
6402 }
6403
David Blaikie30263482012-01-20 21:50:17 +00006404 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006405}
6406
Richard Smithf48fdb02011-12-09 22:58:01 +00006407/// Evaluate an expression as a C++11 integral constant expression.
6408static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6409 const Expr *E,
6410 llvm::APSInt *Value,
6411 SourceLocation *Loc) {
6412 if (!E->getType()->isIntegralOrEnumerationType()) {
6413 if (Loc) *Loc = E->getExprLoc();
6414 return false;
6415 }
6416
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006417 APValue Result;
6418 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006419 return false;
6420
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006421 assert(Result.isInt() && "pointer cast to int is not an ICE");
6422 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006423 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006424}
6425
Richard Smithdd1f29b2011-12-12 09:28:41 +00006426bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006427 if (Ctx.getLangOptions().CPlusPlus0x)
6428 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6429
John McCalld905f5a2010-05-07 05:32:02 +00006430 ICEDiag d = CheckICE(this, Ctx);
6431 if (d.Val != 0) {
6432 if (Loc) *Loc = d.Loc;
6433 return false;
6434 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006435 return true;
6436}
6437
6438bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6439 SourceLocation *Loc, bool isEvaluated) const {
6440 if (Ctx.getLangOptions().CPlusPlus0x)
6441 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6442
6443 if (!isIntegerConstantExpr(Ctx, Loc))
6444 return false;
6445 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006446 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006447 return true;
6448}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006449
Richard Smith70488e22012-02-14 21:38:30 +00006450bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6451 return CheckICE(this, Ctx).Val == 0;
6452}
6453
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006454bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6455 SourceLocation *Loc) const {
6456 // We support this checking in C++98 mode in order to diagnose compatibility
6457 // issues.
6458 assert(Ctx.getLangOptions().CPlusPlus);
6459
Richard Smith70488e22012-02-14 21:38:30 +00006460 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006461 Expr::EvalStatus Status;
6462 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6463 Status.Diag = &Diags;
6464 EvalInfo Info(Ctx, Status);
6465
6466 APValue Scratch;
6467 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6468
6469 if (!Diags.empty()) {
6470 IsConstExpr = false;
6471 if (Loc) *Loc = Diags[0].first;
6472 } else if (!IsConstExpr) {
6473 // FIXME: This shouldn't happen.
6474 if (Loc) *Loc = getExprLoc();
6475 }
6476
6477 return IsConstExpr;
6478}
Richard Smith745f5142012-01-27 01:14:48 +00006479
6480bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6481 llvm::SmallVectorImpl<
6482 PartialDiagnosticAt> &Diags) {
6483 // FIXME: It would be useful to check constexpr function templates, but at the
6484 // moment the constant expression evaluator cannot cope with the non-rigorous
6485 // ASTs which we build for dependent expressions.
6486 if (FD->isDependentContext())
6487 return true;
6488
6489 Expr::EvalStatus Status;
6490 Status.Diag = &Diags;
6491
6492 EvalInfo Info(FD->getASTContext(), Status);
6493 Info.CheckingPotentialConstantExpression = true;
6494
6495 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6496 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6497
6498 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6499 // is a temporary being used as the 'this' pointer.
6500 LValue This;
6501 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6502 This.set(&VIE, Info.CurrentCall);
6503
6504 APValue Scratch;
6505 ArrayRef<const Expr*> Args;
6506
6507 SourceLocation Loc = FD->getLocation();
6508
6509 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6510 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6511 } else
6512 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6513 Args, FD->getBody(), Info, Scratch);
6514
6515 return Diags.empty();
6516}