blob: e33d22a4aa35cbdb950f9de6112dde631a367191 [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
858 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000859static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
860static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000861static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
862 EvalInfo &Info);
863static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000864static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000865static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000866 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000867static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000868static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000869
870//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000871// Misc utilities
872//===----------------------------------------------------------------------===//
873
Richard Smith180f4792011-11-10 06:34:14 +0000874/// Should this call expression be treated as a string literal?
875static bool IsStringLiteralCall(const CallExpr *E) {
876 unsigned Builtin = E->isBuiltinCall();
877 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
878 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
879}
880
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000881static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000882 // C++11 [expr.const]p3 An address constant expression is a prvalue core
883 // constant expression of pointer type that evaluates to...
884
885 // ... a null pointer value, or a prvalue core constant expression of type
886 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000887 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000888
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000889 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
890 // ... the address of an object with static storage duration,
891 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
892 return VD->hasGlobalStorage();
893 // ... the address of a function,
894 return isa<FunctionDecl>(D);
895 }
896
897 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000898 switch (E->getStmtClass()) {
899 default:
900 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000901 case Expr::CompoundLiteralExprClass:
902 return cast<CompoundLiteralExpr>(E)->isFileScope();
903 // A string literal has static storage duration.
904 case Expr::StringLiteralClass:
905 case Expr::PredefinedExprClass:
906 case Expr::ObjCStringLiteralClass:
907 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000908 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000909 return true;
910 case Expr::CallExprClass:
911 return IsStringLiteralCall(cast<CallExpr>(E));
912 // For GCC compatibility, &&label has static storage duration.
913 case Expr::AddrLabelExprClass:
914 return true;
915 // A Block literal expression may be used as the initialization value for
916 // Block variables at global or local static scope.
917 case Expr::BlockExprClass:
918 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000919 case Expr::ImplicitValueInitExprClass:
920 // FIXME:
921 // We can never form an lvalue with an implicit value initialization as its
922 // base through expression evaluation, so these only appear in one case: the
923 // implicit variable declaration we invent when checking whether a constexpr
924 // constructor can produce a constant expression. We must assume that such
925 // an expression might be a global lvalue.
926 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000927 }
John McCall42c8f872010-05-10 23:27:23 +0000928}
929
Richard Smith9a17a682011-11-07 05:07:52 +0000930/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000931/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000932/// either LValue or CCValue. Return true if we can fold this expression,
933/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000934template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000935static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000936 const T &LVal, APValue &Value,
937 CheckConstantExpressionKind CCEK) {
938 APValue::LValueBase Base = LVal.getLValueBase();
939 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
940
941 if (!IsGlobalLValue(Base)) {
942 if (Info.getLangOpts().CPlusPlus0x) {
943 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
944 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
945 << E->isGLValue() << !Designator.Entries.empty()
946 << !!VD << CCEK << VD;
947 if (VD)
948 Info.Note(VD->getLocation(), diag::note_declared_at);
949 else
950 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
951 diag::note_constexpr_temporary_here);
952 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000953 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000954 }
Richard Smith61e61622012-01-12 06:08:57 +0000955 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000956 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000957 }
Richard Smith9a17a682011-11-07 05:07:52 +0000958
Richard Smithb4e85ed2012-01-06 16:39:00 +0000959 bool IsReferenceType = E->isGLValue();
960
961 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000962 // This is not a core constant expression. An appropriate diagnostic will
963 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000964 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
965 APValue::NoLValuePath());
966 return true;
967 }
968
Richard Smithb4e85ed2012-01-06 16:39:00 +0000969 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
970 Designator.Entries, Designator.IsOnePastTheEnd);
971
972 // Allow address constant expressions to be past-the-end pointers. This is
973 // an extension: the standard requires them to point to an object.
974 if (!IsReferenceType)
975 return true;
976
977 // A reference constant expression must refer to an object.
978 if (!Base) {
979 // FIXME: diagnostic
980 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000981 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000982 }
983
Richard Smithc1c5f272011-12-13 06:39:58 +0000984 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000985 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000986 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
987 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
988 << !Designator.Entries.empty() << !!VD << VD;
989 if (VD)
990 Info.Note(VD->getLocation(), diag::note_declared_at);
991 else
992 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
993 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000994 }
995
Richard Smith9a17a682011-11-07 05:07:52 +0000996 return true;
997}
998
Richard Smith51201882011-12-30 21:15:51 +0000999/// Check that this core constant expression is of literal type, and if not,
1000/// produce an appropriate diagnostic.
1001static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1002 if (!E->isRValue() || E->getType()->isLiteralType())
1003 return true;
1004
1005 // Prvalue constant expressions must be of literal types.
1006 if (Info.getLangOpts().CPlusPlus0x)
1007 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1008 << E->getType();
1009 else
1010 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1011 return false;
1012}
1013
Richard Smith47a1eed2011-10-29 20:57:55 +00001014/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +00001015/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +00001016/// If not, report an appropriate diagnostic. Does not check that the expression
1017/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +00001018static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 const CCValue &CCValue, APValue &Value,
1020 CheckConstantExpressionKind CCEK
1021 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001022 if (!CCValue.isLValue()) {
1023 Value = CCValue;
1024 return true;
1025 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001026 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001027}
1028
Richard Smith9e36b532011-10-31 05:11:32 +00001029const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001030 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001031}
1032
1033static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001034 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001035}
1036
Richard Smith65ac5982011-11-01 21:06:14 +00001037static bool IsWeakLValue(const LValue &Value) {
1038 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001039 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001040}
1041
Richard Smithe24f5fc2011-11-17 22:56:20 +00001042static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001043 // A null base expression indicates a null pointer. These are always
1044 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001045 if (!Value.getLValueBase()) {
1046 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001047 return true;
1048 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001049
Richard Smithe24f5fc2011-11-17 22:56:20 +00001050 // We have a non-null base. These are generally known to be true, but if it's
1051 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001052 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001053 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001054 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001055}
1056
Richard Smith47a1eed2011-10-29 20:57:55 +00001057static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001058 switch (Val.getKind()) {
1059 case APValue::Uninitialized:
1060 return false;
1061 case APValue::Int:
1062 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001063 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001064 case APValue::Float:
1065 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001066 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001067 case APValue::ComplexInt:
1068 Result = Val.getComplexIntReal().getBoolValue() ||
1069 Val.getComplexIntImag().getBoolValue();
1070 return true;
1071 case APValue::ComplexFloat:
1072 Result = !Val.getComplexFloatReal().isZero() ||
1073 !Val.getComplexFloatImag().isZero();
1074 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001075 case APValue::LValue:
1076 return EvalPointerValueAsBool(Val, Result);
1077 case APValue::MemberPointer:
1078 Result = Val.getMemberPointerDecl();
1079 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001080 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001081 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001082 case APValue::Struct:
1083 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001084 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001085 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001086 }
1087
Richard Smithc49bd112011-10-28 17:51:58 +00001088 llvm_unreachable("unknown APValue kind");
1089}
1090
1091static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1092 EvalInfo &Info) {
1093 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001094 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001095 if (!Evaluate(Val, Info, E))
1096 return false;
1097 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001098}
1099
Richard Smithc1c5f272011-12-13 06:39:58 +00001100template<typename T>
1101static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1102 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001103 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001104 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001105 return false;
1106}
1107
1108static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1109 QualType SrcType, const APFloat &Value,
1110 QualType DestType, APSInt &Result) {
1111 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001112 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001113 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Richard Smithc1c5f272011-12-13 06:39:58 +00001115 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001116 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001117 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1118 & APFloat::opInvalidOp)
1119 return HandleOverflow(Info, E, Value, DestType);
1120 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001121}
1122
Richard Smithc1c5f272011-12-13 06:39:58 +00001123static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1124 QualType SrcType, QualType DestType,
1125 APFloat &Result) {
1126 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001127 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001128 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1129 APFloat::rmNearestTiesToEven, &ignored)
1130 & APFloat::opOverflow)
1131 return HandleOverflow(Info, E, Value, DestType);
1132 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001133}
1134
Richard Smithf72fccf2012-01-30 22:27:01 +00001135static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1136 QualType DestType, QualType SrcType,
1137 APSInt &Value) {
1138 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001139 APSInt Result = Value;
1140 // Figure out if this is a truncate, extend or noop cast.
1141 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001142 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001143 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001144 return Result;
1145}
1146
Richard Smithc1c5f272011-12-13 06:39:58 +00001147static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1148 QualType SrcType, const APSInt &Value,
1149 QualType DestType, APFloat &Result) {
1150 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1151 if (Result.convertFromAPInt(Value, Value.isSigned(),
1152 APFloat::rmNearestTiesToEven)
1153 & APFloat::opOverflow)
1154 return HandleOverflow(Info, E, Value, DestType);
1155 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001156}
1157
Eli Friedmane6a24e82011-12-22 03:51:45 +00001158static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1159 llvm::APInt &Res) {
1160 CCValue SVal;
1161 if (!Evaluate(SVal, Info, E))
1162 return false;
1163 if (SVal.isInt()) {
1164 Res = SVal.getInt();
1165 return true;
1166 }
1167 if (SVal.isFloat()) {
1168 Res = SVal.getFloat().bitcastToAPInt();
1169 return true;
1170 }
1171 if (SVal.isVector()) {
1172 QualType VecTy = E->getType();
1173 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1174 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1175 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1176 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1177 Res = llvm::APInt::getNullValue(VecSize);
1178 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1179 APValue &Elt = SVal.getVectorElt(i);
1180 llvm::APInt EltAsInt;
1181 if (Elt.isInt()) {
1182 EltAsInt = Elt.getInt();
1183 } else if (Elt.isFloat()) {
1184 EltAsInt = Elt.getFloat().bitcastToAPInt();
1185 } else {
1186 // Don't try to handle vectors of anything other than int or float
1187 // (not sure if it's possible to hit this case).
1188 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1189 return false;
1190 }
1191 unsigned BaseEltSize = EltAsInt.getBitWidth();
1192 if (BigEndian)
1193 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1194 else
1195 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1196 }
1197 return true;
1198 }
1199 // Give up if the input isn't an int, float, or vector. For example, we
1200 // reject "(v4i16)(intptr_t)&a".
1201 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1202 return false;
1203}
1204
Richard Smithb4e85ed2012-01-06 16:39:00 +00001205/// Cast an lvalue referring to a base subobject to a derived class, by
1206/// truncating the lvalue's path to the given length.
1207static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1208 const RecordDecl *TruncatedType,
1209 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001210 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001211
1212 // Check we actually point to a derived class object.
1213 if (TruncatedElements == D.Entries.size())
1214 return true;
1215 assert(TruncatedElements >= D.MostDerivedPathLength &&
1216 "not casting to a derived class");
1217 if (!Result.checkSubobject(Info, E, CSK_Derived))
1218 return false;
1219
1220 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001221 const RecordDecl *RD = TruncatedType;
1222 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001223 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1224 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001225 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001226 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001227 else
Richard Smith180f4792011-11-10 06:34:14 +00001228 Result.Offset -= Layout.getBaseClassOffset(Base);
1229 RD = Base;
1230 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001231 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001232 return true;
1233}
1234
Richard Smithb4e85ed2012-01-06 16:39:00 +00001235static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001236 const CXXRecordDecl *Derived,
1237 const CXXRecordDecl *Base,
1238 const ASTRecordLayout *RL = 0) {
1239 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1240 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001241 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001242}
1243
Richard Smithb4e85ed2012-01-06 16:39:00 +00001244static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001245 const CXXRecordDecl *DerivedDecl,
1246 const CXXBaseSpecifier *Base) {
1247 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1248
1249 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001250 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001251 return true;
1252 }
1253
Richard Smithb4e85ed2012-01-06 16:39:00 +00001254 SubobjectDesignator &D = Obj.Designator;
1255 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001256 return false;
1257
Richard Smithb4e85ed2012-01-06 16:39:00 +00001258 // Extract most-derived object and corresponding type.
1259 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1260 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1261 return false;
1262
1263 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001264 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1265 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001267 return true;
1268}
1269
1270/// Update LVal to refer to the given field, which must be a member of the type
1271/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001273 const FieldDecl *FD,
1274 const ASTRecordLayout *RL = 0) {
1275 if (!RL)
1276 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1277
1278 unsigned I = FD->getFieldIndex();
1279 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001280 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001281}
1282
Richard Smithd9b02e72012-01-25 22:15:11 +00001283/// Update LVal to refer to the given indirect field.
1284static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1285 LValue &LVal,
1286 const IndirectFieldDecl *IFD) {
1287 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1288 CE = IFD->chain_end(); C != CE; ++C)
1289 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1290}
1291
Richard Smith180f4792011-11-10 06:34:14 +00001292/// Get the size of the given type in char units.
1293static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1294 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1295 // extension.
1296 if (Type->isVoidType() || Type->isFunctionType()) {
1297 Size = CharUnits::One();
1298 return true;
1299 }
1300
1301 if (!Type->isConstantSizeType()) {
1302 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001303 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001304 return false;
1305 }
1306
1307 Size = Info.Ctx.getTypeSizeInChars(Type);
1308 return true;
1309}
1310
1311/// Update a pointer value to model pointer arithmetic.
1312/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001313/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001314/// \param LVal - The pointer value to be updated.
1315/// \param EltTy - The pointee type represented by LVal.
1316/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001317static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1318 LValue &LVal, QualType EltTy,
1319 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001320 CharUnits SizeOfPointee;
1321 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1322 return false;
1323
1324 // Compute the new offset in the appropriate width.
1325 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001326 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001327 return true;
1328}
1329
Richard Smith03f96112011-10-24 17:54:18 +00001330/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001331static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1332 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001333 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001334 // If this is a parameter to an active constexpr function call, perform
1335 // argument substitution.
1336 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001337 // Assume arguments of a potential constant expression are unknown
1338 // constant expressions.
1339 if (Info.CheckingPotentialConstantExpression)
1340 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001341 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001342 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001343 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001344 }
Richard Smith177dce72011-11-01 16:57:24 +00001345 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1346 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001347 }
Richard Smith03f96112011-10-24 17:54:18 +00001348
Richard Smith099e7f62011-12-19 06:19:21 +00001349 // Dig out the initializer, and use the declaration which it's attached to.
1350 const Expr *Init = VD->getAnyInitializer(VD);
1351 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001352 // If we're checking a potential constant expression, the variable could be
1353 // initialized later.
1354 if (!Info.CheckingPotentialConstantExpression)
1355 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001356 return false;
1357 }
1358
Richard Smith180f4792011-11-10 06:34:14 +00001359 // If we're currently evaluating the initializer of this declaration, use that
1360 // in-flight value.
1361 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001362 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1363 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001364 return !Result.isUninit();
1365 }
1366
Richard Smith65ac5982011-11-01 21:06:14 +00001367 // Never evaluate the initializer of a weak variable. We can't be sure that
1368 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001369 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001370 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001371 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001372 }
Richard Smith65ac5982011-11-01 21:06:14 +00001373
Richard Smith099e7f62011-12-19 06:19:21 +00001374 // Check that we can fold the initializer. In C++, we will have already done
1375 // this in the cases where it matters for conformance.
1376 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1377 if (!VD->evaluateValue(Notes)) {
1378 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1379 Notes.size() + 1) << VD;
1380 Info.Note(VD->getLocation(), diag::note_declared_at);
1381 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001382 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001383 } else if (!VD->checkInitIsICE()) {
1384 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1385 Notes.size() + 1) << VD;
1386 Info.Note(VD->getLocation(), diag::note_declared_at);
1387 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001388 }
Richard Smith03f96112011-10-24 17:54:18 +00001389
Richard Smithb4e85ed2012-01-06 16:39:00 +00001390 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001391 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001392}
1393
Richard Smithc49bd112011-10-28 17:51:58 +00001394static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001395 Qualifiers Quals = T.getQualifiers();
1396 return Quals.hasConst() && !Quals.hasVolatile();
1397}
1398
Richard Smith59efe262011-11-11 04:05:33 +00001399/// Get the base index of the given base class within an APValue representing
1400/// the given derived class.
1401static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1402 const CXXRecordDecl *Base) {
1403 Base = Base->getCanonicalDecl();
1404 unsigned Index = 0;
1405 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1406 E = Derived->bases_end(); I != E; ++I, ++Index) {
1407 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1408 return Index;
1409 }
1410
1411 llvm_unreachable("base class missing from derived class's bases list");
1412}
1413
Richard Smithcc5d4f62011-11-07 09:22:26 +00001414/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001415static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1416 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001417 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001418 if (Sub.Invalid)
1419 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001420 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001421 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001422 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001423 (unsigned)diag::note_constexpr_read_past_end :
1424 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001425 return false;
1426 }
Richard Smithf64699e2011-11-11 08:28:03 +00001427 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001428 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001429 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1430 // This object might be initialized later.
1431 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001432
1433 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1434 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001435 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001436 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001437 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001438 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001439 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001441 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001442 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001443 // Note, it should not be possible to form a pointer with a valid
1444 // designator which points more than one past the end of the array.
1445 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001446 (unsigned)diag::note_constexpr_read_past_end :
1447 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001448 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001450 if (O->getArrayInitializedElts() > Index)
1451 O = &O->getArrayInitializedElt(Index);
1452 else
1453 O = &O->getArrayFiller();
1454 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001455 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1456 // Next subobject is a class, struct or union field.
1457 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1458 if (RD->isUnion()) {
1459 const FieldDecl *UnionField = O->getUnionField();
1460 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001461 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001462 Info.Diag(E->getExprLoc(),
1463 diag::note_constexpr_read_inactive_union_member)
1464 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001465 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001466 }
Richard Smith180f4792011-11-10 06:34:14 +00001467 O = &O->getUnionValue();
1468 } else
1469 O = &O->getStructField(Field->getFieldIndex());
1470 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001471
1472 if (ObjType.isVolatileQualified()) {
1473 if (Info.getLangOpts().CPlusPlus) {
1474 // FIXME: Include a description of the path to the volatile subobject.
1475 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1476 << 2 << Field;
1477 Info.Note(Field->getLocation(), diag::note_declared_at);
1478 } else {
1479 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1480 }
1481 return false;
1482 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001483 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001484 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001485 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1486 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1487 O = &O->getStructBase(getBaseIndex(Derived, Base));
1488 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001489 }
Richard Smith180f4792011-11-10 06:34:14 +00001490
Richard Smithf48fdb02011-12-09 22:58:01 +00001491 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001492 if (!Info.CheckingPotentialConstantExpression)
1493 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001494 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001495 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001496 }
1497
Richard Smithb4e85ed2012-01-06 16:39:00 +00001498 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001499 return true;
1500}
1501
Richard Smithf15fda02012-02-02 01:16:57 +00001502/// Find the position where two subobject designators diverge, or equivalently
1503/// the length of the common initial subsequence.
1504static unsigned FindDesignatorMismatch(QualType ObjType,
1505 const SubobjectDesignator &A,
1506 const SubobjectDesignator &B,
1507 bool &WasArrayIndex) {
1508 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1509 for (/**/; I != N; ++I) {
1510 if (!ObjType.isNull() && ObjType->isArrayType()) {
1511 // Next subobject is an array element.
1512 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1513 WasArrayIndex = true;
1514 return I;
1515 }
1516 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1517 } else {
1518 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1519 WasArrayIndex = false;
1520 return I;
1521 }
1522 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1523 // Next subobject is a field.
1524 ObjType = FD->getType();
1525 else
1526 // Next subobject is a base class.
1527 ObjType = QualType();
1528 }
1529 }
1530 WasArrayIndex = false;
1531 return I;
1532}
1533
1534/// Determine whether the given subobject designators refer to elements of the
1535/// same array object.
1536static bool AreElementsOfSameArray(QualType ObjType,
1537 const SubobjectDesignator &A,
1538 const SubobjectDesignator &B) {
1539 if (A.Entries.size() != B.Entries.size())
1540 return false;
1541
1542 bool IsArray = A.MostDerivedArraySize != 0;
1543 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1544 // A is a subobject of the array element.
1545 return false;
1546
1547 // If A (and B) designates an array element, the last entry will be the array
1548 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1549 // of length 1' case, and the entire path must match.
1550 bool WasArrayIndex;
1551 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1552 return CommonLength >= A.Entries.size() - IsArray;
1553}
1554
Richard Smith180f4792011-11-10 06:34:14 +00001555/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1556/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1557/// for looking up the glvalue referred to by an entity of reference type.
1558///
1559/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001560/// \param Conv - The expression for which we are performing the conversion.
1561/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001562/// \param Type - The type we expect this conversion to produce, before
1563/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001564/// \param LVal - The glvalue on which we are attempting to perform this action.
1565/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001566static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1567 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001568 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001569 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1570 if (!Info.getLangOpts().CPlusPlus)
1571 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1572
Richard Smithb4e85ed2012-01-06 16:39:00 +00001573 if (LVal.Designator.Invalid)
1574 // A diagnostic will have already been produced.
1575 return false;
1576
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001577 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001578 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001579 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001580
Richard Smithf48fdb02011-12-09 22:58:01 +00001581 if (!LVal.Base) {
1582 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001583 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1584 return false;
1585 }
1586
1587 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1588 // is not a constant expression (even if the object is non-volatile). We also
1589 // apply this rule to C++98, in order to conform to the expected 'volatile'
1590 // semantics.
1591 if (Type.isVolatileQualified()) {
1592 if (Info.getLangOpts().CPlusPlus)
1593 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1594 else
1595 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001596 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001597 }
Richard Smithc49bd112011-10-28 17:51:58 +00001598
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001599 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001600 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1601 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001602 // expressions are constant expressions too. Inside constexpr functions,
1603 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001604 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001605 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001606 if (const VarDecl *VDef = VD->getDefinition())
1607 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001608 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001609 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001610 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001611 }
1612
Richard Smith7098cbd2011-12-21 05:04:46 +00001613 // DR1313: If the object is volatile-qualified but the glvalue was not,
1614 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001615 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001616 if (VT.isVolatileQualified()) {
1617 if (Info.getLangOpts().CPlusPlus) {
1618 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1619 Info.Note(VD->getLocation(), diag::note_declared_at);
1620 } else {
1621 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001622 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001623 return false;
1624 }
1625
1626 if (!isa<ParmVarDecl>(VD)) {
1627 if (VD->isConstexpr()) {
1628 // OK, we can read this variable.
1629 } else if (VT->isIntegralOrEnumerationType()) {
1630 if (!VT.isConstQualified()) {
1631 if (Info.getLangOpts().CPlusPlus) {
1632 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1633 Info.Note(VD->getLocation(), diag::note_declared_at);
1634 } else {
1635 Info.Diag(Loc);
1636 }
1637 return false;
1638 }
1639 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1640 // We support folding of const floating-point types, in order to make
1641 // static const data members of such types (supported as an extension)
1642 // more useful.
1643 if (Info.getLangOpts().CPlusPlus0x) {
1644 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1645 Info.Note(VD->getLocation(), diag::note_declared_at);
1646 } else {
1647 Info.CCEDiag(Loc);
1648 }
1649 } else {
1650 // FIXME: Allow folding of values of any literal type in all languages.
1651 if (Info.getLangOpts().CPlusPlus0x) {
1652 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1653 Info.Note(VD->getLocation(), diag::note_declared_at);
1654 } else {
1655 Info.Diag(Loc);
1656 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001657 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001658 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001659 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001660
Richard Smithf48fdb02011-12-09 22:58:01 +00001661 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001662 return false;
1663
Richard Smith47a1eed2011-10-29 20:57:55 +00001664 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001665 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001666
1667 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1668 // conversion. This happens when the declaration and the lvalue should be
1669 // considered synonymous, for instance when initializing an array of char
1670 // from a string literal. Continue as if the initializer lvalue was the
1671 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001672 assert(RVal.getLValueOffset().isZero() &&
1673 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001674 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001675 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001676 }
1677
Richard Smith7098cbd2011-12-21 05:04:46 +00001678 // Volatile temporary objects cannot be read in constant expressions.
1679 if (Base->getType().isVolatileQualified()) {
1680 if (Info.getLangOpts().CPlusPlus) {
1681 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1682 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1683 } else {
1684 Info.Diag(Loc);
1685 }
1686 return false;
1687 }
1688
Richard Smith0a3bdb62011-11-04 02:25:55 +00001689 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1690 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1691 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001692 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001693 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001694 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001695 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001696
1697 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001698 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001699 const ConstantArrayType *CAT =
1700 Info.Ctx.getAsConstantArrayType(S->getType());
1701 if (Index >= CAT->getSize().getZExtValue()) {
1702 // Note, it should not be possible to form a pointer which points more
1703 // than one past the end of the array without producing a prior const expr
1704 // diagnostic.
1705 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001706 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001707 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001708 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1709 Type->isUnsignedIntegerType());
1710 if (Index < S->getLength())
1711 Value = S->getCodeUnit(Index);
1712 RVal = CCValue(Value);
1713 return true;
1714 }
1715
Richard Smithcc5d4f62011-11-07 09:22:26 +00001716 if (Frame) {
1717 // If this is a temporary expression with a nontrivial initializer, grab the
1718 // value from the relevant stack frame.
1719 RVal = Frame->Temporaries[Base];
1720 } else if (const CompoundLiteralExpr *CLE
1721 = dyn_cast<CompoundLiteralExpr>(Base)) {
1722 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1723 // initializer until now for such expressions. Such an expression can't be
1724 // an ICE in C, so this only matters for fold.
1725 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1726 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1727 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001728 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001729 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001730 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001731 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001732
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1734 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001735}
1736
Richard Smith59efe262011-11-11 04:05:33 +00001737/// Build an lvalue for the object argument of a member function call.
1738static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1739 LValue &This) {
1740 if (Object->getType()->isPointerType())
1741 return EvaluatePointer(Object, This, Info);
1742
1743 if (Object->isGLValue())
1744 return EvaluateLValue(Object, This, Info);
1745
Richard Smithe24f5fc2011-11-17 22:56:20 +00001746 if (Object->getType()->isLiteralType())
1747 return EvaluateTemporary(Object, This, Info);
1748
1749 return false;
1750}
1751
1752/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1753/// lvalue referring to the result.
1754///
1755/// \param Info - Information about the ongoing evaluation.
1756/// \param BO - The member pointer access operation.
1757/// \param LV - Filled in with a reference to the resulting object.
1758/// \param IncludeMember - Specifies whether the member itself is included in
1759/// the resulting LValue subobject designator. This is not possible when
1760/// creating a bound member function.
1761/// \return The field or method declaration to which the member pointer refers,
1762/// or 0 if evaluation fails.
1763static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1764 const BinaryOperator *BO,
1765 LValue &LV,
1766 bool IncludeMember = true) {
1767 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1768
Richard Smith745f5142012-01-27 01:14:48 +00001769 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1770 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001771 return 0;
1772
1773 MemberPtr MemPtr;
1774 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1775 return 0;
1776
1777 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1778 // member value, the behavior is undefined.
1779 if (!MemPtr.getDecl())
1780 return 0;
1781
Richard Smith745f5142012-01-27 01:14:48 +00001782 if (!EvalObjOK)
1783 return 0;
1784
Richard Smithe24f5fc2011-11-17 22:56:20 +00001785 if (MemPtr.isDerivedMember()) {
1786 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001787 // The end of the derived-to-base path for the base object must match the
1788 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001789 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001790 LV.Designator.Entries.size())
1791 return 0;
1792 unsigned PathLengthToMember =
1793 LV.Designator.Entries.size() - MemPtr.Path.size();
1794 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1795 const CXXRecordDecl *LVDecl = getAsBaseClass(
1796 LV.Designator.Entries[PathLengthToMember + I]);
1797 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1798 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1799 return 0;
1800 }
1801
1802 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001803 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1804 PathLengthToMember))
1805 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001806 } else if (!MemPtr.Path.empty()) {
1807 // Extend the LValue path with the member pointer's path.
1808 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1809 MemPtr.Path.size() + IncludeMember);
1810
1811 // Walk down to the appropriate base class.
1812 QualType LVType = BO->getLHS()->getType();
1813 if (const PointerType *PT = LVType->getAs<PointerType>())
1814 LVType = PT->getPointeeType();
1815 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1816 assert(RD && "member pointer access on non-class-type expression");
1817 // The first class in the path is that of the lvalue.
1818 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1819 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001820 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001821 RD = Base;
1822 }
1823 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001824 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001825 }
1826
1827 // Add the member. Note that we cannot build bound member functions here.
1828 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001829 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1830 HandleLValueMember(Info, BO, LV, FD);
1831 else if (const IndirectFieldDecl *IFD =
1832 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1833 HandleLValueIndirectMember(Info, BO, LV, IFD);
1834 else
1835 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001836 }
1837
1838 return MemPtr.getDecl();
1839}
1840
1841/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1842/// the provided lvalue, which currently refers to the base object.
1843static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1844 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001845 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001846 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001847 return false;
1848
Richard Smithb4e85ed2012-01-06 16:39:00 +00001849 QualType TargetQT = E->getType();
1850 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1851 TargetQT = PT->getPointeeType();
1852
1853 // Check this cast lands within the final derived-to-base subobject path.
1854 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1855 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1856 << D.MostDerivedType << TargetQT;
1857 return false;
1858 }
1859
Richard Smithe24f5fc2011-11-17 22:56:20 +00001860 // Check the type of the final cast. We don't need to check the path,
1861 // since a cast can only be formed if the path is unique.
1862 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001863 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1864 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001865 if (NewEntriesSize == D.MostDerivedPathLength)
1866 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1867 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001868 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001869 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1870 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1871 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001872 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001873 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001874
1875 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001876 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001877}
1878
Mike Stumpc4c90452009-10-27 22:09:17 +00001879namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001880enum EvalStmtResult {
1881 /// Evaluation failed.
1882 ESR_Failed,
1883 /// Hit a 'return' statement.
1884 ESR_Returned,
1885 /// Evaluation succeeded.
1886 ESR_Succeeded
1887};
1888}
1889
1890// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001891static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001892 const Stmt *S) {
1893 switch (S->getStmtClass()) {
1894 default:
1895 return ESR_Failed;
1896
1897 case Stmt::NullStmtClass:
1898 case Stmt::DeclStmtClass:
1899 return ESR_Succeeded;
1900
Richard Smithc1c5f272011-12-13 06:39:58 +00001901 case Stmt::ReturnStmtClass: {
1902 CCValue CCResult;
1903 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1904 if (!Evaluate(CCResult, Info, RetExpr) ||
1905 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1906 CCEK_ReturnValue))
1907 return ESR_Failed;
1908 return ESR_Returned;
1909 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001910
1911 case Stmt::CompoundStmtClass: {
1912 const CompoundStmt *CS = cast<CompoundStmt>(S);
1913 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1914 BE = CS->body_end(); BI != BE; ++BI) {
1915 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1916 if (ESR != ESR_Succeeded)
1917 return ESR;
1918 }
1919 return ESR_Succeeded;
1920 }
1921 }
1922}
1923
Richard Smith61802452011-12-22 02:22:31 +00001924/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1925/// default constructor. If so, we'll fold it whether or not it's marked as
1926/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1927/// so we need special handling.
1928static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001929 const CXXConstructorDecl *CD,
1930 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001931 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1932 return false;
1933
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001934 // Value-initialization does not call a trivial default constructor, so such a
1935 // call is a core constant expression whether or not the constructor is
1936 // constexpr.
1937 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001938 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001939 // FIXME: If DiagDecl is an implicitly-declared special member function,
1940 // we should be much more explicit about why it's not constexpr.
1941 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1942 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1943 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001944 } else {
1945 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1946 }
1947 }
1948 return true;
1949}
1950
Richard Smithc1c5f272011-12-13 06:39:58 +00001951/// CheckConstexprFunction - Check that a function can be called in a constant
1952/// expression.
1953static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1954 const FunctionDecl *Declaration,
1955 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001956 // Potential constant expressions can contain calls to declared, but not yet
1957 // defined, constexpr functions.
1958 if (Info.CheckingPotentialConstantExpression && !Definition &&
1959 Declaration->isConstexpr())
1960 return false;
1961
Richard Smithc1c5f272011-12-13 06:39:58 +00001962 // Can we evaluate this function call?
1963 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1964 return true;
1965
1966 if (Info.getLangOpts().CPlusPlus0x) {
1967 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001968 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1969 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001970 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1971 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1972 << DiagDecl;
1973 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1974 } else {
1975 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1976 }
1977 return false;
1978}
1979
Richard Smith180f4792011-11-10 06:34:14 +00001980namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001981typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001982}
1983
1984/// EvaluateArgs - Evaluate the arguments to a function call.
1985static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1986 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001987 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001988 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001989 I != E; ++I) {
1990 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1991 // If we're checking for a potential constant expression, evaluate all
1992 // initializers even if some of them fail.
1993 if (!Info.keepEvaluatingAfterFailure())
1994 return false;
1995 Success = false;
1996 }
1997 }
1998 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001999}
2000
Richard Smithd0dccea2011-10-28 22:34:42 +00002001/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002002static bool HandleFunctionCall(SourceLocation CallLoc,
2003 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002004 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00002005 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002006 ArgVector ArgValues(Args.size());
2007 if (!EvaluateArgs(Args, ArgValues, Info))
2008 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002009
Richard Smith745f5142012-01-27 01:14:48 +00002010 if (!Info.CheckCallLimit(CallLoc))
2011 return false;
2012
2013 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002014 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2015}
2016
Richard Smith180f4792011-11-10 06:34:14 +00002017/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002018static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002019 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002020 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002021 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002022 ArgVector ArgValues(Args.size());
2023 if (!EvaluateArgs(Args, ArgValues, Info))
2024 return false;
2025
Richard Smith745f5142012-01-27 01:14:48 +00002026 if (!Info.CheckCallLimit(CallLoc))
2027 return false;
2028
2029 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002030
2031 // If it's a delegating constructor, just delegate.
2032 if (Definition->isDelegatingConstructor()) {
2033 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2034 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2035 }
2036
Richard Smith610a60c2012-01-10 04:32:03 +00002037 // For a trivial copy or move constructor, perform an APValue copy. This is
2038 // essential for unions, where the operations performed by the constructor
2039 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00002040 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00002041 if (Definition->isDefaulted() &&
2042 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2043 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2044 LValue RHS;
2045 RHS.setFrom(ArgValues[0]);
2046 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002047 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2048 RHS, Value))
2049 return false;
2050 assert((Value.isStruct() || Value.isUnion()) &&
2051 "trivial copy/move from non-class type?");
2052 // Any CCValue of class type must already be a constant expression.
2053 Result = Value;
2054 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002055 }
2056
2057 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002058 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002059 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2060 std::distance(RD->field_begin(), RD->field_end()));
2061
2062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2063
Richard Smith745f5142012-01-27 01:14:48 +00002064 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002065 unsigned BasesSeen = 0;
2066#ifndef NDEBUG
2067 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2068#endif
2069 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2070 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002071 LValue Subobject = This;
2072 APValue *Value = &Result;
2073
2074 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002075 if ((*I)->isBaseInitializer()) {
2076 QualType BaseType((*I)->getBaseClass(), 0);
2077#ifndef NDEBUG
2078 // Non-virtual base classes are initialized in the order in the class
2079 // definition. We cannot have a virtual base class for a literal type.
2080 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2081 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2082 "base class initializers not in expected order");
2083 ++BaseIt;
2084#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002085 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002086 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002087 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002088 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002089 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002090 if (RD->isUnion()) {
2091 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002092 Value = &Result.getUnionValue();
2093 } else {
2094 Value = &Result.getStructField(FD->getFieldIndex());
2095 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002096 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002097 // Walk the indirect field decl's chain to find the object to initialize,
2098 // and make sure we've initialized every step along it.
2099 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2100 CE = IFD->chain_end();
2101 C != CE; ++C) {
2102 FieldDecl *FD = cast<FieldDecl>(*C);
2103 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2104 // Switch the union field if it differs. This happens if we had
2105 // preceding zero-initialization, and we're now initializing a union
2106 // subobject other than the first.
2107 // FIXME: In this case, the values of the other subobjects are
2108 // specified, since zero-initialization sets all padding bits to zero.
2109 if (Value->isUninit() ||
2110 (Value->isUnion() && Value->getUnionField() != FD)) {
2111 if (CD->isUnion())
2112 *Value = APValue(FD);
2113 else
2114 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2115 std::distance(CD->field_begin(), CD->field_end()));
2116 }
Richard Smith745f5142012-01-27 01:14:48 +00002117 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002118 if (CD->isUnion())
2119 Value = &Value->getUnionValue();
2120 else
2121 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002122 }
Richard Smith180f4792011-11-10 06:34:14 +00002123 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002124 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002125 }
Richard Smith745f5142012-01-27 01:14:48 +00002126
2127 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2128 (*I)->isBaseInitializer()
2129 ? CCEK_Constant : CCEK_MemberInit)) {
2130 // If we're checking for a potential constant expression, evaluate all
2131 // initializers even if some of them fail.
2132 if (!Info.keepEvaluatingAfterFailure())
2133 return false;
2134 Success = false;
2135 }
Richard Smith180f4792011-11-10 06:34:14 +00002136 }
2137
Richard Smith745f5142012-01-27 01:14:48 +00002138 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002139}
2140
Richard Smithd0dccea2011-10-28 22:34:42 +00002141namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002142class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002143 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002144 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002145public:
2146
Richard Smith1e12c592011-10-16 21:26:27 +00002147 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002148
2149 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002150 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002151 return true;
2152 }
2153
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002154 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2155 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002156 return Visit(E->getResultExpr());
2157 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002158 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002159 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002160 return true;
2161 return false;
2162 }
John McCallf85e1932011-06-15 23:02:42 +00002163 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002164 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002165 return true;
2166 return false;
2167 }
2168 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002169 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002170 return true;
2171 return false;
2172 }
2173
Mike Stumpc4c90452009-10-27 22:09:17 +00002174 // We don't want to evaluate BlockExprs multiple times, as they generate
2175 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002176 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2177 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2178 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002179 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002180 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2181 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2182 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2183 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2184 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2185 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002186 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002187 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002188 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002190 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002191 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2192 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2193 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2194 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002195 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002196 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2197 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2198 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2199 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2200 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002201 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002202 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002203 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002204 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002205 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002206
2207 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002208 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002209 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2210 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002211 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002212 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002213 return false;
2214 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002215
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002216 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002217};
2218
John McCall56ca35d2011-02-17 10:25:35 +00002219class OpaqueValueEvaluation {
2220 EvalInfo &info;
2221 OpaqueValueExpr *opaqueValue;
2222
2223public:
2224 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2225 Expr *value)
2226 : info(info), opaqueValue(opaqueValue) {
2227
2228 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002229 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002230 this->opaqueValue = 0;
2231 return;
2232 }
John McCall56ca35d2011-02-17 10:25:35 +00002233 }
2234
2235 bool hasError() const { return opaqueValue == 0; }
2236
2237 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002238 // FIXME: This will not work for recursive constexpr functions using opaque
2239 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002240 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2241 }
2242};
2243
Mike Stumpc4c90452009-10-27 22:09:17 +00002244} // end anonymous namespace
2245
Eli Friedman4efaa272008-11-12 09:44:48 +00002246//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002247// Generic Evaluation
2248//===----------------------------------------------------------------------===//
2249namespace {
2250
Richard Smithf48fdb02011-12-09 22:58:01 +00002251// FIXME: RetTy is always bool. Remove it.
2252template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253class ExprEvaluatorBase
2254 : public ConstStmtVisitor<Derived, RetTy> {
2255private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002256 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002257 return static_cast<Derived*>(this)->Success(V, E);
2258 }
Richard Smith51201882011-12-30 21:15:51 +00002259 RetTy DerivedZeroInitialization(const Expr *E) {
2260 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002261 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002262
2263protected:
2264 EvalInfo &Info;
2265 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2266 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2267
Richard Smithdd1f29b2011-12-12 09:28:41 +00002268 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002269 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002270 }
2271
2272 /// Report an evaluation error. This should only be called when an error is
2273 /// first discovered. When propagating an error, just return false.
2274 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002275 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002276 return false;
2277 }
2278 bool Error(const Expr *E) {
2279 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2280 }
2281
Richard Smith51201882011-12-30 21:15:51 +00002282 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002283
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284public:
2285 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2286
2287 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002288 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289 }
2290 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002291 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 }
2293
2294 RetTy VisitParenExpr(const ParenExpr *E)
2295 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2296 RetTy VisitUnaryExtension(const UnaryOperator *E)
2297 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2298 RetTy VisitUnaryPlus(const UnaryOperator *E)
2299 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2300 RetTy VisitChooseExpr(const ChooseExpr *E)
2301 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2302 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2303 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002304 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2305 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002306 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2307 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002308 // We cannot create any objects for which cleanups are required, so there is
2309 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2310 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2311 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002312
Richard Smithc216a012011-12-12 12:46:16 +00002313 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2314 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2315 return static_cast<Derived*>(this)->VisitCastExpr(E);
2316 }
2317 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2318 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2319 return static_cast<Derived*>(this)->VisitCastExpr(E);
2320 }
2321
Richard Smithe24f5fc2011-11-17 22:56:20 +00002322 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2323 switch (E->getOpcode()) {
2324 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002325 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002326
2327 case BO_Comma:
2328 VisitIgnoredValue(E->getLHS());
2329 return StmtVisitorTy::Visit(E->getRHS());
2330
2331 case BO_PtrMemD:
2332 case BO_PtrMemI: {
2333 LValue Obj;
2334 if (!HandleMemberPointerAccess(Info, E, Obj))
2335 return false;
2336 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002337 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002338 return false;
2339 return DerivedSuccess(Result, E);
2340 }
2341 }
2342 }
2343
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2345 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2346 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002347 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002348
2349 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002350 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002351 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352
2353 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2354 }
2355
2356 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002357 bool IsBcpCall = false;
2358 // If the condition (ignoring parens) is a __builtin_constant_p call,
2359 // the result is a constant expression if it can be folded without
2360 // side-effects. This is an important GNU extension. See GCC PR38377
2361 // for discussion.
2362 if (const CallExpr *CallCE =
2363 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2364 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2365 IsBcpCall = true;
2366
2367 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2368 // constant expression; we can't check whether it's potentially foldable.
2369 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2370 return false;
2371
2372 FoldConstant Fold(Info);
2373
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002374 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002375 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002376 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002377
Richard Smithc49bd112011-10-28 17:51:58 +00002378 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002379 if (!StmtVisitorTy::Visit(EvalExpr))
2380 return false;
2381
2382 if (IsBcpCall)
2383 Fold.Fold(Info);
2384
2385 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002386 }
2387
2388 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002389 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002390 if (!Value) {
2391 const Expr *Source = E->getSourceExpr();
2392 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002393 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002394 if (Source == E) { // sanity checking.
2395 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002396 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002397 }
2398 return StmtVisitorTy::Visit(Source);
2399 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002400 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002401 }
Richard Smithf10d9172011-10-11 21:43:33 +00002402
Richard Smithd0dccea2011-10-28 22:34:42 +00002403 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002404 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002405 QualType CalleeType = Callee->getType();
2406
Richard Smithd0dccea2011-10-28 22:34:42 +00002407 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002408 LValue *This = 0, ThisVal;
2409 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002410
Richard Smith59efe262011-11-11 04:05:33 +00002411 // Extract function decl and 'this' pointer from the callee.
2412 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002413 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002414 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2415 // Explicit bound member calls, such as x.f() or p->g();
2416 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002417 return false;
2418 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002419 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002420 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2421 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002422 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2423 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002424 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002425 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002426 return Error(Callee);
2427
2428 FD = dyn_cast<FunctionDecl>(Member);
2429 if (!FD)
2430 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002431 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002432 LValue Call;
2433 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002434 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002435
Richard Smithb4e85ed2012-01-06 16:39:00 +00002436 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002437 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002438 FD = dyn_cast_or_null<FunctionDecl>(
2439 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002440 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002442
2443 // Overloaded operator calls to member functions are represented as normal
2444 // calls with '*this' as the first argument.
2445 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2446 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 // FIXME: When selecting an implicit conversion for an overloaded
2448 // operator delete, we sometimes try to evaluate calls to conversion
2449 // operators without a 'this' parameter!
2450 if (Args.empty())
2451 return Error(E);
2452
Richard Smith59efe262011-11-11 04:05:33 +00002453 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2454 return false;
2455 This = &ThisVal;
2456 Args = Args.slice(1);
2457 }
2458
2459 // Don't call function pointers which have been cast to some other type.
2460 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002461 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002462 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002463 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002464
Richard Smithb04035a2012-02-01 02:39:43 +00002465 if (This && !This->checkSubobject(Info, E, CSK_This))
2466 return false;
2467
Richard Smithc1c5f272011-12-13 06:39:58 +00002468 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002469 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002470 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002471
Richard Smithc1c5f272011-12-13 06:39:58 +00002472 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002473 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2474 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002475 return false;
2476
Richard Smithb4e85ed2012-01-06 16:39:00 +00002477 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002478 }
2479
Richard Smithc49bd112011-10-28 17:51:58 +00002480 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2481 return StmtVisitorTy::Visit(E->getInitializer());
2482 }
Richard Smithf10d9172011-10-11 21:43:33 +00002483 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002484 if (E->getNumInits() == 0)
2485 return DerivedZeroInitialization(E);
2486 if (E->getNumInits() == 1)
2487 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002488 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002489 }
2490 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002491 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002492 }
2493 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002494 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002495 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002497 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 }
Richard Smithf10d9172011-10-11 21:43:33 +00002499
Richard Smith180f4792011-11-10 06:34:14 +00002500 /// A member expression where the object is a prvalue is itself a prvalue.
2501 RetTy VisitMemberExpr(const MemberExpr *E) {
2502 assert(!E->isArrow() && "missing call to bound member function?");
2503
2504 CCValue Val;
2505 if (!Evaluate(Val, Info, E->getBase()))
2506 return false;
2507
2508 QualType BaseTy = E->getBase()->getType();
2509
2510 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002511 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002512 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2513 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2514 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2515
Richard Smithb4e85ed2012-01-06 16:39:00 +00002516 SubobjectDesignator Designator(BaseTy);
2517 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002518
Richard Smithf48fdb02011-12-09 22:58:01 +00002519 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002520 DerivedSuccess(Val, E);
2521 }
2522
Richard Smithc49bd112011-10-28 17:51:58 +00002523 RetTy VisitCastExpr(const CastExpr *E) {
2524 switch (E->getCastKind()) {
2525 default:
2526 break;
2527
David Chisnall7a7ee302012-01-16 17:27:18 +00002528 case CK_AtomicToNonAtomic:
2529 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002530 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002531 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002532 return StmtVisitorTy::Visit(E->getSubExpr());
2533
2534 case CK_LValueToRValue: {
2535 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002536 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2537 return false;
2538 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002539 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2540 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2541 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002542 return false;
2543 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002544 }
2545 }
2546
Richard Smithf48fdb02011-12-09 22:58:01 +00002547 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002548 }
2549
Richard Smith8327fad2011-10-24 18:44:57 +00002550 /// Visit a value which is evaluated, but whose value is ignored.
2551 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002552 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002553 if (!Evaluate(Scratch, Info, E))
2554 Info.EvalStatus.HasSideEffects = true;
2555 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002556};
2557
2558}
2559
2560//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002561// Common base class for lvalue and temporary evaluation.
2562//===----------------------------------------------------------------------===//
2563namespace {
2564template<class Derived>
2565class LValueExprEvaluatorBase
2566 : public ExprEvaluatorBase<Derived, bool> {
2567protected:
2568 LValue &Result;
2569 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2570 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2571
2572 bool Success(APValue::LValueBase B) {
2573 Result.set(B);
2574 return true;
2575 }
2576
2577public:
2578 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2579 ExprEvaluatorBaseTy(Info), Result(Result) {}
2580
2581 bool Success(const CCValue &V, const Expr *E) {
2582 Result.setFrom(V);
2583 return true;
2584 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002585
Richard Smithe24f5fc2011-11-17 22:56:20 +00002586 bool VisitMemberExpr(const MemberExpr *E) {
2587 // Handle non-static data members.
2588 QualType BaseTy;
2589 if (E->isArrow()) {
2590 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2591 return false;
2592 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002593 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002594 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002595 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2596 return false;
2597 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002598 } else {
2599 if (!this->Visit(E->getBase()))
2600 return false;
2601 BaseTy = E->getBase()->getType();
2602 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002603
Richard Smithd9b02e72012-01-25 22:15:11 +00002604 const ValueDecl *MD = E->getMemberDecl();
2605 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2606 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2607 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2608 (void)BaseTy;
2609 HandleLValueMember(this->Info, E, Result, FD);
2610 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2611 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2612 } else
2613 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002614
Richard Smithd9b02e72012-01-25 22:15:11 +00002615 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002616 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002617 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002618 RefValue))
2619 return false;
2620 return Success(RefValue, E);
2621 }
2622 return true;
2623 }
2624
2625 bool VisitBinaryOperator(const BinaryOperator *E) {
2626 switch (E->getOpcode()) {
2627 default:
2628 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2629
2630 case BO_PtrMemD:
2631 case BO_PtrMemI:
2632 return HandleMemberPointerAccess(this->Info, E, Result);
2633 }
2634 }
2635
2636 bool VisitCastExpr(const CastExpr *E) {
2637 switch (E->getCastKind()) {
2638 default:
2639 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2640
2641 case CK_DerivedToBase:
2642 case CK_UncheckedDerivedToBase: {
2643 if (!this->Visit(E->getSubExpr()))
2644 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002645
2646 // Now figure out the necessary offset to add to the base LV to get from
2647 // the derived class to the base class.
2648 QualType Type = E->getSubExpr()->getType();
2649
2650 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2651 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002652 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002653 *PathI))
2654 return false;
2655 Type = (*PathI)->getType();
2656 }
2657
2658 return true;
2659 }
2660 }
2661 }
2662};
2663}
2664
2665//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002666// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002667//
2668// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2669// function designators (in C), decl references to void objects (in C), and
2670// temporaries (if building with -Wno-address-of-temporary).
2671//
2672// LValue evaluation produces values comprising a base expression of one of the
2673// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002674// - Declarations
2675// * VarDecl
2676// * FunctionDecl
2677// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002678// * CompoundLiteralExpr in C
2679// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002680// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002681// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002682// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002683// * ObjCEncodeExpr
2684// * AddrLabelExpr
2685// * BlockExpr
2686// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002687// - Locals and temporaries
2688// * Any Expr, with a Frame indicating the function in which the temporary was
2689// evaluated.
2690// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002691//===----------------------------------------------------------------------===//
2692namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002693class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002694 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002695public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002696 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2697 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Richard Smithc49bd112011-10-28 17:51:58 +00002699 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2700
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002701 bool VisitDeclRefExpr(const DeclRefExpr *E);
2702 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002703 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002704 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2705 bool VisitMemberExpr(const MemberExpr *E);
2706 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2707 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002708 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002709 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2710 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002711
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002712 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002713 switch (E->getCastKind()) {
2714 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002715 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002716
Eli Friedmandb924222011-10-11 00:13:24 +00002717 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002718 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002719 if (!Visit(E->getSubExpr()))
2720 return false;
2721 Result.Designator.setInvalid();
2722 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002723
Richard Smithe24f5fc2011-11-17 22:56:20 +00002724 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002725 if (!Visit(E->getSubExpr()))
2726 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002727 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002728 }
2729 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002730
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002731 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002732
Eli Friedman4efaa272008-11-12 09:44:48 +00002733};
2734} // end anonymous namespace
2735
Richard Smithc49bd112011-10-28 17:51:58 +00002736/// Evaluate an expression as an lvalue. This can be legitimately called on
2737/// expressions which are not glvalues, in a few cases:
2738/// * function designators in C,
2739/// * "extern void" objects,
2740/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002741static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002742 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2743 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2744 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002745 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002746}
2747
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002748bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002749 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2750 return Success(FD);
2751 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002752 return VisitVarDecl(E, VD);
2753 return Error(E);
2754}
Richard Smith436c8892011-10-24 23:14:33 +00002755
Richard Smithc49bd112011-10-28 17:51:58 +00002756bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002757 if (!VD->getType()->isReferenceType()) {
2758 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002759 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002760 return true;
2761 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002762 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002763 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002764
Richard Smith47a1eed2011-10-29 20:57:55 +00002765 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002766 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2767 return false;
2768 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002769}
2770
Richard Smithbd552ef2011-10-31 05:52:43 +00002771bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2772 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002773 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002774 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002775 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2776
2777 Result.set(E, Info.CurrentCall);
2778 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2779 Result, E->GetTemporaryExpr());
2780 }
2781
2782 // Materialization of an lvalue temporary occurs when we need to force a copy
2783 // (for instance, if it's a bitfield).
2784 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2785 if (!Visit(E->GetTemporaryExpr()))
2786 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002787 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002788 Info.CurrentCall->Temporaries[E]))
2789 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002790 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002791 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002792}
2793
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002794bool
2795LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002796 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2797 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2798 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002799 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002800}
2801
Richard Smith47d21452011-12-27 12:18:28 +00002802bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2803 if (E->isTypeOperand())
2804 return Success(E);
2805 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2806 if (RD && RD->isPolymorphic()) {
2807 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2808 << E->getExprOperand()->getType()
2809 << E->getExprOperand()->getSourceRange();
2810 return false;
2811 }
2812 return Success(E);
2813}
2814
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002815bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002816 // Handle static data members.
2817 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2818 VisitIgnoredValue(E->getBase());
2819 return VisitVarDecl(E, VD);
2820 }
2821
Richard Smithd0dccea2011-10-28 22:34:42 +00002822 // Handle static member functions.
2823 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2824 if (MD->isStatic()) {
2825 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002826 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002827 }
2828 }
2829
Richard Smith180f4792011-11-10 06:34:14 +00002830 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002831 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002832}
2833
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002834bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002835 // FIXME: Deal with vectors as array subscript bases.
2836 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002837 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002838
Anders Carlsson3068d112008-11-16 19:01:22 +00002839 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Anders Carlsson3068d112008-11-16 19:01:22 +00002842 APSInt Index;
2843 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002844 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002845 int64_t IndexValue
2846 = Index.isSigned() ? Index.getSExtValue()
2847 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002848
Richard Smithb4e85ed2012-01-06 16:39:00 +00002849 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002850}
Eli Friedman4efaa272008-11-12 09:44:48 +00002851
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002852bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002853 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002854}
2855
Eli Friedman4efaa272008-11-12 09:44:48 +00002856//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002857// Pointer Evaluation
2858//===----------------------------------------------------------------------===//
2859
Anders Carlssonc754aa62008-07-08 05:13:58 +00002860namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002861class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002862 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002863 LValue &Result;
2864
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002865 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002866 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002867 return true;
2868 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002869public:
Mike Stump1eb44332009-09-09 15:08:12 +00002870
John McCallefdb83e2010-05-07 21:00:08 +00002871 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002872 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002873
Richard Smith47a1eed2011-10-29 20:57:55 +00002874 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002875 Result.setFrom(V);
2876 return true;
2877 }
Richard Smith51201882011-12-30 21:15:51 +00002878 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002879 return Success((Expr*)0);
2880 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002881
John McCallefdb83e2010-05-07 21:00:08 +00002882 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002883 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002884 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002885 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002886 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002887 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002888 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002889 bool VisitCallExpr(const CallExpr *E);
2890 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002891 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002892 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002893 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002894 }
Richard Smith180f4792011-11-10 06:34:14 +00002895 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2896 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002897 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002898 Result = *Info.CurrentCall->This;
2899 return true;
2900 }
John McCall56ca35d2011-02-17 10:25:35 +00002901
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002902 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002903};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002904} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002905
John McCallefdb83e2010-05-07 21:00:08 +00002906static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002907 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002908 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002909}
2910
John McCallefdb83e2010-05-07 21:00:08 +00002911bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002912 if (E->getOpcode() != BO_Add &&
2913 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002914 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002916 const Expr *PExp = E->getLHS();
2917 const Expr *IExp = E->getRHS();
2918 if (IExp->getType()->isPointerType())
2919 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Richard Smith745f5142012-01-27 01:14:48 +00002921 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2922 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002923 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002924
John McCallefdb83e2010-05-07 21:00:08 +00002925 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002926 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002927 return false;
2928 int64_t AdditionalOffset
2929 = Offset.isSigned() ? Offset.getSExtValue()
2930 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002931 if (E->getOpcode() == BO_Sub)
2932 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002933
Richard Smith180f4792011-11-10 06:34:14 +00002934 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002935 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2936 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002937}
Eli Friedman4efaa272008-11-12 09:44:48 +00002938
John McCallefdb83e2010-05-07 21:00:08 +00002939bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2940 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002941}
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002943bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2944 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002945
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002946 switch (E->getCastKind()) {
2947 default:
2948 break;
2949
John McCall2de56d12010-08-25 11:45:40 +00002950 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002951 case CK_CPointerToObjCPointerCast:
2952 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002953 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002954 if (!Visit(SubExpr))
2955 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002956 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2957 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2958 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002959 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002960 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002961 if (SubExpr->getType()->isVoidPointerType())
2962 CCEDiag(E, diag::note_constexpr_invalid_cast)
2963 << 3 << SubExpr->getType();
2964 else
2965 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2966 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002967 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002968
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002969 case CK_DerivedToBase:
2970 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002971 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002972 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002973 if (!Result.Base && Result.Offset.isZero())
2974 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002975
Richard Smith180f4792011-11-10 06:34:14 +00002976 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002977 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002978 QualType Type =
2979 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002980
Richard Smith180f4792011-11-10 06:34:14 +00002981 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002982 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002983 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2984 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002985 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002986 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002987 }
2988
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002989 return true;
2990 }
2991
Richard Smithe24f5fc2011-11-17 22:56:20 +00002992 case CK_BaseToDerived:
2993 if (!Visit(E->getSubExpr()))
2994 return false;
2995 if (!Result.Base && Result.Offset.isZero())
2996 return true;
2997 return HandleBaseToDerivedCast(Info, E, Result);
2998
Richard Smith47a1eed2011-10-29 20:57:55 +00002999 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003000 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003001
John McCall2de56d12010-08-25 11:45:40 +00003002 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003003 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3004
Richard Smith47a1eed2011-10-29 20:57:55 +00003005 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003006 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003007 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003008
John McCallefdb83e2010-05-07 21:00:08 +00003009 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003010 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3011 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003012 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003013 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00003014 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003015 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003016 return true;
3017 } else {
3018 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003019 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003020 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003021 }
3022 }
John McCall2de56d12010-08-25 11:45:40 +00003023 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003024 if (SubExpr->isGLValue()) {
3025 if (!EvaluateLValue(SubExpr, Result, Info))
3026 return false;
3027 } else {
3028 Result.set(SubExpr, Info.CurrentCall);
3029 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3030 Info, Result, SubExpr))
3031 return false;
3032 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003033 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003034 if (const ConstantArrayType *CAT
3035 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3036 Result.addArray(Info, E, CAT);
3037 else
3038 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003039 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003040
John McCall2de56d12010-08-25 11:45:40 +00003041 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003042 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003043 }
3044
Richard Smithc49bd112011-10-28 17:51:58 +00003045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003046}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003047
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003048bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003049 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003050 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003051
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003052 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003053}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003054
3055//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003056// Member Pointer Evaluation
3057//===----------------------------------------------------------------------===//
3058
3059namespace {
3060class MemberPointerExprEvaluator
3061 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3062 MemberPtr &Result;
3063
3064 bool Success(const ValueDecl *D) {
3065 Result = MemberPtr(D);
3066 return true;
3067 }
3068public:
3069
3070 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3071 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3072
3073 bool Success(const CCValue &V, const Expr *E) {
3074 Result.setFrom(V);
3075 return true;
3076 }
Richard Smith51201882011-12-30 21:15:51 +00003077 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003078 return Success((const ValueDecl*)0);
3079 }
3080
3081 bool VisitCastExpr(const CastExpr *E);
3082 bool VisitUnaryAddrOf(const UnaryOperator *E);
3083};
3084} // end anonymous namespace
3085
3086static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3087 EvalInfo &Info) {
3088 assert(E->isRValue() && E->getType()->isMemberPointerType());
3089 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3090}
3091
3092bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3093 switch (E->getCastKind()) {
3094 default:
3095 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3096
3097 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003098 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003099
3100 case CK_BaseToDerivedMemberPointer: {
3101 if (!Visit(E->getSubExpr()))
3102 return false;
3103 if (E->path_empty())
3104 return true;
3105 // Base-to-derived member pointer casts store the path in derived-to-base
3106 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3107 // the wrong end of the derived->base arc, so stagger the path by one class.
3108 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3109 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3110 PathI != PathE; ++PathI) {
3111 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3112 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3113 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003114 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003115 }
3116 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3117 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003118 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003119 return true;
3120 }
3121
3122 case CK_DerivedToBaseMemberPointer:
3123 if (!Visit(E->getSubExpr()))
3124 return false;
3125 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3126 PathE = E->path_end(); PathI != PathE; ++PathI) {
3127 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3128 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3129 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003130 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003131 }
3132 return true;
3133 }
3134}
3135
3136bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3137 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3138 // member can be formed.
3139 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3140}
3141
3142//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003143// Record Evaluation
3144//===----------------------------------------------------------------------===//
3145
3146namespace {
3147 class RecordExprEvaluator
3148 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3149 const LValue &This;
3150 APValue &Result;
3151 public:
3152
3153 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3154 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3155
3156 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003157 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003158 }
Richard Smith51201882011-12-30 21:15:51 +00003159 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003160
Richard Smith59efe262011-11-11 04:05:33 +00003161 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003162 bool VisitInitListExpr(const InitListExpr *E);
3163 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3164 };
3165}
3166
Richard Smith51201882011-12-30 21:15:51 +00003167/// Perform zero-initialization on an object of non-union class type.
3168/// C++11 [dcl.init]p5:
3169/// To zero-initialize an object or reference of type T means:
3170/// [...]
3171/// -- if T is a (possibly cv-qualified) non-union class type,
3172/// each non-static data member and each base-class subobject is
3173/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003174static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3175 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003176 const LValue &This, APValue &Result) {
3177 assert(!RD->isUnion() && "Expected non-union class type");
3178 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3179 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3180 std::distance(RD->field_begin(), RD->field_end()));
3181
3182 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3183
3184 if (CD) {
3185 unsigned Index = 0;
3186 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003187 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003188 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3189 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003190 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3191 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003192 Result.getStructBase(Index)))
3193 return false;
3194 }
3195 }
3196
Richard Smithb4e85ed2012-01-06 16:39:00 +00003197 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3198 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003199 // -- if T is a reference type, no initialization is performed.
3200 if ((*I)->getType()->isReferenceType())
3201 continue;
3202
3203 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003204 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003205
3206 ImplicitValueInitExpr VIE((*I)->getType());
3207 if (!EvaluateConstantExpression(
3208 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3209 return false;
3210 }
3211
3212 return true;
3213}
3214
3215bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3216 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3217 if (RD->isUnion()) {
3218 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3219 // object's first non-static named data member is zero-initialized
3220 RecordDecl::field_iterator I = RD->field_begin();
3221 if (I == RD->field_end()) {
3222 Result = APValue((const FieldDecl*)0);
3223 return true;
3224 }
3225
3226 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003227 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003228 Result = APValue(*I);
3229 ImplicitValueInitExpr VIE((*I)->getType());
3230 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3231 Subobject, &VIE);
3232 }
3233
Richard Smithb4e85ed2012-01-06 16:39:00 +00003234 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003235}
3236
Richard Smith59efe262011-11-11 04:05:33 +00003237bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3238 switch (E->getCastKind()) {
3239 default:
3240 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3241
3242 case CK_ConstructorConversion:
3243 return Visit(E->getSubExpr());
3244
3245 case CK_DerivedToBase:
3246 case CK_UncheckedDerivedToBase: {
3247 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003248 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003249 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003250 if (!DerivedObject.isStruct())
3251 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003252
3253 // Derived-to-base rvalue conversion: just slice off the derived part.
3254 APValue *Value = &DerivedObject;
3255 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3256 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3257 PathE = E->path_end(); PathI != PathE; ++PathI) {
3258 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3259 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3260 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3261 RD = Base;
3262 }
3263 Result = *Value;
3264 return true;
3265 }
3266 }
3267}
3268
Richard Smith180f4792011-11-10 06:34:14 +00003269bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3270 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3271 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3272
3273 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003274 const FieldDecl *Field = E->getInitializedFieldInUnion();
3275 Result = APValue(Field);
3276 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003277 return true;
Richard Smithec789162012-01-12 18:54:33 +00003278
3279 // If the initializer list for a union does not contain any elements, the
3280 // first element of the union is value-initialized.
3281 ImplicitValueInitExpr VIE(Field->getType());
3282 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3283
Richard Smith180f4792011-11-10 06:34:14 +00003284 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003285 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003286 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003287 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003288 }
3289
3290 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3291 "initializer list for class with base classes");
3292 Result = APValue(APValue::UninitStruct(), 0,
3293 std::distance(RD->field_begin(), RD->field_end()));
3294 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003295 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003296 for (RecordDecl::field_iterator Field = RD->field_begin(),
3297 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3298 // Anonymous bit-fields are not considered members of the class for
3299 // purposes of aggregate initialization.
3300 if (Field->isUnnamedBitfield())
3301 continue;
3302
3303 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003304
Richard Smith745f5142012-01-27 01:14:48 +00003305 bool HaveInit = ElementNo < E->getNumInits();
3306
3307 // FIXME: Diagnostics here should point to the end of the initializer
3308 // list, not the start.
3309 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3310 *Field, &Layout);
3311
3312 // Perform an implicit value-initialization for members beyond the end of
3313 // the initializer list.
3314 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3315
3316 if (!EvaluateConstantExpression(
3317 Result.getStructField((*Field)->getFieldIndex()),
3318 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3319 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003320 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003321 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003322 }
3323 }
3324
Richard Smith745f5142012-01-27 01:14:48 +00003325 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003326}
3327
3328bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3329 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003330 bool ZeroInit = E->requiresZeroInitialization();
3331 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003332 // If we've already performed zero-initialization, we're already done.
3333 if (!Result.isUninit())
3334 return true;
3335
Richard Smith51201882011-12-30 21:15:51 +00003336 if (ZeroInit)
3337 return ZeroInitialization(E);
3338
Richard Smith61802452011-12-22 02:22:31 +00003339 const CXXRecordDecl *RD = FD->getParent();
3340 if (RD->isUnion())
3341 Result = APValue((FieldDecl*)0);
3342 else
3343 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3344 std::distance(RD->field_begin(), RD->field_end()));
3345 return true;
3346 }
3347
Richard Smith180f4792011-11-10 06:34:14 +00003348 const FunctionDecl *Definition = 0;
3349 FD->getBody(Definition);
3350
Richard Smithc1c5f272011-12-13 06:39:58 +00003351 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3352 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003353
Richard Smith610a60c2012-01-10 04:32:03 +00003354 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003355 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003356 if (const MaterializeTemporaryExpr *ME
3357 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3358 return Visit(ME->GetTemporaryExpr());
3359
Richard Smith51201882011-12-30 21:15:51 +00003360 if (ZeroInit && !ZeroInitialization(E))
3361 return false;
3362
Richard Smith180f4792011-11-10 06:34:14 +00003363 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003364 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003365 cast<CXXConstructorDecl>(Definition), Info,
3366 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003367}
3368
3369static bool EvaluateRecord(const Expr *E, const LValue &This,
3370 APValue &Result, EvalInfo &Info) {
3371 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003372 "can't evaluate expression as a record rvalue");
3373 return RecordExprEvaluator(Info, This, Result).Visit(E);
3374}
3375
3376//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003377// Temporary Evaluation
3378//
3379// Temporaries are represented in the AST as rvalues, but generally behave like
3380// lvalues. The full-object of which the temporary is a subobject is implicitly
3381// materialized so that a reference can bind to it.
3382//===----------------------------------------------------------------------===//
3383namespace {
3384class TemporaryExprEvaluator
3385 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3386public:
3387 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3388 LValueExprEvaluatorBaseTy(Info, Result) {}
3389
3390 /// Visit an expression which constructs the value of this temporary.
3391 bool VisitConstructExpr(const Expr *E) {
3392 Result.set(E, Info.CurrentCall);
3393 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3394 Result, E);
3395 }
3396
3397 bool VisitCastExpr(const CastExpr *E) {
3398 switch (E->getCastKind()) {
3399 default:
3400 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3401
3402 case CK_ConstructorConversion:
3403 return VisitConstructExpr(E->getSubExpr());
3404 }
3405 }
3406 bool VisitInitListExpr(const InitListExpr *E) {
3407 return VisitConstructExpr(E);
3408 }
3409 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3410 return VisitConstructExpr(E);
3411 }
3412 bool VisitCallExpr(const CallExpr *E) {
3413 return VisitConstructExpr(E);
3414 }
3415};
3416} // end anonymous namespace
3417
3418/// Evaluate an expression of record type as a temporary.
3419static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003420 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003421 return TemporaryExprEvaluator(Info, Result).Visit(E);
3422}
3423
3424//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003425// Vector Evaluation
3426//===----------------------------------------------------------------------===//
3427
3428namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003429 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003430 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3431 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003432 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Richard Smith07fc6572011-10-22 21:10:00 +00003434 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3435 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Richard Smith07fc6572011-10-22 21:10:00 +00003437 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3438 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3439 // FIXME: remove this APValue copy.
3440 Result = APValue(V.data(), V.size());
3441 return true;
3442 }
Richard Smith69c2c502011-11-04 05:33:44 +00003443 bool Success(const CCValue &V, const Expr *E) {
3444 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003445 Result = V;
3446 return true;
3447 }
Richard Smith51201882011-12-30 21:15:51 +00003448 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Richard Smith07fc6572011-10-22 21:10:00 +00003450 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003451 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003452 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003453 bool VisitInitListExpr(const InitListExpr *E);
3454 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003455 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003456 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003457 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003458 };
3459} // end anonymous namespace
3460
3461static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003462 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003463 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003464}
3465
Richard Smith07fc6572011-10-22 21:10:00 +00003466bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3467 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003468 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Richard Smithd62ca372011-12-06 22:44:34 +00003470 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003471 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003472
Eli Friedman46a52322011-03-25 00:43:55 +00003473 switch (E->getCastKind()) {
3474 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003475 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003476 if (SETy->isIntegerType()) {
3477 APSInt IntResult;
3478 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003479 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003480 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003481 } else if (SETy->isRealFloatingType()) {
3482 APFloat F(0.0);
3483 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003484 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003485 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003486 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003487 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003488 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003489
3490 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003491 SmallVector<APValue, 4> Elts(NElts, Val);
3492 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003493 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003494 case CK_BitCast: {
3495 // Evaluate the operand into an APInt we can extract from.
3496 llvm::APInt SValInt;
3497 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3498 return false;
3499 // Extract the elements
3500 QualType EltTy = VTy->getElementType();
3501 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3502 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3503 SmallVector<APValue, 4> Elts;
3504 if (EltTy->isRealFloatingType()) {
3505 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3506 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3507 unsigned FloatEltSize = EltSize;
3508 if (&Sem == &APFloat::x87DoubleExtended)
3509 FloatEltSize = 80;
3510 for (unsigned i = 0; i < NElts; i++) {
3511 llvm::APInt Elt;
3512 if (BigEndian)
3513 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3514 else
3515 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3516 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3517 }
3518 } else if (EltTy->isIntegerType()) {
3519 for (unsigned i = 0; i < NElts; i++) {
3520 llvm::APInt Elt;
3521 if (BigEndian)
3522 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3523 else
3524 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3525 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3526 }
3527 } else {
3528 return Error(E);
3529 }
3530 return Success(Elts, E);
3531 }
Eli Friedman46a52322011-03-25 00:43:55 +00003532 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003533 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003534 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003535}
3536
Richard Smith07fc6572011-10-22 21:10:00 +00003537bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003538VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003539 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003540 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003541 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Nate Begeman59b5da62009-01-18 03:20:47 +00003543 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003544 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003545
Eli Friedman3edd5a92012-01-03 23:24:20 +00003546 // The number of initializers can be less than the number of
3547 // vector elements. For OpenCL, this can be due to nested vector
3548 // initialization. For GCC compatibility, missing trailing elements
3549 // should be initialized with zeroes.
3550 unsigned CountInits = 0, CountElts = 0;
3551 while (CountElts < NumElements) {
3552 // Handle nested vector initialization.
3553 if (CountInits < NumInits
3554 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3555 APValue v;
3556 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3557 return Error(E);
3558 unsigned vlen = v.getVectorLength();
3559 for (unsigned j = 0; j < vlen; j++)
3560 Elements.push_back(v.getVectorElt(j));
3561 CountElts += vlen;
3562 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003563 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003564 if (CountInits < NumInits) {
3565 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3566 return Error(E);
3567 } else // trailing integer zero.
3568 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3569 Elements.push_back(APValue(sInt));
3570 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003571 } else {
3572 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003573 if (CountInits < NumInits) {
3574 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3575 return Error(E);
3576 } else // trailing float zero.
3577 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3578 Elements.push_back(APValue(f));
3579 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003580 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003581 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003582 }
Richard Smith07fc6572011-10-22 21:10:00 +00003583 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003584}
3585
Richard Smith07fc6572011-10-22 21:10:00 +00003586bool
Richard Smith51201882011-12-30 21:15:51 +00003587VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003588 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003589 QualType EltTy = VT->getElementType();
3590 APValue ZeroElement;
3591 if (EltTy->isIntegerType())
3592 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3593 else
3594 ZeroElement =
3595 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3596
Chris Lattner5f9e2722011-07-23 10:55:15 +00003597 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003598 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003599}
3600
Richard Smith07fc6572011-10-22 21:10:00 +00003601bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003602 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003603 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003604}
3605
Nate Begeman59b5da62009-01-18 03:20:47 +00003606//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003607// Array Evaluation
3608//===----------------------------------------------------------------------===//
3609
3610namespace {
3611 class ArrayExprEvaluator
3612 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003613 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003614 APValue &Result;
3615 public:
3616
Richard Smith180f4792011-11-10 06:34:14 +00003617 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3618 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003619
3620 bool Success(const APValue &V, const Expr *E) {
3621 assert(V.isArray() && "Expected array type");
3622 Result = V;
3623 return true;
3624 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003625
Richard Smith51201882011-12-30 21:15:51 +00003626 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003627 const ConstantArrayType *CAT =
3628 Info.Ctx.getAsConstantArrayType(E->getType());
3629 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003630 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003631
3632 Result = APValue(APValue::UninitArray(), 0,
3633 CAT->getSize().getZExtValue());
3634 if (!Result.hasArrayFiller()) return true;
3635
Richard Smith51201882011-12-30 21:15:51 +00003636 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003637 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003638 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003639 ImplicitValueInitExpr VIE(CAT->getElementType());
3640 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3641 Subobject, &VIE);
3642 }
3643
Richard Smithcc5d4f62011-11-07 09:22:26 +00003644 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003645 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003646 };
3647} // end anonymous namespace
3648
Richard Smith180f4792011-11-10 06:34:14 +00003649static bool EvaluateArray(const Expr *E, const LValue &This,
3650 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003651 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003652 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003653}
3654
3655bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3656 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3657 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003658 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003659
Richard Smith974c5f92011-12-22 01:07:19 +00003660 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3661 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003662 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003663 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3664 LValue LV;
3665 if (!EvaluateLValue(E->getInit(0), LV, Info))
3666 return false;
3667 uint64_t NumElements = CAT->getSize().getZExtValue();
3668 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3669
3670 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003671 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003672 for (uint64_t I = 0; I < NumElements; ++I) {
3673 CCValue Char;
3674 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003675 CAT->getElementType(), LV, Char) ||
3676 !CheckConstantExpression(Info, E->getInit(0), Char,
3677 Result.getArrayInitializedElt(I)) ||
3678 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003679 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003680 return false;
3681 }
3682 return true;
3683 }
3684
Richard Smith745f5142012-01-27 01:14:48 +00003685 bool Success = true;
3686
Richard Smithcc5d4f62011-11-07 09:22:26 +00003687 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3688 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003689 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003690 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003691 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003692 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003693 I != End; ++I, ++Index) {
3694 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003695 Info, Subobject, cast<Expr>(*I)) ||
3696 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3697 CAT->getElementType(), 1)) {
3698 if (!Info.keepEvaluatingAfterFailure())
3699 return false;
3700 Success = false;
3701 }
Richard Smith180f4792011-11-10 06:34:14 +00003702 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003703
Richard Smith745f5142012-01-27 01:14:48 +00003704 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003705 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003706 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3707 // but sometimes does:
3708 // struct S { constexpr S() : p(&p) {} void *p; };
3709 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003710 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003711 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003712}
3713
Richard Smithe24f5fc2011-11-17 22:56:20 +00003714bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3715 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3716 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003717 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003718
Richard Smithec789162012-01-12 18:54:33 +00003719 bool HadZeroInit = !Result.isUninit();
3720 if (!HadZeroInit)
3721 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003722 if (!Result.hasArrayFiller())
3723 return true;
3724
3725 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003726
Richard Smith51201882011-12-30 21:15:51 +00003727 bool ZeroInit = E->requiresZeroInitialization();
3728 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003729 if (HadZeroInit)
3730 return true;
3731
Richard Smith51201882011-12-30 21:15:51 +00003732 if (ZeroInit) {
3733 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003734 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003735 ImplicitValueInitExpr VIE(CAT->getElementType());
3736 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3737 Subobject, &VIE);
3738 }
3739
Richard Smith61802452011-12-22 02:22:31 +00003740 const CXXRecordDecl *RD = FD->getParent();
3741 if (RD->isUnion())
3742 Result.getArrayFiller() = APValue((FieldDecl*)0);
3743 else
3744 Result.getArrayFiller() =
3745 APValue(APValue::UninitStruct(), RD->getNumBases(),
3746 std::distance(RD->field_begin(), RD->field_end()));
3747 return true;
3748 }
3749
Richard Smithe24f5fc2011-11-17 22:56:20 +00003750 const FunctionDecl *Definition = 0;
3751 FD->getBody(Definition);
3752
Richard Smithc1c5f272011-12-13 06:39:58 +00003753 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3754 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003755
3756 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3757 // but sometimes does:
3758 // struct S { constexpr S() : p(&p) {} void *p; };
3759 // S s[10];
3760 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003761 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003762
Richard Smithec789162012-01-12 18:54:33 +00003763 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003764 ImplicitValueInitExpr VIE(CAT->getElementType());
3765 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3766 &VIE))
3767 return false;
3768 }
3769
Richard Smithe24f5fc2011-11-17 22:56:20 +00003770 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003771 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003772 cast<CXXConstructorDecl>(Definition),
3773 Info, Result.getArrayFiller());
3774}
3775
Richard Smithcc5d4f62011-11-07 09:22:26 +00003776//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003777// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003778//
3779// As a GNU extension, we support casting pointers to sufficiently-wide integer
3780// types and back in constant folding. Integer values are thus represented
3781// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003782//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003783
3784namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003785class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003786 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003787 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003788public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003789 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003790 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003791
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003792 bool Success(const llvm::APSInt &SI, const Expr *E) {
3793 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003794 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003795 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003796 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003797 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003798 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003799 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003800 return true;
3801 }
3802
Daniel Dunbar131eb432009-02-19 09:06:44 +00003803 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003804 assert(E->getType()->isIntegralOrEnumerationType() &&
3805 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003806 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003807 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003808 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003809 Result.getInt().setIsUnsigned(
3810 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003811 return true;
3812 }
3813
3814 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003815 assert(E->getType()->isIntegralOrEnumerationType() &&
3816 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003817 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003818 return true;
3819 }
3820
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003821 bool Success(CharUnits Size, const Expr *E) {
3822 return Success(Size.getQuantity(), E);
3823 }
3824
Richard Smith47a1eed2011-10-29 20:57:55 +00003825 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003826 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003827 Result = V;
3828 return true;
3829 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003830 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003831 }
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Richard Smith51201882011-12-30 21:15:51 +00003833 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003834
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003835 //===--------------------------------------------------------------------===//
3836 // Visitor Methods
3837 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003838
Chris Lattner4c4867e2008-07-12 00:38:25 +00003839 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003840 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003841 }
3842 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003843 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003844 }
Eli Friedman04309752009-11-24 05:28:59 +00003845
3846 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3847 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003848 if (CheckReferencedDecl(E, E->getDecl()))
3849 return true;
3850
3851 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003852 }
3853 bool VisitMemberExpr(const MemberExpr *E) {
3854 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003855 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003856 return true;
3857 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003858
3859 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003860 }
3861
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003862 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003863 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003864 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003865 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003866
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003867 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003868 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003869
Anders Carlsson3068d112008-11-16 19:01:22 +00003870 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003871 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Richard Smithf10d9172011-10-11 21:43:33 +00003874 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003875 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003876 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003877 }
3878
Sebastian Redl64b45f72009-01-05 20:52:13 +00003879 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003880 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003881 }
3882
Francois Pichet6ad6f282010-12-07 00:08:36 +00003883 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3884 return Success(E->getValue(), E);
3885 }
3886
John Wiegley21ff2e52011-04-28 00:16:57 +00003887 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3888 return Success(E->getValue(), E);
3889 }
3890
John Wiegley55262202011-04-25 06:54:41 +00003891 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3892 return Success(E->getValue(), E);
3893 }
3894
Eli Friedman722c7172009-02-28 03:59:05 +00003895 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003896 bool VisitUnaryImag(const UnaryOperator *E);
3897
Sebastian Redl295995c2010-09-10 20:55:47 +00003898 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003899 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003900
Chris Lattnerfcee0012008-07-11 21:24:13 +00003901private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003902 CharUnits GetAlignOfExpr(const Expr *E);
3903 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003904 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003905 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003906 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003907};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003908} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003909
Richard Smithc49bd112011-10-28 17:51:58 +00003910/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3911/// produce either the integer value or a pointer.
3912///
3913/// GCC has a heinous extension which folds casts between pointer types and
3914/// pointer-sized integral types. We support this by allowing the evaluation of
3915/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3916/// Some simple arithmetic on such values is supported (they are treated much
3917/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003918static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003919 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003920 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003921 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003922}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003923
Richard Smithf48fdb02011-12-09 22:58:01 +00003924static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003925 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003926 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003927 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003928 if (!Val.isInt()) {
3929 // FIXME: It would be better to produce the diagnostic for casting
3930 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003931 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003932 return false;
3933 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003934 Result = Val.getInt();
3935 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003936}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003937
Richard Smithf48fdb02011-12-09 22:58:01 +00003938/// Check whether the given declaration can be directly converted to an integral
3939/// rvalue. If not, no diagnostic is produced; there are other things we can
3940/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003941bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003942 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003943 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003944 // Check for signedness/width mismatches between E type and ECD value.
3945 bool SameSign = (ECD->getInitVal().isSigned()
3946 == E->getType()->isSignedIntegerOrEnumerationType());
3947 bool SameWidth = (ECD->getInitVal().getBitWidth()
3948 == Info.Ctx.getIntWidth(E->getType()));
3949 if (SameSign && SameWidth)
3950 return Success(ECD->getInitVal(), E);
3951 else {
3952 // Get rid of mismatch (otherwise Success assertions will fail)
3953 // by computing a new value matching the type of E.
3954 llvm::APSInt Val = ECD->getInitVal();
3955 if (!SameSign)
3956 Val.setIsSigned(!ECD->getInitVal().isSigned());
3957 if (!SameWidth)
3958 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3959 return Success(Val, E);
3960 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003961 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003962 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003963}
3964
Chris Lattnera4d55d82008-10-06 06:40:35 +00003965/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3966/// as GCC.
3967static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3968 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003969 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003970 enum gcc_type_class {
3971 no_type_class = -1,
3972 void_type_class, integer_type_class, char_type_class,
3973 enumeral_type_class, boolean_type_class,
3974 pointer_type_class, reference_type_class, offset_type_class,
3975 real_type_class, complex_type_class,
3976 function_type_class, method_type_class,
3977 record_type_class, union_type_class,
3978 array_type_class, string_type_class,
3979 lang_type_class
3980 };
Mike Stump1eb44332009-09-09 15:08:12 +00003981
3982 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003983 // ideal, however it is what gcc does.
3984 if (E->getNumArgs() == 0)
3985 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Chris Lattnera4d55d82008-10-06 06:40:35 +00003987 QualType ArgTy = E->getArg(0)->getType();
3988 if (ArgTy->isVoidType())
3989 return void_type_class;
3990 else if (ArgTy->isEnumeralType())
3991 return enumeral_type_class;
3992 else if (ArgTy->isBooleanType())
3993 return boolean_type_class;
3994 else if (ArgTy->isCharType())
3995 return string_type_class; // gcc doesn't appear to use char_type_class
3996 else if (ArgTy->isIntegerType())
3997 return integer_type_class;
3998 else if (ArgTy->isPointerType())
3999 return pointer_type_class;
4000 else if (ArgTy->isReferenceType())
4001 return reference_type_class;
4002 else if (ArgTy->isRealType())
4003 return real_type_class;
4004 else if (ArgTy->isComplexType())
4005 return complex_type_class;
4006 else if (ArgTy->isFunctionType())
4007 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004008 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004009 return record_type_class;
4010 else if (ArgTy->isUnionType())
4011 return union_type_class;
4012 else if (ArgTy->isArrayType())
4013 return array_type_class;
4014 else if (ArgTy->isUnionType())
4015 return union_type_class;
4016 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004017 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004018}
4019
Richard Smith80d4b552011-12-28 19:48:30 +00004020/// EvaluateBuiltinConstantPForLValue - Determine the result of
4021/// __builtin_constant_p when applied to the given lvalue.
4022///
4023/// An lvalue is only "constant" if it is a pointer or reference to the first
4024/// character of a string literal.
4025template<typename LValue>
4026static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4027 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4028 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4029}
4030
4031/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4032/// GCC as we can manage.
4033static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4034 QualType ArgType = Arg->getType();
4035
4036 // __builtin_constant_p always has one operand. The rules which gcc follows
4037 // are not precisely documented, but are as follows:
4038 //
4039 // - If the operand is of integral, floating, complex or enumeration type,
4040 // and can be folded to a known value of that type, it returns 1.
4041 // - If the operand and can be folded to a pointer to the first character
4042 // of a string literal (or such a pointer cast to an integral type), it
4043 // returns 1.
4044 //
4045 // Otherwise, it returns 0.
4046 //
4047 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4048 // its support for this does not currently work.
4049 if (ArgType->isIntegralOrEnumerationType()) {
4050 Expr::EvalResult Result;
4051 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4052 return false;
4053
4054 APValue &V = Result.Val;
4055 if (V.getKind() == APValue::Int)
4056 return true;
4057
4058 return EvaluateBuiltinConstantPForLValue(V);
4059 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4060 return Arg->isEvaluatable(Ctx);
4061 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4062 LValue LV;
4063 Expr::EvalStatus Status;
4064 EvalInfo Info(Ctx, Status);
4065 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4066 : EvaluatePointer(Arg, LV, Info)) &&
4067 !Status.HasSideEffects)
4068 return EvaluateBuiltinConstantPForLValue(LV);
4069 }
4070
4071 // Anything else isn't considered to be sufficiently constant.
4072 return false;
4073}
4074
John McCall42c8f872010-05-10 23:27:23 +00004075/// Retrieves the "underlying object type" of the given expression,
4076/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004077QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4078 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4079 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004080 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004081 } else if (const Expr *E = B.get<const Expr*>()) {
4082 if (isa<CompoundLiteralExpr>(E))
4083 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004084 }
4085
4086 return QualType();
4087}
4088
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004089bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004090 // TODO: Perhaps we should let LLVM lower this?
4091 LValue Base;
4092 if (!EvaluatePointer(E->getArg(0), Base, Info))
4093 return false;
4094
4095 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004096 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004097
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004098 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004099 if (T.isNull() ||
4100 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004101 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004102 T->isVariablyModifiedType() ||
4103 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004104 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004105
4106 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4107 CharUnits Offset = Base.getLValueOffset();
4108
4109 if (!Offset.isNegative() && Offset <= Size)
4110 Size -= Offset;
4111 else
4112 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004113 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004114}
4115
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004116bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004117 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004118 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004119 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004120
4121 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004122 if (TryEvaluateBuiltinObjectSize(E))
4123 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004124
Eric Christopherb2aaf512010-01-19 22:58:35 +00004125 // If evaluating the argument has side-effects we can't determine
4126 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004127 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004128 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004129 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004130 return Success(0, E);
4131 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004132
Richard Smithf48fdb02011-12-09 22:58:01 +00004133 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004134 }
4135
Chris Lattner019f4e82008-10-06 05:28:25 +00004136 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004137 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Richard Smith80d4b552011-12-28 19:48:30 +00004139 case Builtin::BI__builtin_constant_p:
4140 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004141
Chris Lattner21fb98e2009-09-23 06:06:36 +00004142 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004143 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004144 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004145 return Success(Operand, E);
4146 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004147
4148 case Builtin::BI__builtin_expect:
4149 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004150
Douglas Gregor5726d402010-09-10 06:27:15 +00004151 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004152 // A call to strlen is not a constant expression.
4153 if (Info.getLangOpts().CPlusPlus0x)
4154 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4155 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4156 else
4157 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4158 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004159 case Builtin::BI__builtin_strlen:
4160 // As an extension, we support strlen() and __builtin_strlen() as constant
4161 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004162 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004163 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4164 // The string literal may have embedded null characters. Find the first
4165 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004166 StringRef Str = S->getString();
4167 StringRef::size_type Pos = Str.find(0);
4168 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004169 Str = Str.substr(0, Pos);
4170
4171 return Success(Str.size(), E);
4172 }
4173
Richard Smithf48fdb02011-12-09 22:58:01 +00004174 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004175
4176 case Builtin::BI__atomic_is_lock_free: {
4177 APSInt SizeVal;
4178 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4179 return false;
4180
4181 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4182 // of two less than the maximum inline atomic width, we know it is
4183 // lock-free. If the size isn't a power of two, or greater than the
4184 // maximum alignment where we promote atomics, we know it is not lock-free
4185 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4186 // the answer can only be determined at runtime; for example, 16-byte
4187 // atomics have lock-free implementations on some, but not all,
4188 // x86-64 processors.
4189
4190 // Check power-of-two.
4191 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4192 if (!Size.isPowerOfTwo())
4193#if 0
4194 // FIXME: Suppress this folding until the ABI for the promotion width
4195 // settles.
4196 return Success(0, E);
4197#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004198 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004199#endif
4200
4201#if 0
4202 // Check against promotion width.
4203 // FIXME: Suppress this folding until the ABI for the promotion width
4204 // settles.
4205 unsigned PromoteWidthBits =
4206 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4207 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4208 return Success(0, E);
4209#endif
4210
4211 // Check against inlining width.
4212 unsigned InlineWidthBits =
4213 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4214 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4215 return Success(1, E);
4216
Richard Smithf48fdb02011-12-09 22:58:01 +00004217 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004218 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004219 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004220}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004221
Richard Smith625b8072011-10-31 01:37:14 +00004222static bool HasSameBase(const LValue &A, const LValue &B) {
4223 if (!A.getLValueBase())
4224 return !B.getLValueBase();
4225 if (!B.getLValueBase())
4226 return false;
4227
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004228 if (A.getLValueBase().getOpaqueValue() !=
4229 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004230 const Decl *ADecl = GetLValueBaseDecl(A);
4231 if (!ADecl)
4232 return false;
4233 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004234 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004235 return false;
4236 }
4237
4238 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004239 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004240}
4241
Richard Smith7b48a292012-02-01 05:53:12 +00004242/// Perform the given integer operation, which is known to need at most BitWidth
4243/// bits, and check for overflow in the original type (if that type was not an
4244/// unsigned type).
4245template<typename Operation>
4246static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4247 const APSInt &LHS, const APSInt &RHS,
4248 unsigned BitWidth, Operation Op) {
4249 if (LHS.isUnsigned())
4250 return Op(LHS, RHS);
4251
4252 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4253 APSInt Result = Value.trunc(LHS.getBitWidth());
4254 if (Result.extend(BitWidth) != Value)
4255 HandleOverflow(Info, E, Value, E->getType());
4256 return Result;
4257}
4258
Chris Lattnerb542afe2008-07-11 19:10:17 +00004259bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004260 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004261 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004262
John McCall2de56d12010-08-25 11:45:40 +00004263 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004264 VisitIgnoredValue(E->getLHS());
4265 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004266 }
4267
4268 if (E->isLogicalOp()) {
4269 // These need to be handled specially because the operands aren't
4270 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004271 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Richard Smithc49bd112011-10-28 17:51:58 +00004273 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004274 // We were able to evaluate the LHS, see if we can get away with not
4275 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004276 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004277 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004278
Richard Smithc49bd112011-10-28 17:51:58 +00004279 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004280 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004281 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004282 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004283 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004284 }
4285 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004286 // FIXME: If both evaluations fail, we should produce the diagnostic from
4287 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4288 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004289 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004290 // We can't evaluate the LHS; however, sometimes the result
4291 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004292 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004293 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004294 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004295 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004296
4297 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004298 }
4299 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004300 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004301
Eli Friedmana6afa762008-11-13 06:09:17 +00004302 return false;
4303 }
4304
Anders Carlsson286f85e2008-11-16 07:17:21 +00004305 QualType LHSTy = E->getLHS()->getType();
4306 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004307
4308 if (LHSTy->isAnyComplexType()) {
4309 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004310 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004311
Richard Smith745f5142012-01-27 01:14:48 +00004312 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4313 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004314 return false;
4315
Richard Smith745f5142012-01-27 01:14:48 +00004316 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004317 return false;
4318
4319 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004320 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004321 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004322 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004323 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4324
John McCall2de56d12010-08-25 11:45:40 +00004325 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004326 return Success((CR_r == APFloat::cmpEqual &&
4327 CR_i == APFloat::cmpEqual), E);
4328 else {
John McCall2de56d12010-08-25 11:45:40 +00004329 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004330 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004331 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004332 CR_r == APFloat::cmpLessThan ||
4333 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004334 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004335 CR_i == APFloat::cmpLessThan ||
4336 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004337 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004338 } else {
John McCall2de56d12010-08-25 11:45:40 +00004339 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004340 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4341 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4342 else {
John McCall2de56d12010-08-25 11:45:40 +00004343 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004344 "Invalid compex comparison.");
4345 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4346 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4347 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004348 }
4349 }
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Anders Carlsson286f85e2008-11-16 07:17:21 +00004351 if (LHSTy->isRealFloatingType() &&
4352 RHSTy->isRealFloatingType()) {
4353 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004354
Richard Smith745f5142012-01-27 01:14:48 +00004355 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4356 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004357 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Richard Smith745f5142012-01-27 01:14:48 +00004359 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004360 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Anders Carlsson286f85e2008-11-16 07:17:21 +00004362 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004363
Anders Carlsson286f85e2008-11-16 07:17:21 +00004364 switch (E->getOpcode()) {
4365 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004366 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004367 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004368 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004369 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004370 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004371 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004372 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004373 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004374 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004375 E);
John McCall2de56d12010-08-25 11:45:40 +00004376 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004377 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004378 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004379 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004380 || CR == APFloat::cmpLessThan
4381 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004382 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004383 }
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004385 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004386 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004387 LValue LHSValue, RHSValue;
4388
4389 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4390 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004391 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004392
Richard Smith745f5142012-01-27 01:14:48 +00004393 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004394 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004395
Richard Smith625b8072011-10-31 01:37:14 +00004396 // Reject differing bases from the normal codepath; we special-case
4397 // comparisons to null.
4398 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004399 if (E->getOpcode() == BO_Sub) {
4400 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004401 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4402 return false;
4403 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4404 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4405 if (!LHSExpr || !RHSExpr)
4406 return false;
4407 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4408 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4409 if (!LHSAddrExpr || !RHSAddrExpr)
4410 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004411 // Make sure both labels come from the same function.
4412 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4413 RHSAddrExpr->getLabel()->getDeclContext())
4414 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004415 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4416 return true;
4417 }
Richard Smith9e36b532011-10-31 05:11:32 +00004418 // Inequalities and subtractions between unrelated pointers have
4419 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004420 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004421 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004422 // A constant address may compare equal to the address of a symbol.
4423 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004424 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004425 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4426 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004427 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004428 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004429 // distinct addresses. In clang, the result of such a comparison is
4430 // unspecified, so it is not a constant expression. However, we do know
4431 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004432 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4433 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004434 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004435 // We can't tell whether weak symbols will end up pointing to the same
4436 // object.
4437 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004438 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004439 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004440 // (Note that clang defaults to -fmerge-all-constants, which can
4441 // lead to inconsistent results for comparisons involving the address
4442 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004443 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004444 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004445
Richard Smith15efc4d2012-02-01 08:10:20 +00004446 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4447 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4448
Richard Smithf15fda02012-02-02 01:16:57 +00004449 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4450 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4451
John McCall2de56d12010-08-25 11:45:40 +00004452 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004453 // C++11 [expr.add]p6:
4454 // Unless both pointers point to elements of the same array object, or
4455 // one past the last element of the array object, the behavior is
4456 // undefined.
4457 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4458 !AreElementsOfSameArray(getType(LHSValue.Base),
4459 LHSDesignator, RHSDesignator))
4460 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4461
Chris Lattner4992bdd2010-04-20 17:13:14 +00004462 QualType Type = E->getLHS()->getType();
4463 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004464
Richard Smith180f4792011-11-10 06:34:14 +00004465 CharUnits ElementSize;
4466 if (!HandleSizeof(Info, ElementType, ElementSize))
4467 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004468
Richard Smith15efc4d2012-02-01 08:10:20 +00004469 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4470 // and produce incorrect results when it overflows. Such behavior
4471 // appears to be non-conforming, but is common, so perhaps we should
4472 // assume the standard intended for such cases to be undefined behavior
4473 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004474
Richard Smith15efc4d2012-02-01 08:10:20 +00004475 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4476 // overflow in the final conversion to ptrdiff_t.
4477 APSInt LHS(
4478 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4479 APSInt RHS(
4480 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4481 APSInt ElemSize(
4482 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4483 APSInt TrueResult = (LHS - RHS) / ElemSize;
4484 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4485
4486 if (Result.extend(65) != TrueResult)
4487 HandleOverflow(Info, E, TrueResult, E->getType());
4488 return Success(Result, E);
4489 }
Richard Smith82f28582012-01-31 06:41:30 +00004490
4491 // C++11 [expr.rel]p3:
4492 // Pointers to void (after pointer conversions) can be compared, with a
4493 // result defined as follows: If both pointers represent the same
4494 // address or are both the null pointer value, the result is true if the
4495 // operator is <= or >= and false otherwise; otherwise the result is
4496 // unspecified.
4497 // We interpret this as applying to pointers to *cv* void.
4498 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004499 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004500 CCEDiag(E, diag::note_constexpr_void_comparison);
4501
Richard Smithf15fda02012-02-02 01:16:57 +00004502 // C++11 [expr.rel]p2:
4503 // - If two pointers point to non-static data members of the same object,
4504 // or to subobjects or array elements fo such members, recursively, the
4505 // pointer to the later declared member compares greater provided the
4506 // two members have the same access control and provided their class is
4507 // not a union.
4508 // [...]
4509 // - Otherwise pointer comparisons are unspecified.
4510 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4511 E->isRelationalOp()) {
4512 bool WasArrayIndex;
4513 unsigned Mismatch =
4514 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4515 RHSDesignator, WasArrayIndex);
4516 // At the point where the designators diverge, the comparison has a
4517 // specified value if:
4518 // - we are comparing array indices
4519 // - we are comparing fields of a union, or fields with the same access
4520 // Otherwise, the result is unspecified and thus the comparison is not a
4521 // constant expression.
4522 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4523 Mismatch < RHSDesignator.Entries.size()) {
4524 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4525 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4526 if (!LF && !RF)
4527 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4528 else if (!LF)
4529 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4530 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4531 << RF->getParent() << RF;
4532 else if (!RF)
4533 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4534 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4535 << LF->getParent() << LF;
4536 else if (!LF->getParent()->isUnion() &&
4537 LF->getAccess() != RF->getAccess())
4538 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4539 << LF << LF->getAccess() << RF << RF->getAccess()
4540 << LF->getParent();
4541 }
4542 }
4543
Richard Smith625b8072011-10-31 01:37:14 +00004544 switch (E->getOpcode()) {
4545 default: llvm_unreachable("missing comparison operator");
4546 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4547 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4548 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4549 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4550 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4551 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004552 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004553 }
4554 }
Richard Smithb02e4622012-02-01 01:42:44 +00004555
4556 if (LHSTy->isMemberPointerType()) {
4557 assert(E->isEqualityOp() && "unexpected member pointer operation");
4558 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4559
4560 MemberPtr LHSValue, RHSValue;
4561
4562 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4563 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4564 return false;
4565
4566 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4567 return false;
4568
4569 // C++11 [expr.eq]p2:
4570 // If both operands are null, they compare equal. Otherwise if only one is
4571 // null, they compare unequal.
4572 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4573 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4574 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4575 }
4576
4577 // Otherwise if either is a pointer to a virtual member function, the
4578 // result is unspecified.
4579 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4580 if (MD->isVirtual())
4581 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4583 if (MD->isVirtual())
4584 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4585
4586 // Otherwise they compare equal if and only if they would refer to the
4587 // same member of the same most derived object or the same subobject if
4588 // they were dereferenced with a hypothetical object of the associated
4589 // class type.
4590 bool Equal = LHSValue == RHSValue;
4591 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4592 }
4593
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004594 if (!LHSTy->isIntegralOrEnumerationType() ||
4595 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004596 // We can't continue from here for non-integral types.
4597 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004598 }
4599
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004600 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004601 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004602
4603 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4604 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004605 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004606
Richard Smith745f5142012-01-27 01:14:48 +00004607 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004608 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004609
Richard Smith47a1eed2011-10-29 20:57:55 +00004610 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004611
4612 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004613 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004614 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4615 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004616 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004617 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004618 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004619 LHSVal.getLValueOffset() -= AdditionalOffset;
4620 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004621 return true;
4622 }
4623
4624 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004625 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004626 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004627 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4628 LHSVal.getInt().getZExtValue());
4629 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004630 return true;
4631 }
4632
Eli Friedman65639282012-01-04 23:13:47 +00004633 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4634 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004635 if (!LHSVal.getLValueOffset().isZero() ||
4636 !RHSVal.getLValueOffset().isZero())
4637 return false;
4638 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4639 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4640 if (!LHSExpr || !RHSExpr)
4641 return false;
4642 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4643 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4644 if (!LHSAddrExpr || !RHSAddrExpr)
4645 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004646 // Make sure both labels come from the same function.
4647 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4648 RHSAddrExpr->getLabel()->getDeclContext())
4649 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004650 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4651 return true;
4652 }
4653
Eli Friedman42edd0d2009-03-24 01:14:50 +00004654 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004655 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004656 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004657
Richard Smithc49bd112011-10-28 17:51:58 +00004658 APSInt &LHS = LHSVal.getInt();
4659 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004660
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004661 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004662 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004663 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004664 case BO_Mul:
4665 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4666 LHS.getBitWidth() * 2,
4667 std::multiplies<APSInt>()), E);
4668 case BO_Add:
4669 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4670 LHS.getBitWidth() + 1,
4671 std::plus<APSInt>()), E);
4672 case BO_Sub:
4673 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4674 LHS.getBitWidth() + 1,
4675 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004676 case BO_And: return Success(LHS & RHS, E);
4677 case BO_Xor: return Success(LHS ^ RHS, E);
4678 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004679 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004680 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004681 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004682 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004683 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4684 // actually undefined behavior in C++11 due to a language defect.
4685 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4686 LHS.isSigned() && LHS.isMinSignedValue())
4687 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4688 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004689 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004690 // During constant-folding, a negative shift is an opposite shift. Such a
4691 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004692 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004693 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004694 RHS = -RHS;
4695 goto shift_right;
4696 }
4697
4698 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004699 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4700 // shifted type.
4701 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4702 if (SA != RHS) {
4703 CCEDiag(E, diag::note_constexpr_large_shift)
4704 << RHS << E->getType() << LHS.getBitWidth();
4705 } else if (LHS.isSigned()) {
4706 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4707 // operand, and must not overflow.
4708 if (LHS.isNegative())
4709 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4710 else if (LHS.countLeadingZeros() <= SA)
4711 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4712 E->getType());
4713 }
4714
Richard Smithc49bd112011-10-28 17:51:58 +00004715 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004716 }
John McCall2de56d12010-08-25 11:45:40 +00004717 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004718 // During constant-folding, a negative shift is an opposite shift. Such a
4719 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004720 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004721 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004722 RHS = -RHS;
4723 goto shift_left;
4724 }
4725
4726 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004727 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4728 // shifted type.
4729 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4730 if (SA != RHS)
4731 CCEDiag(E, diag::note_constexpr_large_shift)
4732 << RHS << E->getType() << LHS.getBitWidth();
4733
Richard Smithc49bd112011-10-28 17:51:58 +00004734 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004735 }
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Richard Smithc49bd112011-10-28 17:51:58 +00004737 case BO_LT: return Success(LHS < RHS, E);
4738 case BO_GT: return Success(LHS > RHS, E);
4739 case BO_LE: return Success(LHS <= RHS, E);
4740 case BO_GE: return Success(LHS >= RHS, E);
4741 case BO_EQ: return Success(LHS == RHS, E);
4742 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004743 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004744}
4745
Ken Dyck8b752f12010-01-27 17:10:57 +00004746CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004747 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4748 // the result is the size of the referenced type."
4749 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4750 // result shall be the alignment of the referenced type."
4751 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4752 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004753
4754 // __alignof is defined to return the preferred alignment.
4755 return Info.Ctx.toCharUnitsFromBits(
4756 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004757}
4758
Ken Dyck8b752f12010-01-27 17:10:57 +00004759CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004760 E = E->IgnoreParens();
4761
4762 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004763 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004764 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004765 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4766 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004767
Chris Lattneraf707ab2009-01-24 21:53:27 +00004768 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004769 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4770 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004771
Chris Lattnere9feb472009-01-24 21:09:06 +00004772 return GetAlignOfType(E->getType());
4773}
4774
4775
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004776/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4777/// a result as the expression's type.
4778bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4779 const UnaryExprOrTypeTraitExpr *E) {
4780 switch(E->getKind()) {
4781 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004782 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004783 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004784 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004785 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004786 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004787
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004788 case UETT_VecStep: {
4789 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004790
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004791 if (Ty->isVectorType()) {
4792 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004793
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004794 // The vec_step built-in functions that take a 3-component
4795 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4796 if (n == 3)
4797 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004798
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004799 return Success(n, E);
4800 } else
4801 return Success(1, E);
4802 }
4803
4804 case UETT_SizeOf: {
4805 QualType SrcTy = E->getTypeOfArgument();
4806 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4807 // the result is the size of the referenced type."
4808 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4809 // result shall be the alignment of the referenced type."
4810 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4811 SrcTy = Ref->getPointeeType();
4812
Richard Smith180f4792011-11-10 06:34:14 +00004813 CharUnits Sizeof;
4814 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004815 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004816 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004817 }
4818 }
4819
4820 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004821}
4822
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004823bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004824 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004825 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004826 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004827 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004828 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004829 for (unsigned i = 0; i != n; ++i) {
4830 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4831 switch (ON.getKind()) {
4832 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004833 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004834 APSInt IdxResult;
4835 if (!EvaluateInteger(Idx, IdxResult, Info))
4836 return false;
4837 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4838 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004839 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004840 CurrentType = AT->getElementType();
4841 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4842 Result += IdxResult.getSExtValue() * ElementSize;
4843 break;
4844 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004845
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004846 case OffsetOfExpr::OffsetOfNode::Field: {
4847 FieldDecl *MemberDecl = ON.getField();
4848 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004849 if (!RT)
4850 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004851 RecordDecl *RD = RT->getDecl();
4852 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004853 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004854 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004855 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004856 CurrentType = MemberDecl->getType().getNonReferenceType();
4857 break;
4858 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004859
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004860 case OffsetOfExpr::OffsetOfNode::Identifier:
4861 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004862
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004863 case OffsetOfExpr::OffsetOfNode::Base: {
4864 CXXBaseSpecifier *BaseSpec = ON.getBase();
4865 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004866 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004867
4868 // Find the layout of the class whose base we are looking into.
4869 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004870 if (!RT)
4871 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004872 RecordDecl *RD = RT->getDecl();
4873 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4874
4875 // Find the base class itself.
4876 CurrentType = BaseSpec->getType();
4877 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4878 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004879 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004880
4881 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004882 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004883 break;
4884 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004885 }
4886 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004887 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004888}
4889
Chris Lattnerb542afe2008-07-11 19:10:17 +00004890bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004891 switch (E->getOpcode()) {
4892 default:
4893 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4894 // See C99 6.6p3.
4895 return Error(E);
4896 case UO_Extension:
4897 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4898 // If so, we could clear the diagnostic ID.
4899 return Visit(E->getSubExpr());
4900 case UO_Plus:
4901 // The result is just the value.
4902 return Visit(E->getSubExpr());
4903 case UO_Minus: {
4904 if (!Visit(E->getSubExpr()))
4905 return false;
4906 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004907 const APSInt &Value = Result.getInt();
4908 if (Value.isSigned() && Value.isMinSignedValue())
4909 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4910 E->getType());
4911 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004912 }
4913 case UO_Not: {
4914 if (!Visit(E->getSubExpr()))
4915 return false;
4916 if (!Result.isInt()) return Error(E);
4917 return Success(~Result.getInt(), E);
4918 }
4919 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004920 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004921 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004922 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004923 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004924 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004925 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004926}
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Chris Lattner732b2232008-07-12 01:15:53 +00004928/// HandleCast - This is used to evaluate implicit or explicit casts where the
4929/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004930bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4931 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004932 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004933 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004934
Eli Friedman46a52322011-03-25 00:43:55 +00004935 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004936 case CK_BaseToDerived:
4937 case CK_DerivedToBase:
4938 case CK_UncheckedDerivedToBase:
4939 case CK_Dynamic:
4940 case CK_ToUnion:
4941 case CK_ArrayToPointerDecay:
4942 case CK_FunctionToPointerDecay:
4943 case CK_NullToPointer:
4944 case CK_NullToMemberPointer:
4945 case CK_BaseToDerivedMemberPointer:
4946 case CK_DerivedToBaseMemberPointer:
4947 case CK_ConstructorConversion:
4948 case CK_IntegralToPointer:
4949 case CK_ToVoid:
4950 case CK_VectorSplat:
4951 case CK_IntegralToFloating:
4952 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004953 case CK_CPointerToObjCPointerCast:
4954 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004955 case CK_AnyPointerToBlockPointerCast:
4956 case CK_ObjCObjectLValueCast:
4957 case CK_FloatingRealToComplex:
4958 case CK_FloatingComplexToReal:
4959 case CK_FloatingComplexCast:
4960 case CK_FloatingComplexToIntegralComplex:
4961 case CK_IntegralRealToComplex:
4962 case CK_IntegralComplexCast:
4963 case CK_IntegralComplexToFloatingComplex:
4964 llvm_unreachable("invalid cast kind for integral value");
4965
Eli Friedmane50c2972011-03-25 19:07:11 +00004966 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004967 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004968 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004969 case CK_ARCProduceObject:
4970 case CK_ARCConsumeObject:
4971 case CK_ARCReclaimReturnedObject:
4972 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004973 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004974
Richard Smith7d580a42012-01-17 21:17:26 +00004975 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004976 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004977 case CK_AtomicToNonAtomic:
4978 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004979 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004980 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004981
4982 case CK_MemberPointerToBoolean:
4983 case CK_PointerToBoolean:
4984 case CK_IntegralToBoolean:
4985 case CK_FloatingToBoolean:
4986 case CK_FloatingComplexToBoolean:
4987 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004988 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004989 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004990 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004991 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004992 }
4993
Eli Friedman46a52322011-03-25 00:43:55 +00004994 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004995 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004996 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004997
Eli Friedmanbe265702009-02-20 01:15:07 +00004998 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004999 // Allow casts of address-of-label differences if they are no-ops
5000 // or narrowing. (The narrowing case isn't actually guaranteed to
5001 // be constant-evaluatable except in some narrow cases which are hard
5002 // to detect here. We let it through on the assumption the user knows
5003 // what they are doing.)
5004 if (Result.isAddrLabelDiff())
5005 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005006 // Only allow casts of lvalues if they are lossless.
5007 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5008 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005009
Richard Smithf72fccf2012-01-30 22:27:01 +00005010 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5011 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005012 }
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Eli Friedman46a52322011-03-25 00:43:55 +00005014 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005015 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5016
John McCallefdb83e2010-05-07 21:00:08 +00005017 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005018 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005019 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005020
Daniel Dunbardd211642009-02-19 22:24:01 +00005021 if (LV.getLValueBase()) {
5022 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005023 // FIXME: Allow a larger integer size than the pointer size, and allow
5024 // narrowing back down to pointer width in subsequent integral casts.
5025 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005026 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005027 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005028
Richard Smithb755a9d2011-11-16 07:18:12 +00005029 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005030 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005031 return true;
5032 }
5033
Ken Dycka7305832010-01-15 12:37:54 +00005034 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5035 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005036 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005037 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005038
Eli Friedman46a52322011-03-25 00:43:55 +00005039 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005040 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005041 if (!EvaluateComplex(SubExpr, C, Info))
5042 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005043 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005044 }
Eli Friedman2217c872009-02-22 11:46:18 +00005045
Eli Friedman46a52322011-03-25 00:43:55 +00005046 case CK_FloatingToIntegral: {
5047 APFloat F(0.0);
5048 if (!EvaluateFloat(SubExpr, F, Info))
5049 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005050
Richard Smithc1c5f272011-12-13 06:39:58 +00005051 APSInt Value;
5052 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5053 return false;
5054 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005055 }
5056 }
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Eli Friedman46a52322011-03-25 00:43:55 +00005058 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005059}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005060
Eli Friedman722c7172009-02-28 03:59:05 +00005061bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5062 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005063 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005064 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5065 return false;
5066 if (!LV.isComplexInt())
5067 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005068 return Success(LV.getComplexIntReal(), E);
5069 }
5070
5071 return Visit(E->getSubExpr());
5072}
5073
Eli Friedman664a1042009-02-27 04:45:43 +00005074bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005075 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005076 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005077 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5078 return false;
5079 if (!LV.isComplexInt())
5080 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005081 return Success(LV.getComplexIntImag(), E);
5082 }
5083
Richard Smith8327fad2011-10-24 18:44:57 +00005084 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005085 return Success(0, E);
5086}
5087
Douglas Gregoree8aff02011-01-04 17:33:58 +00005088bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5089 return Success(E->getPackLength(), E);
5090}
5091
Sebastian Redl295995c2010-09-10 20:55:47 +00005092bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5093 return Success(E->getValue(), E);
5094}
5095
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005096//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005097// Float Evaluation
5098//===----------------------------------------------------------------------===//
5099
5100namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005101class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005102 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005103 APFloat &Result;
5104public:
5105 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005106 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005107
Richard Smith47a1eed2011-10-29 20:57:55 +00005108 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005109 Result = V.getFloat();
5110 return true;
5111 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005112
Richard Smith51201882011-12-30 21:15:51 +00005113 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005114 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5115 return true;
5116 }
5117
Chris Lattner019f4e82008-10-06 05:28:25 +00005118 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005119
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005120 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005121 bool VisitBinaryOperator(const BinaryOperator *E);
5122 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005123 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005124
John McCallabd3a852010-05-07 22:08:54 +00005125 bool VisitUnaryReal(const UnaryOperator *E);
5126 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005127
Richard Smith51201882011-12-30 21:15:51 +00005128 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005129};
5130} // end anonymous namespace
5131
5132static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005133 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005134 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005135}
5136
Jay Foad4ba2a172011-01-12 09:06:06 +00005137static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005138 QualType ResultTy,
5139 const Expr *Arg,
5140 bool SNaN,
5141 llvm::APFloat &Result) {
5142 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5143 if (!S) return false;
5144
5145 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5146
5147 llvm::APInt fill;
5148
5149 // Treat empty strings as if they were zero.
5150 if (S->getString().empty())
5151 fill = llvm::APInt(32, 0);
5152 else if (S->getString().getAsInteger(0, fill))
5153 return false;
5154
5155 if (SNaN)
5156 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5157 else
5158 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5159 return true;
5160}
5161
Chris Lattner019f4e82008-10-06 05:28:25 +00005162bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005163 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005164 default:
5165 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5166
Chris Lattner019f4e82008-10-06 05:28:25 +00005167 case Builtin::BI__builtin_huge_val:
5168 case Builtin::BI__builtin_huge_valf:
5169 case Builtin::BI__builtin_huge_vall:
5170 case Builtin::BI__builtin_inf:
5171 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005172 case Builtin::BI__builtin_infl: {
5173 const llvm::fltSemantics &Sem =
5174 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005175 Result = llvm::APFloat::getInf(Sem);
5176 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005177 }
Mike Stump1eb44332009-09-09 15:08:12 +00005178
John McCalldb7b72a2010-02-28 13:00:19 +00005179 case Builtin::BI__builtin_nans:
5180 case Builtin::BI__builtin_nansf:
5181 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005182 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5183 true, Result))
5184 return Error(E);
5185 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005186
Chris Lattner9e621712008-10-06 06:31:58 +00005187 case Builtin::BI__builtin_nan:
5188 case Builtin::BI__builtin_nanf:
5189 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005190 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005191 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005192 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5193 false, Result))
5194 return Error(E);
5195 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005196
5197 case Builtin::BI__builtin_fabs:
5198 case Builtin::BI__builtin_fabsf:
5199 case Builtin::BI__builtin_fabsl:
5200 if (!EvaluateFloat(E->getArg(0), Result, Info))
5201 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005202
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005203 if (Result.isNegative())
5204 Result.changeSign();
5205 return true;
5206
Mike Stump1eb44332009-09-09 15:08:12 +00005207 case Builtin::BI__builtin_copysign:
5208 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005209 case Builtin::BI__builtin_copysignl: {
5210 APFloat RHS(0.);
5211 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5212 !EvaluateFloat(E->getArg(1), RHS, Info))
5213 return false;
5214 Result.copySign(RHS);
5215 return true;
5216 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005217 }
5218}
5219
John McCallabd3a852010-05-07 22:08:54 +00005220bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005221 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5222 ComplexValue CV;
5223 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5224 return false;
5225 Result = CV.FloatReal;
5226 return true;
5227 }
5228
5229 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005230}
5231
5232bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005233 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5234 ComplexValue CV;
5235 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5236 return false;
5237 Result = CV.FloatImag;
5238 return true;
5239 }
5240
Richard Smith8327fad2011-10-24 18:44:57 +00005241 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005242 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5243 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005244 return true;
5245}
5246
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005247bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005248 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005249 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005250 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005251 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005252 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005253 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5254 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005255 Result.changeSign();
5256 return true;
5257 }
5258}
Chris Lattner019f4e82008-10-06 05:28:25 +00005259
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005260bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005261 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5262 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005263
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005264 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005265 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5266 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005267 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005268 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005269 return false;
5270
5271 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005272 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005273 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005274 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005275 break;
John McCall2de56d12010-08-25 11:45:40 +00005276 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005277 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005278 break;
John McCall2de56d12010-08-25 11:45:40 +00005279 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005280 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005281 break;
John McCall2de56d12010-08-25 11:45:40 +00005282 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005283 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005284 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005285 }
Richard Smith7b48a292012-02-01 05:53:12 +00005286
5287 if (Result.isInfinity() || Result.isNaN())
5288 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5289 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005290}
5291
5292bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5293 Result = E->getValue();
5294 return true;
5295}
5296
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005297bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5298 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Eli Friedman2a523ee2011-03-25 00:54:52 +00005300 switch (E->getCastKind()) {
5301 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005302 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005303
5304 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005305 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005306 return EvaluateInteger(SubExpr, IntResult, Info) &&
5307 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5308 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005309 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005310
5311 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005312 if (!Visit(SubExpr))
5313 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005314 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5315 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005316 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005317
Eli Friedman2a523ee2011-03-25 00:54:52 +00005318 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005319 ComplexValue V;
5320 if (!EvaluateComplex(SubExpr, V, Info))
5321 return false;
5322 Result = V.getComplexFloatReal();
5323 return true;
5324 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005325 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005326}
5327
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005328//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005329// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005330//===----------------------------------------------------------------------===//
5331
5332namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005333class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005334 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005335 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005336
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005337public:
John McCallf4cf1a12010-05-07 17:22:02 +00005338 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005339 : ExprEvaluatorBaseTy(info), Result(Result) {}
5340
Richard Smith47a1eed2011-10-29 20:57:55 +00005341 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005342 Result.setFrom(V);
5343 return true;
5344 }
Mike Stump1eb44332009-09-09 15:08:12 +00005345
Eli Friedman7ead5c72012-01-10 04:58:17 +00005346 bool ZeroInitialization(const Expr *E);
5347
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005348 //===--------------------------------------------------------------------===//
5349 // Visitor Methods
5350 //===--------------------------------------------------------------------===//
5351
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005352 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005353 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005354 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005355 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005356 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005357};
5358} // end anonymous namespace
5359
John McCallf4cf1a12010-05-07 17:22:02 +00005360static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5361 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005362 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005363 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005364}
5365
Eli Friedman7ead5c72012-01-10 04:58:17 +00005366bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005367 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005368 if (ElemTy->isRealFloatingType()) {
5369 Result.makeComplexFloat();
5370 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5371 Result.FloatReal = Zero;
5372 Result.FloatImag = Zero;
5373 } else {
5374 Result.makeComplexInt();
5375 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5376 Result.IntReal = Zero;
5377 Result.IntImag = Zero;
5378 }
5379 return true;
5380}
5381
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005382bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5383 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005384
5385 if (SubExpr->getType()->isRealFloatingType()) {
5386 Result.makeComplexFloat();
5387 APFloat &Imag = Result.FloatImag;
5388 if (!EvaluateFloat(SubExpr, Imag, Info))
5389 return false;
5390
5391 Result.FloatReal = APFloat(Imag.getSemantics());
5392 return true;
5393 } else {
5394 assert(SubExpr->getType()->isIntegerType() &&
5395 "Unexpected imaginary literal.");
5396
5397 Result.makeComplexInt();
5398 APSInt &Imag = Result.IntImag;
5399 if (!EvaluateInteger(SubExpr, Imag, Info))
5400 return false;
5401
5402 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5403 return true;
5404 }
5405}
5406
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005407bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005408
John McCall8786da72010-12-14 17:51:41 +00005409 switch (E->getCastKind()) {
5410 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005411 case CK_BaseToDerived:
5412 case CK_DerivedToBase:
5413 case CK_UncheckedDerivedToBase:
5414 case CK_Dynamic:
5415 case CK_ToUnion:
5416 case CK_ArrayToPointerDecay:
5417 case CK_FunctionToPointerDecay:
5418 case CK_NullToPointer:
5419 case CK_NullToMemberPointer:
5420 case CK_BaseToDerivedMemberPointer:
5421 case CK_DerivedToBaseMemberPointer:
5422 case CK_MemberPointerToBoolean:
5423 case CK_ConstructorConversion:
5424 case CK_IntegralToPointer:
5425 case CK_PointerToIntegral:
5426 case CK_PointerToBoolean:
5427 case CK_ToVoid:
5428 case CK_VectorSplat:
5429 case CK_IntegralCast:
5430 case CK_IntegralToBoolean:
5431 case CK_IntegralToFloating:
5432 case CK_FloatingToIntegral:
5433 case CK_FloatingToBoolean:
5434 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005435 case CK_CPointerToObjCPointerCast:
5436 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005437 case CK_AnyPointerToBlockPointerCast:
5438 case CK_ObjCObjectLValueCast:
5439 case CK_FloatingComplexToReal:
5440 case CK_FloatingComplexToBoolean:
5441 case CK_IntegralComplexToReal:
5442 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005443 case CK_ARCProduceObject:
5444 case CK_ARCConsumeObject:
5445 case CK_ARCReclaimReturnedObject:
5446 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005447 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005448
John McCall8786da72010-12-14 17:51:41 +00005449 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005450 case CK_AtomicToNonAtomic:
5451 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005452 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005453 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005454
5455 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005456 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005457 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005458 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005459
5460 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005461 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005462 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005463 return false;
5464
John McCall8786da72010-12-14 17:51:41 +00005465 Result.makeComplexFloat();
5466 Result.FloatImag = APFloat(Real.getSemantics());
5467 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005468 }
5469
John McCall8786da72010-12-14 17:51:41 +00005470 case CK_FloatingComplexCast: {
5471 if (!Visit(E->getSubExpr()))
5472 return false;
5473
5474 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5475 QualType From
5476 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5477
Richard Smithc1c5f272011-12-13 06:39:58 +00005478 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5479 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005480 }
5481
5482 case CK_FloatingComplexToIntegralComplex: {
5483 if (!Visit(E->getSubExpr()))
5484 return false;
5485
5486 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5487 QualType From
5488 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5489 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005490 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5491 To, Result.IntReal) &&
5492 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5493 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005494 }
5495
5496 case CK_IntegralRealToComplex: {
5497 APSInt &Real = Result.IntReal;
5498 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5499 return false;
5500
5501 Result.makeComplexInt();
5502 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5503 return true;
5504 }
5505
5506 case CK_IntegralComplexCast: {
5507 if (!Visit(E->getSubExpr()))
5508 return false;
5509
5510 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5511 QualType From
5512 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5513
Richard Smithf72fccf2012-01-30 22:27:01 +00005514 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5515 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005516 return true;
5517 }
5518
5519 case CK_IntegralComplexToFloatingComplex: {
5520 if (!Visit(E->getSubExpr()))
5521 return false;
5522
5523 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5524 QualType From
5525 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5526 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005527 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5528 To, Result.FloatReal) &&
5529 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5530 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005531 }
5532 }
5533
5534 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005535}
5536
John McCallf4cf1a12010-05-07 17:22:02 +00005537bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005538 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005539 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5540
Richard Smith745f5142012-01-27 01:14:48 +00005541 bool LHSOK = Visit(E->getLHS());
5542 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005543 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005544
John McCallf4cf1a12010-05-07 17:22:02 +00005545 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005546 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005547 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005548
Daniel Dunbar3f279872009-01-29 01:32:56 +00005549 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5550 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005551 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005552 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005553 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005554 if (Result.isComplexFloat()) {
5555 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5556 APFloat::rmNearestTiesToEven);
5557 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5558 APFloat::rmNearestTiesToEven);
5559 } else {
5560 Result.getComplexIntReal() += RHS.getComplexIntReal();
5561 Result.getComplexIntImag() += RHS.getComplexIntImag();
5562 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005563 break;
John McCall2de56d12010-08-25 11:45:40 +00005564 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005565 if (Result.isComplexFloat()) {
5566 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5567 APFloat::rmNearestTiesToEven);
5568 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5569 APFloat::rmNearestTiesToEven);
5570 } else {
5571 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5572 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5573 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005574 break;
John McCall2de56d12010-08-25 11:45:40 +00005575 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005576 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005577 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005578 APFloat &LHS_r = LHS.getComplexFloatReal();
5579 APFloat &LHS_i = LHS.getComplexFloatImag();
5580 APFloat &RHS_r = RHS.getComplexFloatReal();
5581 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Daniel Dunbar3f279872009-01-29 01:32:56 +00005583 APFloat Tmp = LHS_r;
5584 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5585 Result.getComplexFloatReal() = Tmp;
5586 Tmp = LHS_i;
5587 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5588 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5589
5590 Tmp = LHS_r;
5591 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5592 Result.getComplexFloatImag() = Tmp;
5593 Tmp = LHS_i;
5594 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5595 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5596 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005597 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005598 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005599 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5600 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005601 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005602 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5603 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5604 }
5605 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005606 case BO_Div:
5607 if (Result.isComplexFloat()) {
5608 ComplexValue LHS = Result;
5609 APFloat &LHS_r = LHS.getComplexFloatReal();
5610 APFloat &LHS_i = LHS.getComplexFloatImag();
5611 APFloat &RHS_r = RHS.getComplexFloatReal();
5612 APFloat &RHS_i = RHS.getComplexFloatImag();
5613 APFloat &Res_r = Result.getComplexFloatReal();
5614 APFloat &Res_i = Result.getComplexFloatImag();
5615
5616 APFloat Den = RHS_r;
5617 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5618 APFloat Tmp = RHS_i;
5619 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5620 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5621
5622 Res_r = LHS_r;
5623 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5624 Tmp = LHS_i;
5625 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5626 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5627 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5628
5629 Res_i = LHS_i;
5630 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5631 Tmp = LHS_r;
5632 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5633 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5634 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5635 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005636 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5637 return Error(E, diag::note_expr_divide_by_zero);
5638
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005639 ComplexValue LHS = Result;
5640 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5641 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5642 Result.getComplexIntReal() =
5643 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5644 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5645 Result.getComplexIntImag() =
5646 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5647 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5648 }
5649 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005650 }
5651
John McCallf4cf1a12010-05-07 17:22:02 +00005652 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005653}
5654
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005655bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5656 // Get the operand value into 'Result'.
5657 if (!Visit(E->getSubExpr()))
5658 return false;
5659
5660 switch (E->getOpcode()) {
5661 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005662 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005663 case UO_Extension:
5664 return true;
5665 case UO_Plus:
5666 // The result is always just the subexpr.
5667 return true;
5668 case UO_Minus:
5669 if (Result.isComplexFloat()) {
5670 Result.getComplexFloatReal().changeSign();
5671 Result.getComplexFloatImag().changeSign();
5672 }
5673 else {
5674 Result.getComplexIntReal() = -Result.getComplexIntReal();
5675 Result.getComplexIntImag() = -Result.getComplexIntImag();
5676 }
5677 return true;
5678 case UO_Not:
5679 if (Result.isComplexFloat())
5680 Result.getComplexFloatImag().changeSign();
5681 else
5682 Result.getComplexIntImag() = -Result.getComplexIntImag();
5683 return true;
5684 }
5685}
5686
Eli Friedman7ead5c72012-01-10 04:58:17 +00005687bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5688 if (E->getNumInits() == 2) {
5689 if (E->getType()->isComplexType()) {
5690 Result.makeComplexFloat();
5691 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5692 return false;
5693 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5694 return false;
5695 } else {
5696 Result.makeComplexInt();
5697 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5698 return false;
5699 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5700 return false;
5701 }
5702 return true;
5703 }
5704 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5705}
5706
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005707//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005708// Void expression evaluation, primarily for a cast to void on the LHS of a
5709// comma operator
5710//===----------------------------------------------------------------------===//
5711
5712namespace {
5713class VoidExprEvaluator
5714 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5715public:
5716 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5717
5718 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005719
5720 bool VisitCastExpr(const CastExpr *E) {
5721 switch (E->getCastKind()) {
5722 default:
5723 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5724 case CK_ToVoid:
5725 VisitIgnoredValue(E->getSubExpr());
5726 return true;
5727 }
5728 }
5729};
5730} // end anonymous namespace
5731
5732static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5733 assert(E->isRValue() && E->getType()->isVoidType());
5734 return VoidExprEvaluator(Info).Visit(E);
5735}
5736
5737//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005738// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005739//===----------------------------------------------------------------------===//
5740
Richard Smith47a1eed2011-10-29 20:57:55 +00005741static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005742 // In C, function designators are not lvalues, but we evaluate them as if they
5743 // are.
5744 if (E->isGLValue() || E->getType()->isFunctionType()) {
5745 LValue LV;
5746 if (!EvaluateLValue(E, LV, Info))
5747 return false;
5748 LV.moveInto(Result);
5749 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005750 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005751 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005752 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005753 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005754 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005755 } else if (E->getType()->hasPointerRepresentation()) {
5756 LValue LV;
5757 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005758 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005759 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005760 } else if (E->getType()->isRealFloatingType()) {
5761 llvm::APFloat F(0.0);
5762 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005763 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005764 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005765 } else if (E->getType()->isAnyComplexType()) {
5766 ComplexValue C;
5767 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005768 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005769 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005770 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005771 MemberPtr P;
5772 if (!EvaluateMemberPointer(E, P, Info))
5773 return false;
5774 P.moveInto(Result);
5775 return true;
Richard Smith51201882011-12-30 21:15:51 +00005776 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005777 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005778 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005779 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005780 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005781 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005782 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005783 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005784 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005785 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5786 return false;
5787 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005788 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005789 if (Info.getLangOpts().CPlusPlus0x)
5790 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5791 << E->getType();
5792 else
5793 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005794 if (!EvaluateVoid(E, Info))
5795 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005796 } else if (Info.getLangOpts().CPlusPlus0x) {
5797 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5798 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005799 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005800 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005801 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005802 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005803
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005804 return true;
5805}
5806
Richard Smith69c2c502011-11-04 05:33:44 +00005807/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5808/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5809/// since later initializers for an object can indirectly refer to subobjects
5810/// which were initialized earlier.
5811static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005812 const LValue &This, const Expr *E,
5813 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005814 if (!CheckLiteralType(Info, E))
5815 return false;
5816
5817 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005818 // Evaluate arrays and record types in-place, so that later initializers can
5819 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005820 if (E->getType()->isArrayType())
5821 return EvaluateArray(E, This, Result, Info);
5822 else if (E->getType()->isRecordType())
5823 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005824 }
5825
5826 // For any other type, in-place evaluation is unimportant.
5827 CCValue CoreConstResult;
5828 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005829 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005830}
5831
Richard Smithf48fdb02011-12-09 22:58:01 +00005832/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5833/// lvalue-to-rvalue cast if it is an lvalue.
5834static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005835 if (!CheckLiteralType(Info, E))
5836 return false;
5837
Richard Smithf48fdb02011-12-09 22:58:01 +00005838 CCValue Value;
5839 if (!::Evaluate(Value, Info, E))
5840 return false;
5841
5842 if (E->isGLValue()) {
5843 LValue LV;
5844 LV.setFrom(Value);
5845 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5846 return false;
5847 }
5848
5849 // Check this core constant expression is a constant expression, and if so,
5850 // convert it to one.
5851 return CheckConstantExpression(Info, E, Value, Result);
5852}
Richard Smithc49bd112011-10-28 17:51:58 +00005853
Richard Smith51f47082011-10-29 00:50:52 +00005854/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005855/// any crazy technique (that has nothing to do with language standards) that
5856/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005857/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5858/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005859bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005860 // Fast-path evaluations of integer literals, since we sometimes see files
5861 // containing vast quantities of these.
5862 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5863 Result.Val = APValue(APSInt(L->getValue(),
5864 L->getType()->isUnsignedIntegerType()));
5865 return true;
5866 }
5867
Richard Smith2d6a5672012-01-14 04:30:29 +00005868 // FIXME: Evaluating values of large array and record types can cause
5869 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005870 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5871 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005872 return false;
5873
Richard Smithf48fdb02011-12-09 22:58:01 +00005874 EvalInfo Info(Ctx, Result);
5875 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005876}
5877
Jay Foad4ba2a172011-01-12 09:06:06 +00005878bool Expr::EvaluateAsBooleanCondition(bool &Result,
5879 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005880 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005881 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005882 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5883 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005884 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005885}
5886
Richard Smith80d4b552011-12-28 19:48:30 +00005887bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5888 SideEffectsKind AllowSideEffects) const {
5889 if (!getType()->isIntegralOrEnumerationType())
5890 return false;
5891
Richard Smithc49bd112011-10-28 17:51:58 +00005892 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005893 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5894 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005895 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005896
Richard Smithc49bd112011-10-28 17:51:58 +00005897 Result = ExprResult.Val.getInt();
5898 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005899}
5900
Jay Foad4ba2a172011-01-12 09:06:06 +00005901bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005902 EvalInfo Info(Ctx, Result);
5903
John McCallefdb83e2010-05-07 21:00:08 +00005904 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005905 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005906 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5907 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005908}
5909
Richard Smith099e7f62011-12-19 06:19:21 +00005910bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5911 const VarDecl *VD,
5912 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005913 // FIXME: Evaluating initializers for large array and record types can cause
5914 // performance problems. Only do so in C++11 for now.
5915 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5916 !Ctx.getLangOptions().CPlusPlus0x)
5917 return false;
5918
Richard Smith099e7f62011-12-19 06:19:21 +00005919 Expr::EvalStatus EStatus;
5920 EStatus.Diag = &Notes;
5921
5922 EvalInfo InitInfo(Ctx, EStatus);
5923 InitInfo.setEvaluatingDecl(VD, Value);
5924
Richard Smith51201882011-12-30 21:15:51 +00005925 if (!CheckLiteralType(InitInfo, this))
5926 return false;
5927
Richard Smith099e7f62011-12-19 06:19:21 +00005928 LValue LVal;
5929 LVal.set(VD);
5930
Richard Smith51201882011-12-30 21:15:51 +00005931 // C++11 [basic.start.init]p2:
5932 // Variables with static storage duration or thread storage duration shall be
5933 // zero-initialized before any other initialization takes place.
5934 // This behavior is not present in C.
5935 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5936 !VD->getType()->isReferenceType()) {
5937 ImplicitValueInitExpr VIE(VD->getType());
5938 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5939 return false;
5940 }
5941
Richard Smith099e7f62011-12-19 06:19:21 +00005942 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5943 !EStatus.HasSideEffects;
5944}
5945
Richard Smith51f47082011-10-29 00:50:52 +00005946/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5947/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005948bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005949 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005950 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005951}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005952
Jay Foad4ba2a172011-01-12 09:06:06 +00005953bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005954 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005955}
5956
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005957APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005958 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005959 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005960 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005961 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005962 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005963
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005964 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005965}
John McCalld905f5a2010-05-07 05:32:02 +00005966
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005967 bool Expr::EvalResult::isGlobalLValue() const {
5968 assert(Val.isLValue());
5969 return IsGlobalLValue(Val.getLValueBase());
5970 }
5971
5972
John McCalld905f5a2010-05-07 05:32:02 +00005973/// isIntegerConstantExpr - this recursive routine will test if an expression is
5974/// an integer constant expression.
5975
5976/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5977/// comma, etc
5978///
5979/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5980/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5981/// cast+dereference.
5982
5983// CheckICE - This function does the fundamental ICE checking: the returned
5984// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5985// Note that to reduce code duplication, this helper does no evaluation
5986// itself; the caller checks whether the expression is evaluatable, and
5987// in the rare cases where CheckICE actually cares about the evaluated
5988// value, it calls into Evalute.
5989//
5990// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005991// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005992// 1: This expression is not an ICE, but if it isn't evaluated, it's
5993// a legal subexpression for an ICE. This return value is used to handle
5994// the comma operator in C99 mode.
5995// 2: This expression is not an ICE, and is not a legal subexpression for one.
5996
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005997namespace {
5998
John McCalld905f5a2010-05-07 05:32:02 +00005999struct ICEDiag {
6000 unsigned Val;
6001 SourceLocation Loc;
6002
6003 public:
6004 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6005 ICEDiag() : Val(0) {}
6006};
6007
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006008}
6009
6010static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006011
6012static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6013 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006014 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006015 !EVResult.Val.isInt()) {
6016 return ICEDiag(2, E->getLocStart());
6017 }
6018 return NoDiag();
6019}
6020
6021static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6022 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006023 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006024 return ICEDiag(2, E->getLocStart());
6025 }
6026
6027 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006028#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006029#define STMT(Node, Base) case Expr::Node##Class:
6030#define EXPR(Node, Base)
6031#include "clang/AST/StmtNodes.inc"
6032 case Expr::PredefinedExprClass:
6033 case Expr::FloatingLiteralClass:
6034 case Expr::ImaginaryLiteralClass:
6035 case Expr::StringLiteralClass:
6036 case Expr::ArraySubscriptExprClass:
6037 case Expr::MemberExprClass:
6038 case Expr::CompoundAssignOperatorClass:
6039 case Expr::CompoundLiteralExprClass:
6040 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006041 case Expr::DesignatedInitExprClass:
6042 case Expr::ImplicitValueInitExprClass:
6043 case Expr::ParenListExprClass:
6044 case Expr::VAArgExprClass:
6045 case Expr::AddrLabelExprClass:
6046 case Expr::StmtExprClass:
6047 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006048 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006049 case Expr::CXXDynamicCastExprClass:
6050 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006051 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006052 case Expr::CXXNullPtrLiteralExprClass:
6053 case Expr::CXXThisExprClass:
6054 case Expr::CXXThrowExprClass:
6055 case Expr::CXXNewExprClass:
6056 case Expr::CXXDeleteExprClass:
6057 case Expr::CXXPseudoDestructorExprClass:
6058 case Expr::UnresolvedLookupExprClass:
6059 case Expr::DependentScopeDeclRefExprClass:
6060 case Expr::CXXConstructExprClass:
6061 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006062 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006063 case Expr::CXXTemporaryObjectExprClass:
6064 case Expr::CXXUnresolvedConstructExprClass:
6065 case Expr::CXXDependentScopeMemberExprClass:
6066 case Expr::UnresolvedMemberExprClass:
6067 case Expr::ObjCStringLiteralClass:
6068 case Expr::ObjCEncodeExprClass:
6069 case Expr::ObjCMessageExprClass:
6070 case Expr::ObjCSelectorExprClass:
6071 case Expr::ObjCProtocolExprClass:
6072 case Expr::ObjCIvarRefExprClass:
6073 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006074 case Expr::ObjCIsaExprClass:
6075 case Expr::ShuffleVectorExprClass:
6076 case Expr::BlockExprClass:
6077 case Expr::BlockDeclRefExprClass:
6078 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006079 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006080 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006081 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006082 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006083 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006084 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006085 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006086 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006087 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006088 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006089 return ICEDiag(2, E->getLocStart());
6090
Douglas Gregoree8aff02011-01-04 17:33:58 +00006091 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006092 case Expr::GNUNullExprClass:
6093 // GCC considers the GNU __null value to be an integral constant expression.
6094 return NoDiag();
6095
John McCall91a57552011-07-15 05:09:51 +00006096 case Expr::SubstNonTypeTemplateParmExprClass:
6097 return
6098 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6099
John McCalld905f5a2010-05-07 05:32:02 +00006100 case Expr::ParenExprClass:
6101 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006102 case Expr::GenericSelectionExprClass:
6103 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006104 case Expr::IntegerLiteralClass:
6105 case Expr::CharacterLiteralClass:
6106 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006107 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006108 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006109 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006110 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006111 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006112 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006113 return NoDiag();
6114 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006115 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006116 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6117 // constant expressions, but they can never be ICEs because an ICE cannot
6118 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006119 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006120 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006121 return CheckEvalInICE(E, Ctx);
6122 return ICEDiag(2, E->getLocStart());
6123 }
6124 case Expr::DeclRefExprClass:
6125 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6126 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006127 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006128 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6129
6130 // Parameter variables are never constants. Without this check,
6131 // getAnyInitializer() can find a default argument, which leads
6132 // to chaos.
6133 if (isa<ParmVarDecl>(D))
6134 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6135
6136 // C++ 7.1.5.1p2
6137 // A variable of non-volatile const-qualified integral or enumeration
6138 // type initialized by an ICE can be used in ICEs.
6139 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006140 if (!Dcl->getType()->isIntegralOrEnumerationType())
6141 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6142
Richard Smith099e7f62011-12-19 06:19:21 +00006143 const VarDecl *VD;
6144 // Look for a declaration of this variable that has an initializer, and
6145 // check whether it is an ICE.
6146 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6147 return NoDiag();
6148 else
6149 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006150 }
6151 }
6152 return ICEDiag(2, E->getLocStart());
6153 case Expr::UnaryOperatorClass: {
6154 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6155 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006156 case UO_PostInc:
6157 case UO_PostDec:
6158 case UO_PreInc:
6159 case UO_PreDec:
6160 case UO_AddrOf:
6161 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006162 // C99 6.6/3 allows increment and decrement within unevaluated
6163 // subexpressions of constant expressions, but they can never be ICEs
6164 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006165 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006166 case UO_Extension:
6167 case UO_LNot:
6168 case UO_Plus:
6169 case UO_Minus:
6170 case UO_Not:
6171 case UO_Real:
6172 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006173 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006174 }
6175
6176 // OffsetOf falls through here.
6177 }
6178 case Expr::OffsetOfExprClass: {
6179 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006180 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006181 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006182 // compliance: we should warn earlier for offsetof expressions with
6183 // array subscripts that aren't ICEs, and if the array subscripts
6184 // are ICEs, the value of the offsetof must be an integer constant.
6185 return CheckEvalInICE(E, Ctx);
6186 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006187 case Expr::UnaryExprOrTypeTraitExprClass: {
6188 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6189 if ((Exp->getKind() == UETT_SizeOf) &&
6190 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006191 return ICEDiag(2, E->getLocStart());
6192 return NoDiag();
6193 }
6194 case Expr::BinaryOperatorClass: {
6195 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6196 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006197 case BO_PtrMemD:
6198 case BO_PtrMemI:
6199 case BO_Assign:
6200 case BO_MulAssign:
6201 case BO_DivAssign:
6202 case BO_RemAssign:
6203 case BO_AddAssign:
6204 case BO_SubAssign:
6205 case BO_ShlAssign:
6206 case BO_ShrAssign:
6207 case BO_AndAssign:
6208 case BO_XorAssign:
6209 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006210 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6211 // constant expressions, but they can never be ICEs because an ICE cannot
6212 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006213 return ICEDiag(2, E->getLocStart());
6214
John McCall2de56d12010-08-25 11:45:40 +00006215 case BO_Mul:
6216 case BO_Div:
6217 case BO_Rem:
6218 case BO_Add:
6219 case BO_Sub:
6220 case BO_Shl:
6221 case BO_Shr:
6222 case BO_LT:
6223 case BO_GT:
6224 case BO_LE:
6225 case BO_GE:
6226 case BO_EQ:
6227 case BO_NE:
6228 case BO_And:
6229 case BO_Xor:
6230 case BO_Or:
6231 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006232 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6233 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006234 if (Exp->getOpcode() == BO_Div ||
6235 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006236 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006237 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006238 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006239 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006240 if (REval == 0)
6241 return ICEDiag(1, E->getLocStart());
6242 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006243 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006244 if (LEval.isMinSignedValue())
6245 return ICEDiag(1, E->getLocStart());
6246 }
6247 }
6248 }
John McCall2de56d12010-08-25 11:45:40 +00006249 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006250 if (Ctx.getLangOptions().C99) {
6251 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6252 // if it isn't evaluated.
6253 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6254 return ICEDiag(1, E->getLocStart());
6255 } else {
6256 // In both C89 and C++, commas in ICEs are illegal.
6257 return ICEDiag(2, E->getLocStart());
6258 }
6259 }
6260 if (LHSResult.Val >= RHSResult.Val)
6261 return LHSResult;
6262 return RHSResult;
6263 }
John McCall2de56d12010-08-25 11:45:40 +00006264 case BO_LAnd:
6265 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006266 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6267 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6268 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6269 // Rare case where the RHS has a comma "side-effect"; we need
6270 // to actually check the condition to see whether the side
6271 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006272 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006273 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006274 return RHSResult;
6275 return NoDiag();
6276 }
6277
6278 if (LHSResult.Val >= RHSResult.Val)
6279 return LHSResult;
6280 return RHSResult;
6281 }
6282 }
6283 }
6284 case Expr::ImplicitCastExprClass:
6285 case Expr::CStyleCastExprClass:
6286 case Expr::CXXFunctionalCastExprClass:
6287 case Expr::CXXStaticCastExprClass:
6288 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006289 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006290 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006291 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006292 if (isa<ExplicitCastExpr>(E)) {
6293 if (const FloatingLiteral *FL
6294 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6295 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6296 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6297 APSInt IgnoredVal(DestWidth, !DestSigned);
6298 bool Ignored;
6299 // If the value does not fit in the destination type, the behavior is
6300 // undefined, so we are not required to treat it as a constant
6301 // expression.
6302 if (FL->getValue().convertToInteger(IgnoredVal,
6303 llvm::APFloat::rmTowardZero,
6304 &Ignored) & APFloat::opInvalidOp)
6305 return ICEDiag(2, E->getLocStart());
6306 return NoDiag();
6307 }
6308 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006309 switch (cast<CastExpr>(E)->getCastKind()) {
6310 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006311 case CK_AtomicToNonAtomic:
6312 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006313 case CK_NoOp:
6314 case CK_IntegralToBoolean:
6315 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006316 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006317 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006318 return ICEDiag(2, E->getLocStart());
6319 }
John McCalld905f5a2010-05-07 05:32:02 +00006320 }
John McCall56ca35d2011-02-17 10:25:35 +00006321 case Expr::BinaryConditionalOperatorClass: {
6322 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6323 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6324 if (CommonResult.Val == 2) return CommonResult;
6325 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6326 if (FalseResult.Val == 2) return FalseResult;
6327 if (CommonResult.Val == 1) return CommonResult;
6328 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006329 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006330 return FalseResult;
6331 }
John McCalld905f5a2010-05-07 05:32:02 +00006332 case Expr::ConditionalOperatorClass: {
6333 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6334 // If the condition (ignoring parens) is a __builtin_constant_p call,
6335 // then only the true side is actually considered in an integer constant
6336 // expression, and it is fully evaluated. This is an important GNU
6337 // extension. See GCC PR38377 for discussion.
6338 if (const CallExpr *CallCE
6339 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006340 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6341 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006342 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006343 if (CondResult.Val == 2)
6344 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006345
Richard Smithf48fdb02011-12-09 22:58:01 +00006346 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6347 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006348
John McCalld905f5a2010-05-07 05:32:02 +00006349 if (TrueResult.Val == 2)
6350 return TrueResult;
6351 if (FalseResult.Val == 2)
6352 return FalseResult;
6353 if (CondResult.Val == 1)
6354 return CondResult;
6355 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6356 return NoDiag();
6357 // Rare case where the diagnostics depend on which side is evaluated
6358 // Note that if we get here, CondResult is 0, and at least one of
6359 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006360 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006361 return FalseResult;
6362 }
6363 return TrueResult;
6364 }
6365 case Expr::CXXDefaultArgExprClass:
6366 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6367 case Expr::ChooseExprClass: {
6368 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6369 }
6370 }
6371
David Blaikie30263482012-01-20 21:50:17 +00006372 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006373}
6374
Richard Smithf48fdb02011-12-09 22:58:01 +00006375/// Evaluate an expression as a C++11 integral constant expression.
6376static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6377 const Expr *E,
6378 llvm::APSInt *Value,
6379 SourceLocation *Loc) {
6380 if (!E->getType()->isIntegralOrEnumerationType()) {
6381 if (Loc) *Loc = E->getExprLoc();
6382 return false;
6383 }
6384
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006385 APValue Result;
6386 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006387 return false;
6388
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006389 assert(Result.isInt() && "pointer cast to int is not an ICE");
6390 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006391 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006392}
6393
Richard Smithdd1f29b2011-12-12 09:28:41 +00006394bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006395 if (Ctx.getLangOptions().CPlusPlus0x)
6396 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6397
John McCalld905f5a2010-05-07 05:32:02 +00006398 ICEDiag d = CheckICE(this, Ctx);
6399 if (d.Val != 0) {
6400 if (Loc) *Loc = d.Loc;
6401 return false;
6402 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006403 return true;
6404}
6405
6406bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6407 SourceLocation *Loc, bool isEvaluated) const {
6408 if (Ctx.getLangOptions().CPlusPlus0x)
6409 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6410
6411 if (!isIntegerConstantExpr(Ctx, Loc))
6412 return false;
6413 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006414 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006415 return true;
6416}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006417
6418bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6419 SourceLocation *Loc) const {
6420 // We support this checking in C++98 mode in order to diagnose compatibility
6421 // issues.
6422 assert(Ctx.getLangOptions().CPlusPlus);
6423
6424 Expr::EvalStatus Status;
6425 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6426 Status.Diag = &Diags;
6427 EvalInfo Info(Ctx, Status);
6428
6429 APValue Scratch;
6430 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6431
6432 if (!Diags.empty()) {
6433 IsConstExpr = false;
6434 if (Loc) *Loc = Diags[0].first;
6435 } else if (!IsConstExpr) {
6436 // FIXME: This shouldn't happen.
6437 if (Loc) *Loc = getExprLoc();
6438 }
6439
6440 return IsConstExpr;
6441}
Richard Smith745f5142012-01-27 01:14:48 +00006442
6443bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6444 llvm::SmallVectorImpl<
6445 PartialDiagnosticAt> &Diags) {
6446 // FIXME: It would be useful to check constexpr function templates, but at the
6447 // moment the constant expression evaluator cannot cope with the non-rigorous
6448 // ASTs which we build for dependent expressions.
6449 if (FD->isDependentContext())
6450 return true;
6451
6452 Expr::EvalStatus Status;
6453 Status.Diag = &Diags;
6454
6455 EvalInfo Info(FD->getASTContext(), Status);
6456 Info.CheckingPotentialConstantExpression = true;
6457
6458 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6459 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6460
6461 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6462 // is a temporary being used as the 'this' pointer.
6463 LValue This;
6464 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6465 This.set(&VIE, Info.CurrentCall);
6466
6467 APValue Scratch;
6468 ArrayRef<const Expr*> Args;
6469
6470 SourceLocation Loc = FD->getLocation();
6471
6472 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6473 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6474 } else
6475 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6476 Args, FD->getBody(), Info, Scratch);
6477
6478 return Diags.empty();
6479}