blob: 6a292c392510210ac7161a688716946b0bfce02a [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//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smithb4e85ed2012-01-06 16:39:00 +000079 /// Find the path length and type of the most-derived subobject in the given
80 /// path, and find the size of the containing array, if any.
81 static
82 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
83 ArrayRef<APValue::LValuePathEntry> Path,
84 uint64_t &ArraySize, QualType &Type) {
85 unsigned MostDerivedLength = 0;
86 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +000087 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +000088 if (Type->isArrayType()) {
89 const ConstantArrayType *CAT =
90 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
91 Type = CAT->getElementType();
92 ArraySize = CAT->getSize().getZExtValue();
93 MostDerivedLength = I + 1;
94 } else if (const FieldDecl *FD = getAsField(Path[I])) {
95 Type = FD->getType();
96 ArraySize = 0;
97 MostDerivedLength = I + 1;
98 } else {
Richard Smith9a17a682011-11-07 05:07:52 +000099 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000100 ArraySize = 0;
101 }
Richard Smith9a17a682011-11-07 05:07:52 +0000102 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000104 }
105
Richard Smithb4e85ed2012-01-06 16:39:00 +0000106 // The order of this enum is important for diagnostics.
107 enum CheckSubobjectKind {
108 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
109 };
110
Richard Smith0a3bdb62011-11-04 02:25:55 +0000111 /// A path from a glvalue to a subobject of that glvalue.
112 struct SubobjectDesignator {
113 /// True if the subobject was named in a manner not supported by C++11. Such
114 /// lvalues can still be folded, but they are not core constant expressions
115 /// and we cannot perform lvalue-to-rvalue conversions on them.
116 bool Invalid : 1;
117
Richard Smithb4e85ed2012-01-06 16:39:00 +0000118 /// Is this a pointer one past the end of an object?
119 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000120
Richard Smithb4e85ed2012-01-06 16:39:00 +0000121 /// The length of the path to the most-derived object of which this is a
122 /// subobject.
123 unsigned MostDerivedPathLength : 30;
124
125 /// The size of the array of which the most-derived object is an element, or
126 /// 0 if the most-derived object is not an array element.
127 uint64_t MostDerivedArraySize;
128
129 /// The type of the most derived object referred to by this address.
130 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131
Richard Smith9a17a682011-11-07 05:07:52 +0000132 typedef APValue::LValuePathEntry PathEntry;
133
Richard Smith0a3bdb62011-11-04 02:25:55 +0000134 /// The entries on the path from the glvalue to the designated subobject.
135 SmallVector<PathEntry, 8> Entries;
136
Richard Smithb4e85ed2012-01-06 16:39:00 +0000137 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 explicit SubobjectDesignator(QualType T)
140 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
141 MostDerivedArraySize(0), MostDerivedType(T) {}
142
143 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
144 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
145 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000146 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000147 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000148 ArrayRef<PathEntry> VEntries = V.getLValuePath();
149 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
150 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000151 MostDerivedPathLength =
152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
153 V.getLValuePath(), MostDerivedArraySize,
154 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000155 }
156 }
157
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158 void setInvalid() {
159 Invalid = true;
160 Entries.clear();
161 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162
163 /// Determine whether this is a one-past-the-end pointer.
164 bool isOnePastTheEnd() const {
165 if (IsOnePastTheEnd)
166 return true;
167 if (MostDerivedArraySize &&
168 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
169 return true;
170 return false;
171 }
172
173 /// Check that this refers to a valid subobject.
174 bool isValidSubobject() const {
175 if (Invalid)
176 return false;
177 return !isOnePastTheEnd();
178 }
179 /// Check that this refers to a valid subobject, and if not, produce a
180 /// relevant diagnostic and set the designator as invalid.
181 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
182
183 /// Update this designator to refer to the first element within this array.
184 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000185 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000186 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000187 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000188
189 // This is a most-derived object.
190 MostDerivedType = CAT->getElementType();
191 MostDerivedArraySize = CAT->getSize().getZExtValue();
192 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000193 }
194 /// Update this designator to refer to the given base or member of this
195 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000196 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000197 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000198 APValue::BaseOrMemberType Value(D, Virtual);
199 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000201
202 // If this isn't a base class, it's a new most-derived object.
203 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
204 MostDerivedType = FD->getType();
205 MostDerivedArraySize = 0;
206 MostDerivedPathLength = Entries.size();
207 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000210 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000214 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000215 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
217 setInvalid();
218 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 return;
220 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221 // [expr.add]p4: For the purposes of these operators, a pointer to a
222 // nonarray object behaves the same as a pointer to the first element of
223 // an array of length one with the type of the object as its element type.
224 if (IsOnePastTheEnd && N == (uint64_t)-1)
225 IsOnePastTheEnd = false;
226 else if (!IsOnePastTheEnd && N == 1)
227 IsOnePastTheEnd = true;
228 else if (N != 0) {
229 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000230 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 }
233 };
234
Richard Smith47a1eed2011-10-29 20:57:55 +0000235 /// A core constant value. This can be the value of any constant expression,
236 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000237 ///
238 /// For an LValue, the base and offset are stored in the APValue subobject,
239 /// but the other information is stored in the SubobjectDesignator. For all
240 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000241 class CCValue : public APValue {
242 typedef llvm::APSInt APSInt;
243 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000244 /// If the value is a reference or pointer into a parameter or temporary,
245 /// this is the corresponding call stack frame.
246 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000247 /// If the value is a reference or pointer, this is a description of how the
248 /// subobject was specified.
249 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000250 public:
Richard Smith177dce72011-11-01 16:57:24 +0000251 struct GlobalValue {};
252
Richard Smith47a1eed2011-10-29 20:57:55 +0000253 CCValue() {}
254 explicit CCValue(const APSInt &I) : APValue(I) {}
255 explicit CCValue(const APFloat &F) : APValue(F) {}
256 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
257 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
258 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000261 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
264 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000265 CCValue(const ValueDecl *D, bool IsDerivedMember,
266 ArrayRef<const CXXRecordDecl*> Path) :
267 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
269 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000270
Richard Smith177dce72011-11-01 16:57:24 +0000271 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000273 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000274 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000275 SubobjectDesignator &getLValueDesignator() {
276 assert(getKind() == LValue);
277 return Designator;
278 }
279 const SubobjectDesignator &getLValueDesignator() const {
280 return const_cast<CCValue*>(this)->getLValueDesignator();
281 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000282 };
283
Richard Smithd0dccea2011-10-28 22:34:42 +0000284 /// A stack frame in the constexpr call stack.
285 struct CallStackFrame {
286 EvalInfo &Info;
287
288 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000289 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Richard Smith08d6e032011-12-16 19:06:07 +0000291 /// CallLoc - The location of the call expression for this call.
292 SourceLocation CallLoc;
293
294 /// Callee - The function which was called.
295 const FunctionDecl *Callee;
296
Richard Smith180f4792011-11-10 06:34:14 +0000297 /// This - The binding for the this pointer in this call, if any.
298 const LValue *This;
299
Richard Smithd0dccea2011-10-28 22:34:42 +0000300 /// ParmBindings - Parameter bindings for this function call, indexed by
301 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000302 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000303
Richard Smithbd552ef2011-10-31 05:52:43 +0000304 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
305 typedef MapTy::const_iterator temp_iterator;
306 /// Temporaries - Temporary lvalues materialized within this stack frame.
307 MapTy Temporaries;
308
Richard Smith08d6e032011-12-16 19:06:07 +0000309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
310 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000311 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000312 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000313 };
314
Richard Smithdd1f29b2011-12-12 09:28:41 +0000315 /// A partial diagnostic which we might know in advance that we are not going
316 /// to emit.
317 class OptionalDiagnostic {
318 PartialDiagnostic *Diag;
319
320 public:
321 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
322
323 template<typename T>
324 OptionalDiagnostic &operator<<(const T &v) {
325 if (Diag)
326 *Diag << v;
327 return *this;
328 }
329 };
330
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000332 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000333
334 /// EvalStatus - Contains information about the evaluation.
335 Expr::EvalStatus &EvalStatus;
336
337 /// CurrentCall - The top of the constexpr call stack.
338 CallStackFrame *CurrentCall;
339
Richard Smithbd552ef2011-10-31 05:52:43 +0000340 /// CallStackDepth - The number of calls in the call stack right now.
341 unsigned CallStackDepth;
342
343 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
344 /// OpaqueValues - Values used as the common expression in a
345 /// BinaryConditionalOperator.
346 MapTy OpaqueValues;
347
348 /// BottomFrame - The frame in which evaluation started. This must be
349 /// initialized last.
350 CallStackFrame BottomFrame;
351
Richard Smith180f4792011-11-10 06:34:14 +0000352 /// EvaluatingDecl - This is the declaration whose initializer is being
353 /// evaluated, if any.
354 const VarDecl *EvaluatingDecl;
355
356 /// EvaluatingDeclValue - This is the value being constructed for the
357 /// declaration whose initializer is being evaluated, if any.
358 APValue *EvaluatingDeclValue;
359
Richard Smithc1c5f272011-12-13 06:39:58 +0000360 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
361 /// notes attached to it will also be stored, otherwise they will not be.
362 bool HasActiveDiagnostic;
363
Richard Smithbd552ef2011-10-31 05:52:43 +0000364
365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000369
Richard Smithbd552ef2011-10-31 05:52:43 +0000370 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
371 MapTy::const_iterator i = OpaqueValues.find(e);
372 if (i == OpaqueValues.end()) return 0;
373 return &i->second;
374 }
375
Richard Smith180f4792011-11-10 06:34:14 +0000376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
377 EvaluatingDecl = VD;
378 EvaluatingDeclValue = &Value;
379 }
380
Richard Smithc18c4232011-11-21 19:36:32 +0000381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
382
Richard Smithc1c5f272011-12-13 06:39:58 +0000383 bool CheckCallLimit(SourceLocation Loc) {
384 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
385 return true;
386 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
387 << getLangOpts().ConstexprCallDepth;
388 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000389 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000390
Richard Smithc1c5f272011-12-13 06:39:58 +0000391 private:
392 /// Add a diagnostic to the diagnostics list.
393 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
394 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
395 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
396 return EvalStatus.Diag->back().second;
397 }
398
Richard Smith08d6e032011-12-16 19:06:07 +0000399 /// Add notes containing a call stack to the current point of evaluation.
400 void addCallStack(unsigned Limit);
401
Richard Smithc1c5f272011-12-13 06:39:58 +0000402 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000403 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
405 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000406 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000407 // If we have a prior diagnostic, it will be noting that the expression
408 // isn't a constant expression. This diagnostic is more important.
409 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000410 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000411 unsigned CallStackNotes = CallStackDepth - 1;
412 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
413 if (Limit)
414 CallStackNotes = std::min(CallStackNotes, Limit + 1);
415
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000417 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000418 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
419 addDiag(Loc, DiagId);
420 addCallStack(Limit);
421 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000422 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000423 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000424 return OptionalDiagnostic();
425 }
426
427 /// Diagnose that the evaluation does not produce a C++11 core constant
428 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
430 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000431 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000432 // Don't override a previous diagnostic.
433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
434 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000435 return Diag(Loc, DiagId, ExtraNotes);
436 }
437
438 /// Add a note to a prior diagnostic.
439 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
440 if (!HasActiveDiagnostic)
441 return OptionalDiagnostic();
442 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000443 }
Richard Smith099e7f62011-12-19 06:19:21 +0000444
445 /// Add a stack of notes to a prior diagnostic.
446 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
447 if (HasActiveDiagnostic) {
448 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
449 Diags.begin(), Diags.end());
450 }
451 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000452 };
Richard Smith08d6e032011-12-16 19:06:07 +0000453}
Richard Smithbd552ef2011-10-31 05:52:43 +0000454
Richard Smithb4e85ed2012-01-06 16:39:00 +0000455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
456 CheckSubobjectKind CSK) {
457 if (Invalid)
458 return false;
459 if (isOnePastTheEnd()) {
460 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
461 << CSK;
462 setInvalid();
463 return false;
464 }
465 return true;
466}
467
468void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
469 const Expr *E, uint64_t N) {
470 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
471 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
472 << static_cast<int>(N) << /*array*/ 0
473 << static_cast<unsigned>(MostDerivedArraySize);
474 else
475 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
476 << static_cast<int>(N) << /*non-array*/ 1;
477 setInvalid();
478}
479
Richard Smith08d6e032011-12-16 19:06:07 +0000480CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
481 const FunctionDecl *Callee, const LValue *This,
482 const CCValue *Arguments)
483 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
484 This(This), Arguments(Arguments) {
485 Info.CurrentCall = this;
486 ++Info.CallStackDepth;
487}
488
489CallStackFrame::~CallStackFrame() {
490 assert(Info.CurrentCall == this && "calls retired out of order");
491 --Info.CallStackDepth;
492 Info.CurrentCall = Caller;
493}
494
495/// Produce a string describing the given constexpr call.
496static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
497 unsigned ArgIndex = 0;
498 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
499 !isa<CXXConstructorDecl>(Frame->Callee);
500
501 if (!IsMemberCall)
502 Out << *Frame->Callee << '(';
503
504 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
505 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
506 if (ArgIndex > IsMemberCall)
507 Out << ", ";
508
509 const ParmVarDecl *Param = *I;
510 const CCValue &Arg = Frame->Arguments[ArgIndex];
511 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
512 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
513 else {
514 // Deliberately slice off the frame to form an APValue we can print.
515 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
516 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000517 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000518 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
519 }
520
521 if (ArgIndex == 0 && IsMemberCall)
522 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000523 }
524
Richard Smith08d6e032011-12-16 19:06:07 +0000525 Out << ')';
526}
527
528void EvalInfo::addCallStack(unsigned Limit) {
529 // Determine which calls to skip, if any.
530 unsigned ActiveCalls = CallStackDepth - 1;
531 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
532 if (Limit && Limit < ActiveCalls) {
533 SkipStart = Limit / 2 + Limit % 2;
534 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000535 }
536
Richard Smith08d6e032011-12-16 19:06:07 +0000537 // Walk the call stack and add the diagnostics.
538 unsigned CallIdx = 0;
539 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
540 Frame = Frame->Caller, ++CallIdx) {
541 // Skip this call?
542 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
543 if (CallIdx == SkipStart) {
544 // Note that we're skipping calls.
545 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
546 << unsigned(ActiveCalls - Limit);
547 }
548 continue;
549 }
550
551 llvm::SmallVector<char, 128> Buffer;
552 llvm::raw_svector_ostream Out(Buffer);
553 describeCall(Frame, Out);
554 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
555 }
556}
557
558namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000559 struct ComplexValue {
560 private:
561 bool IsInt;
562
563 public:
564 APSInt IntReal, IntImag;
565 APFloat FloatReal, FloatImag;
566
567 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
568
569 void makeComplexFloat() { IsInt = false; }
570 bool isComplexFloat() const { return !IsInt; }
571 APFloat &getComplexFloatReal() { return FloatReal; }
572 APFloat &getComplexFloatImag() { return FloatImag; }
573
574 void makeComplexInt() { IsInt = true; }
575 bool isComplexInt() const { return IsInt; }
576 APSInt &getComplexIntReal() { return IntReal; }
577 APSInt &getComplexIntImag() { return IntImag; }
578
Richard Smith47a1eed2011-10-29 20:57:55 +0000579 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000580 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000581 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000582 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000583 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000584 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000585 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000586 assert(v.isComplexFloat() || v.isComplexInt());
587 if (v.isComplexFloat()) {
588 makeComplexFloat();
589 FloatReal = v.getComplexFloatReal();
590 FloatImag = v.getComplexFloatImag();
591 } else {
592 makeComplexInt();
593 IntReal = v.getComplexIntReal();
594 IntImag = v.getComplexIntImag();
595 }
596 }
John McCallf4cf1a12010-05-07 17:22:02 +0000597 };
John McCallefdb83e2010-05-07 21:00:08 +0000598
599 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000600 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000601 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000602 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000603 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000604
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000605 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000606 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000607 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000608 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000609 SubobjectDesignator &getLValueDesignator() { return Designator; }
610 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000611
Richard Smith47a1eed2011-10-29 20:57:55 +0000612 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000613 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000614 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000615 void setFrom(const CCValue &V) {
616 assert(V.isLValue());
617 Base = V.getLValueBase();
618 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000619 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000620 Designator = V.getLValueDesignator();
621 }
622
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000623 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
624 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000625 Offset = CharUnits::Zero();
626 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000627 Designator = SubobjectDesignator(getType(B));
628 }
629
630 // Check that this LValue is not based on a null pointer. If it is, produce
631 // a diagnostic and mark the designator as invalid.
632 bool checkNullPointer(EvalInfo &Info, const Expr *E,
633 CheckSubobjectKind CSK) {
634 if (Designator.Invalid)
635 return false;
636 if (!Base) {
637 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
638 << CSK;
639 Designator.setInvalid();
640 return false;
641 }
642 return true;
643 }
644
645 // Check this LValue refers to an object. If not, set the designator to be
646 // invalid and emit a diagnostic.
647 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
648 return checkNullPointer(Info, E, CSK) &&
649 Designator.checkSubobject(Info, E, CSK);
650 }
651
652 void addDecl(EvalInfo &Info, const Expr *E,
653 const Decl *D, bool Virtual = false) {
654 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
655 Designator.addDeclUnchecked(D, Virtual);
656 }
657 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
658 checkSubobject(Info, E, CSK_ArrayToPointer);
659 Designator.addArrayUnchecked(CAT);
660 }
661 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
662 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
663 return;
664 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000665 }
John McCallefdb83e2010-05-07 21:00:08 +0000666 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000667
668 struct MemberPtr {
669 MemberPtr() {}
670 explicit MemberPtr(const ValueDecl *Decl) :
671 DeclAndIsDerivedMember(Decl, false), Path() {}
672
673 /// The member or (direct or indirect) field referred to by this member
674 /// pointer, or 0 if this is a null member pointer.
675 const ValueDecl *getDecl() const {
676 return DeclAndIsDerivedMember.getPointer();
677 }
678 /// Is this actually a member of some type derived from the relevant class?
679 bool isDerivedMember() const {
680 return DeclAndIsDerivedMember.getInt();
681 }
682 /// Get the class which the declaration actually lives in.
683 const CXXRecordDecl *getContainingRecord() const {
684 return cast<CXXRecordDecl>(
685 DeclAndIsDerivedMember.getPointer()->getDeclContext());
686 }
687
688 void moveInto(CCValue &V) const {
689 V = CCValue(getDecl(), isDerivedMember(), Path);
690 }
691 void setFrom(const CCValue &V) {
692 assert(V.isMemberPointer());
693 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
694 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
695 Path.clear();
696 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
697 Path.insert(Path.end(), P.begin(), P.end());
698 }
699
700 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
701 /// whether the member is a member of some class derived from the class type
702 /// of the member pointer.
703 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
704 /// Path - The path of base/derived classes from the member declaration's
705 /// class (exclusive) to the class type of the member pointer (inclusive).
706 SmallVector<const CXXRecordDecl*, 4> Path;
707
708 /// Perform a cast towards the class of the Decl (either up or down the
709 /// hierarchy).
710 bool castBack(const CXXRecordDecl *Class) {
711 assert(!Path.empty());
712 const CXXRecordDecl *Expected;
713 if (Path.size() >= 2)
714 Expected = Path[Path.size() - 2];
715 else
716 Expected = getContainingRecord();
717 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
718 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
719 // if B does not contain the original member and is not a base or
720 // derived class of the class containing the original member, the result
721 // of the cast is undefined.
722 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
723 // (D::*). We consider that to be a language defect.
724 return false;
725 }
726 Path.pop_back();
727 return true;
728 }
729 /// Perform a base-to-derived member pointer cast.
730 bool castToDerived(const CXXRecordDecl *Derived) {
731 if (!getDecl())
732 return true;
733 if (!isDerivedMember()) {
734 Path.push_back(Derived);
735 return true;
736 }
737 if (!castBack(Derived))
738 return false;
739 if (Path.empty())
740 DeclAndIsDerivedMember.setInt(false);
741 return true;
742 }
743 /// Perform a derived-to-base member pointer cast.
744 bool castToBase(const CXXRecordDecl *Base) {
745 if (!getDecl())
746 return true;
747 if (Path.empty())
748 DeclAndIsDerivedMember.setInt(true);
749 if (isDerivedMember()) {
750 Path.push_back(Base);
751 return true;
752 }
753 return castBack(Base);
754 }
755 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000756
757 /// Kinds of constant expression checking, for diagnostics.
758 enum CheckConstantExpressionKind {
759 CCEK_Constant, ///< A normal constant.
760 CCEK_ReturnValue, ///< A constexpr function return value.
761 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
762 };
John McCallf4cf1a12010-05-07 17:22:02 +0000763}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000764
Richard Smith47a1eed2011-10-29 20:57:55 +0000765static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000766static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000767 const LValue &This, const Expr *E,
768 CheckConstantExpressionKind CCEK
769 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000770static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
771static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000772static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
773 EvalInfo &Info);
774static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000776static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000777 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000778static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000779static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000780
781//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000782// Misc utilities
783//===----------------------------------------------------------------------===//
784
Richard Smith180f4792011-11-10 06:34:14 +0000785/// Should this call expression be treated as a string literal?
786static bool IsStringLiteralCall(const CallExpr *E) {
787 unsigned Builtin = E->isBuiltinCall();
788 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
789 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
790}
791
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000792static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000793 // C++11 [expr.const]p3 An address constant expression is a prvalue core
794 // constant expression of pointer type that evaluates to...
795
796 // ... a null pointer value, or a prvalue core constant expression of type
797 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000798 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000799
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000800 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
801 // ... the address of an object with static storage duration,
802 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
803 return VD->hasGlobalStorage();
804 // ... the address of a function,
805 return isa<FunctionDecl>(D);
806 }
807
808 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000809 switch (E->getStmtClass()) {
810 default:
811 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000812 case Expr::CompoundLiteralExprClass:
813 return cast<CompoundLiteralExpr>(E)->isFileScope();
814 // A string literal has static storage duration.
815 case Expr::StringLiteralClass:
816 case Expr::PredefinedExprClass:
817 case Expr::ObjCStringLiteralClass:
818 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000819 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000820 return true;
821 case Expr::CallExprClass:
822 return IsStringLiteralCall(cast<CallExpr>(E));
823 // For GCC compatibility, &&label has static storage duration.
824 case Expr::AddrLabelExprClass:
825 return true;
826 // A Block literal expression may be used as the initialization value for
827 // Block variables at global or local static scope.
828 case Expr::BlockExprClass:
829 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
830 }
John McCall42c8f872010-05-10 23:27:23 +0000831}
832
Richard Smith9a17a682011-11-07 05:07:52 +0000833/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000834/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000835/// either LValue or CCValue. Return true if we can fold this expression,
836/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000837template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000838static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000839 const T &LVal, APValue &Value,
840 CheckConstantExpressionKind CCEK) {
841 APValue::LValueBase Base = LVal.getLValueBase();
842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
843
844 if (!IsGlobalLValue(Base)) {
845 if (Info.getLangOpts().CPlusPlus0x) {
846 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
847 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
848 << E->isGLValue() << !Designator.Entries.empty()
849 << !!VD << CCEK << VD;
850 if (VD)
851 Info.Note(VD->getLocation(), diag::note_declared_at);
852 else
853 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
854 diag::note_constexpr_temporary_here);
855 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000856 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000857 }
Richard Smith61e61622012-01-12 06:08:57 +0000858 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000859 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000860 }
Richard Smith9a17a682011-11-07 05:07:52 +0000861
Richard Smithb4e85ed2012-01-06 16:39:00 +0000862 bool IsReferenceType = E->isGLValue();
863
864 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000865 // This is not a core constant expression. An appropriate diagnostic will
866 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000867 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
868 APValue::NoLValuePath());
869 return true;
870 }
871
Richard Smithb4e85ed2012-01-06 16:39:00 +0000872 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
873 Designator.Entries, Designator.IsOnePastTheEnd);
874
875 // Allow address constant expressions to be past-the-end pointers. This is
876 // an extension: the standard requires them to point to an object.
877 if (!IsReferenceType)
878 return true;
879
880 // A reference constant expression must refer to an object.
881 if (!Base) {
882 // FIXME: diagnostic
883 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000884 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000885 }
886
Richard Smithc1c5f272011-12-13 06:39:58 +0000887 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000888 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000889 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
890 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
891 << !Designator.Entries.empty() << !!VD << VD;
892 if (VD)
893 Info.Note(VD->getLocation(), diag::note_declared_at);
894 else
895 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
896 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000897 }
898
Richard Smith9a17a682011-11-07 05:07:52 +0000899 return true;
900}
901
Richard Smith51201882011-12-30 21:15:51 +0000902/// Check that this core constant expression is of literal type, and if not,
903/// produce an appropriate diagnostic.
904static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
905 if (!E->isRValue() || E->getType()->isLiteralType())
906 return true;
907
908 // Prvalue constant expressions must be of literal types.
909 if (Info.getLangOpts().CPlusPlus0x)
910 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
911 << E->getType();
912 else
913 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
914 return false;
915}
916
Richard Smith47a1eed2011-10-29 20:57:55 +0000917/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000918/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000919/// If not, report an appropriate diagnostic. Does not check that the expression
920/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000921static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000922 const CCValue &CCValue, APValue &Value,
923 CheckConstantExpressionKind CCEK
924 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000925 if (!CCValue.isLValue()) {
926 Value = CCValue;
927 return true;
928 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000929 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000930}
931
Richard Smith9e36b532011-10-31 05:11:32 +0000932const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000933 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000934}
935
936static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000937 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000938}
939
Richard Smith65ac5982011-11-01 21:06:14 +0000940static bool IsWeakLValue(const LValue &Value) {
941 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000942 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000943}
944
Richard Smithe24f5fc2011-11-17 22:56:20 +0000945static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000946 // A null base expression indicates a null pointer. These are always
947 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000948 if (!Value.getLValueBase()) {
949 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000950 return true;
951 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000952
Richard Smithe24f5fc2011-11-17 22:56:20 +0000953 // We have a non-null base. These are generally known to be true, but if it's
954 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000955 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000956 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000957 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000958}
959
Richard Smith47a1eed2011-10-29 20:57:55 +0000960static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000961 switch (Val.getKind()) {
962 case APValue::Uninitialized:
963 return false;
964 case APValue::Int:
965 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000966 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000967 case APValue::Float:
968 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000969 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000970 case APValue::ComplexInt:
971 Result = Val.getComplexIntReal().getBoolValue() ||
972 Val.getComplexIntImag().getBoolValue();
973 return true;
974 case APValue::ComplexFloat:
975 Result = !Val.getComplexFloatReal().isZero() ||
976 !Val.getComplexFloatImag().isZero();
977 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000978 case APValue::LValue:
979 return EvalPointerValueAsBool(Val, Result);
980 case APValue::MemberPointer:
981 Result = Val.getMemberPointerDecl();
982 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000983 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000984 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000985 case APValue::Struct:
986 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +0000987 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +0000988 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000989 }
990
Richard Smithc49bd112011-10-28 17:51:58 +0000991 llvm_unreachable("unknown APValue kind");
992}
993
994static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
995 EvalInfo &Info) {
996 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000997 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000998 if (!Evaluate(Val, Info, E))
999 return false;
1000 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001001}
1002
Richard Smithc1c5f272011-12-13 06:39:58 +00001003template<typename T>
1004static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1005 const T &SrcValue, QualType DestType) {
1006 llvm::SmallVector<char, 32> Buffer;
1007 SrcValue.toString(Buffer);
1008 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1009 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1010 return false;
1011}
1012
1013static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1014 QualType SrcType, const APFloat &Value,
1015 QualType DestType, APSInt &Result) {
1016 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001017 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001018 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Richard Smithc1c5f272011-12-13 06:39:58 +00001020 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001021 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001022 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1023 & APFloat::opInvalidOp)
1024 return HandleOverflow(Info, E, Value, DestType);
1025 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001026}
1027
Richard Smithc1c5f272011-12-13 06:39:58 +00001028static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1029 QualType SrcType, QualType DestType,
1030 APFloat &Result) {
1031 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001032 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001033 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1034 APFloat::rmNearestTiesToEven, &ignored)
1035 & APFloat::opOverflow)
1036 return HandleOverflow(Info, E, Value, DestType);
1037 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001038}
1039
Mike Stump1eb44332009-09-09 15:08:12 +00001040static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +00001041 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001042 unsigned DestWidth = Ctx.getIntWidth(DestType);
1043 APSInt Result = Value;
1044 // Figure out if this is a truncate, extend or noop cast.
1045 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001046 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001047 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001048 return Result;
1049}
1050
Richard Smithc1c5f272011-12-13 06:39:58 +00001051static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1052 QualType SrcType, const APSInt &Value,
1053 QualType DestType, APFloat &Result) {
1054 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1055 if (Result.convertFromAPInt(Value, Value.isSigned(),
1056 APFloat::rmNearestTiesToEven)
1057 & APFloat::opOverflow)
1058 return HandleOverflow(Info, E, Value, DestType);
1059 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001060}
1061
Eli Friedmane6a24e82011-12-22 03:51:45 +00001062static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1063 llvm::APInt &Res) {
1064 CCValue SVal;
1065 if (!Evaluate(SVal, Info, E))
1066 return false;
1067 if (SVal.isInt()) {
1068 Res = SVal.getInt();
1069 return true;
1070 }
1071 if (SVal.isFloat()) {
1072 Res = SVal.getFloat().bitcastToAPInt();
1073 return true;
1074 }
1075 if (SVal.isVector()) {
1076 QualType VecTy = E->getType();
1077 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1078 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1079 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1080 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1081 Res = llvm::APInt::getNullValue(VecSize);
1082 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1083 APValue &Elt = SVal.getVectorElt(i);
1084 llvm::APInt EltAsInt;
1085 if (Elt.isInt()) {
1086 EltAsInt = Elt.getInt();
1087 } else if (Elt.isFloat()) {
1088 EltAsInt = Elt.getFloat().bitcastToAPInt();
1089 } else {
1090 // Don't try to handle vectors of anything other than int or float
1091 // (not sure if it's possible to hit this case).
1092 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1093 return false;
1094 }
1095 unsigned BaseEltSize = EltAsInt.getBitWidth();
1096 if (BigEndian)
1097 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1098 else
1099 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1100 }
1101 return true;
1102 }
1103 // Give up if the input isn't an int, float, or vector. For example, we
1104 // reject "(v4i16)(intptr_t)&a".
1105 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1106 return false;
1107}
1108
Richard Smithb4e85ed2012-01-06 16:39:00 +00001109/// Cast an lvalue referring to a base subobject to a derived class, by
1110/// truncating the lvalue's path to the given length.
1111static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1112 const RecordDecl *TruncatedType,
1113 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001114 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001115
1116 // Check we actually point to a derived class object.
1117 if (TruncatedElements == D.Entries.size())
1118 return true;
1119 assert(TruncatedElements >= D.MostDerivedPathLength &&
1120 "not casting to a derived class");
1121 if (!Result.checkSubobject(Info, E, CSK_Derived))
1122 return false;
1123
1124 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001125 const RecordDecl *RD = TruncatedType;
1126 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001127 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1128 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001129 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001130 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001131 else
Richard Smith180f4792011-11-10 06:34:14 +00001132 Result.Offset -= Layout.getBaseClassOffset(Base);
1133 RD = Base;
1134 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001135 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001136 return true;
1137}
1138
Richard Smithb4e85ed2012-01-06 16:39:00 +00001139static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001140 const CXXRecordDecl *Derived,
1141 const CXXRecordDecl *Base,
1142 const ASTRecordLayout *RL = 0) {
1143 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1144 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001145 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001146}
1147
Richard Smithb4e85ed2012-01-06 16:39:00 +00001148static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001149 const CXXRecordDecl *DerivedDecl,
1150 const CXXBaseSpecifier *Base) {
1151 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1152
1153 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001154 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001155 return true;
1156 }
1157
Richard Smithb4e85ed2012-01-06 16:39:00 +00001158 SubobjectDesignator &D = Obj.Designator;
1159 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001160 return false;
1161
Richard Smithb4e85ed2012-01-06 16:39:00 +00001162 // Extract most-derived object and corresponding type.
1163 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1164 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1165 return false;
1166
1167 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001168 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1169 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001170 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001171 return true;
1172}
1173
1174/// Update LVal to refer to the given field, which must be a member of the type
1175/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001176static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001177 const FieldDecl *FD,
1178 const ASTRecordLayout *RL = 0) {
1179 if (!RL)
1180 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1181
1182 unsigned I = FD->getFieldIndex();
1183 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001184 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001185}
1186
Richard Smithd9b02e72012-01-25 22:15:11 +00001187/// Update LVal to refer to the given indirect field.
1188static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1189 LValue &LVal,
1190 const IndirectFieldDecl *IFD) {
1191 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1192 CE = IFD->chain_end(); C != CE; ++C)
1193 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1194}
1195
Richard Smith180f4792011-11-10 06:34:14 +00001196/// Get the size of the given type in char units.
1197static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1198 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1199 // extension.
1200 if (Type->isVoidType() || Type->isFunctionType()) {
1201 Size = CharUnits::One();
1202 return true;
1203 }
1204
1205 if (!Type->isConstantSizeType()) {
1206 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001207 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001208 return false;
1209 }
1210
1211 Size = Info.Ctx.getTypeSizeInChars(Type);
1212 return true;
1213}
1214
1215/// Update a pointer value to model pointer arithmetic.
1216/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001217/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001218/// \param LVal - The pointer value to be updated.
1219/// \param EltTy - The pointee type represented by LVal.
1220/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001221static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1222 LValue &LVal, QualType EltTy,
1223 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001224 CharUnits SizeOfPointee;
1225 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1226 return false;
1227
1228 // Compute the new offset in the appropriate width.
1229 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001230 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001231 return true;
1232}
1233
Richard Smith03f96112011-10-24 17:54:18 +00001234/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001235static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1236 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001237 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001238 // If this is a parameter to an active constexpr function call, perform
1239 // argument substitution.
1240 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001241 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001242 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001243 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001244 }
Richard Smith177dce72011-11-01 16:57:24 +00001245 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1246 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001247 }
Richard Smith03f96112011-10-24 17:54:18 +00001248
Richard Smith099e7f62011-12-19 06:19:21 +00001249 // Dig out the initializer, and use the declaration which it's attached to.
1250 const Expr *Init = VD->getAnyInitializer(VD);
1251 if (!Init || Init->isValueDependent()) {
1252 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1253 return false;
1254 }
1255
Richard Smith180f4792011-11-10 06:34:14 +00001256 // If we're currently evaluating the initializer of this declaration, use that
1257 // in-flight value.
1258 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001259 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1260 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001261 return !Result.isUninit();
1262 }
1263
Richard Smith65ac5982011-11-01 21:06:14 +00001264 // Never evaluate the initializer of a weak variable. We can't be sure that
1265 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001266 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001267 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001268 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001269 }
Richard Smith65ac5982011-11-01 21:06:14 +00001270
Richard Smith099e7f62011-12-19 06:19:21 +00001271 // Check that we can fold the initializer. In C++, we will have already done
1272 // this in the cases where it matters for conformance.
1273 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1274 if (!VD->evaluateValue(Notes)) {
1275 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1276 Notes.size() + 1) << VD;
1277 Info.Note(VD->getLocation(), diag::note_declared_at);
1278 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001279 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001280 } else if (!VD->checkInitIsICE()) {
1281 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1282 Notes.size() + 1) << VD;
1283 Info.Note(VD->getLocation(), diag::note_declared_at);
1284 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001285 }
Richard Smith03f96112011-10-24 17:54:18 +00001286
Richard Smithb4e85ed2012-01-06 16:39:00 +00001287 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001288 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001289}
1290
Richard Smithc49bd112011-10-28 17:51:58 +00001291static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001292 Qualifiers Quals = T.getQualifiers();
1293 return Quals.hasConst() && !Quals.hasVolatile();
1294}
1295
Richard Smith59efe262011-11-11 04:05:33 +00001296/// Get the base index of the given base class within an APValue representing
1297/// the given derived class.
1298static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1299 const CXXRecordDecl *Base) {
1300 Base = Base->getCanonicalDecl();
1301 unsigned Index = 0;
1302 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1303 E = Derived->bases_end(); I != E; ++I, ++Index) {
1304 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1305 return Index;
1306 }
1307
1308 llvm_unreachable("base class missing from derived class's bases list");
1309}
1310
Richard Smithcc5d4f62011-11-07 09:22:26 +00001311/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001312static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1313 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001314 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 if (Sub.Invalid)
1316 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001317 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001319 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001320 (unsigned)diag::note_constexpr_read_past_end :
1321 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001322 return false;
1323 }
Richard Smithf64699e2011-11-11 08:28:03 +00001324 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001325 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001326
1327 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1328 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001329 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001330 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001331 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001332 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001333 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001334 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001335 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001336 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001337 // Note, it should not be possible to form a pointer with a valid
1338 // designator which points more than one past the end of the array.
1339 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001340 (unsigned)diag::note_constexpr_read_past_end :
1341 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001342 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001343 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001344 if (O->getArrayInitializedElts() > Index)
1345 O = &O->getArrayInitializedElt(Index);
1346 else
1347 O = &O->getArrayFiller();
1348 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001349 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1350 // Next subobject is a class, struct or union field.
1351 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1352 if (RD->isUnion()) {
1353 const FieldDecl *UnionField = O->getUnionField();
1354 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001355 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001356 Info.Diag(E->getExprLoc(),
1357 diag::note_constexpr_read_inactive_union_member)
1358 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001359 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001360 }
Richard Smith180f4792011-11-10 06:34:14 +00001361 O = &O->getUnionValue();
1362 } else
1363 O = &O->getStructField(Field->getFieldIndex());
1364 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001365
1366 if (ObjType.isVolatileQualified()) {
1367 if (Info.getLangOpts().CPlusPlus) {
1368 // FIXME: Include a description of the path to the volatile subobject.
1369 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1370 << 2 << Field;
1371 Info.Note(Field->getLocation(), diag::note_declared_at);
1372 } else {
1373 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1374 }
1375 return false;
1376 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001377 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001378 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001379 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1380 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1381 O = &O->getStructBase(getBaseIndex(Derived, Base));
1382 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001383 }
Richard Smith180f4792011-11-10 06:34:14 +00001384
Richard Smithf48fdb02011-12-09 22:58:01 +00001385 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001386 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001387 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001388 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001389 }
1390
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001392 return true;
1393}
1394
Richard Smith180f4792011-11-10 06:34:14 +00001395/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1396/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1397/// for looking up the glvalue referred to by an entity of reference type.
1398///
1399/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001400/// \param Conv - The expression for which we are performing the conversion.
1401/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001402/// \param Type - The type we expect this conversion to produce.
1403/// \param LVal - The glvalue on which we are attempting to perform this action.
1404/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001405static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1406 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001407 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001408 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1409 if (!Info.getLangOpts().CPlusPlus)
1410 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1411
Richard Smithb4e85ed2012-01-06 16:39:00 +00001412 if (LVal.Designator.Invalid)
1413 // A diagnostic will have already been produced.
1414 return false;
1415
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001416 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001417 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001418 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001419
Richard Smithf48fdb02011-12-09 22:58:01 +00001420 if (!LVal.Base) {
1421 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001422 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1423 return false;
1424 }
1425
1426 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1427 // is not a constant expression (even if the object is non-volatile). We also
1428 // apply this rule to C++98, in order to conform to the expected 'volatile'
1429 // semantics.
1430 if (Type.isVolatileQualified()) {
1431 if (Info.getLangOpts().CPlusPlus)
1432 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1433 else
1434 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 }
Richard Smithc49bd112011-10-28 17:51:58 +00001437
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001438 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001439 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1440 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001441 // expressions are constant expressions too. Inside constexpr functions,
1442 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001443 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001444 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001445 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001446 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001447 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001448 }
1449
Richard Smith7098cbd2011-12-21 05:04:46 +00001450 // DR1313: If the object is volatile-qualified but the glvalue was not,
1451 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001452 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001453 if (VT.isVolatileQualified()) {
1454 if (Info.getLangOpts().CPlusPlus) {
1455 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1456 Info.Note(VD->getLocation(), diag::note_declared_at);
1457 } else {
1458 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001459 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001460 return false;
1461 }
1462
1463 if (!isa<ParmVarDecl>(VD)) {
1464 if (VD->isConstexpr()) {
1465 // OK, we can read this variable.
1466 } else if (VT->isIntegralOrEnumerationType()) {
1467 if (!VT.isConstQualified()) {
1468 if (Info.getLangOpts().CPlusPlus) {
1469 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1470 Info.Note(VD->getLocation(), diag::note_declared_at);
1471 } else {
1472 Info.Diag(Loc);
1473 }
1474 return false;
1475 }
1476 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1477 // We support folding of const floating-point types, in order to make
1478 // static const data members of such types (supported as an extension)
1479 // more useful.
1480 if (Info.getLangOpts().CPlusPlus0x) {
1481 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1482 Info.Note(VD->getLocation(), diag::note_declared_at);
1483 } else {
1484 Info.CCEDiag(Loc);
1485 }
1486 } else {
1487 // FIXME: Allow folding of values of any literal type in all languages.
1488 if (Info.getLangOpts().CPlusPlus0x) {
1489 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1490 Info.Note(VD->getLocation(), diag::note_declared_at);
1491 } else {
1492 Info.Diag(Loc);
1493 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001494 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001495 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001496 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001497
Richard Smithf48fdb02011-12-09 22:58:01 +00001498 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001499 return false;
1500
Richard Smith47a1eed2011-10-29 20:57:55 +00001501 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001502 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001503
1504 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1505 // conversion. This happens when the declaration and the lvalue should be
1506 // considered synonymous, for instance when initializing an array of char
1507 // from a string literal. Continue as if the initializer lvalue was the
1508 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001509 assert(RVal.getLValueOffset().isZero() &&
1510 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001511 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001512 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001513 }
1514
Richard Smith7098cbd2011-12-21 05:04:46 +00001515 // Volatile temporary objects cannot be read in constant expressions.
1516 if (Base->getType().isVolatileQualified()) {
1517 if (Info.getLangOpts().CPlusPlus) {
1518 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1519 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1520 } else {
1521 Info.Diag(Loc);
1522 }
1523 return false;
1524 }
1525
Richard Smith0a3bdb62011-11-04 02:25:55 +00001526 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1527 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1528 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001529 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001530 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001531 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001532 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001533
1534 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001535 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 const ConstantArrayType *CAT =
1537 Info.Ctx.getAsConstantArrayType(S->getType());
1538 if (Index >= CAT->getSize().getZExtValue()) {
1539 // Note, it should not be possible to form a pointer which points more
1540 // than one past the end of the array without producing a prior const expr
1541 // diagnostic.
1542 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001543 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001544 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001545 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1546 Type->isUnsignedIntegerType());
1547 if (Index < S->getLength())
1548 Value = S->getCodeUnit(Index);
1549 RVal = CCValue(Value);
1550 return true;
1551 }
1552
Richard Smithcc5d4f62011-11-07 09:22:26 +00001553 if (Frame) {
1554 // If this is a temporary expression with a nontrivial initializer, grab the
1555 // value from the relevant stack frame.
1556 RVal = Frame->Temporaries[Base];
1557 } else if (const CompoundLiteralExpr *CLE
1558 = dyn_cast<CompoundLiteralExpr>(Base)) {
1559 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1560 // initializer until now for such expressions. Such an expression can't be
1561 // an ICE in C, so this only matters for fold.
1562 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1563 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1564 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001565 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001566 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001567 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001568 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001569
Richard Smithf48fdb02011-12-09 22:58:01 +00001570 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1571 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001572}
1573
Richard Smith59efe262011-11-11 04:05:33 +00001574/// Build an lvalue for the object argument of a member function call.
1575static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1576 LValue &This) {
1577 if (Object->getType()->isPointerType())
1578 return EvaluatePointer(Object, This, Info);
1579
1580 if (Object->isGLValue())
1581 return EvaluateLValue(Object, This, Info);
1582
Richard Smithe24f5fc2011-11-17 22:56:20 +00001583 if (Object->getType()->isLiteralType())
1584 return EvaluateTemporary(Object, This, Info);
1585
1586 return false;
1587}
1588
1589/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1590/// lvalue referring to the result.
1591///
1592/// \param Info - Information about the ongoing evaluation.
1593/// \param BO - The member pointer access operation.
1594/// \param LV - Filled in with a reference to the resulting object.
1595/// \param IncludeMember - Specifies whether the member itself is included in
1596/// the resulting LValue subobject designator. This is not possible when
1597/// creating a bound member function.
1598/// \return The field or method declaration to which the member pointer refers,
1599/// or 0 if evaluation fails.
1600static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1601 const BinaryOperator *BO,
1602 LValue &LV,
1603 bool IncludeMember = true) {
1604 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1605
1606 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1607 return 0;
1608
1609 MemberPtr MemPtr;
1610 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1611 return 0;
1612
1613 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1614 // member value, the behavior is undefined.
1615 if (!MemPtr.getDecl())
1616 return 0;
1617
1618 if (MemPtr.isDerivedMember()) {
1619 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001620 // The end of the derived-to-base path for the base object must match the
1621 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001622 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001623 LV.Designator.Entries.size())
1624 return 0;
1625 unsigned PathLengthToMember =
1626 LV.Designator.Entries.size() - MemPtr.Path.size();
1627 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1628 const CXXRecordDecl *LVDecl = getAsBaseClass(
1629 LV.Designator.Entries[PathLengthToMember + I]);
1630 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1631 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1632 return 0;
1633 }
1634
1635 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001636 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1637 PathLengthToMember))
1638 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001639 } else if (!MemPtr.Path.empty()) {
1640 // Extend the LValue path with the member pointer's path.
1641 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1642 MemPtr.Path.size() + IncludeMember);
1643
1644 // Walk down to the appropriate base class.
1645 QualType LVType = BO->getLHS()->getType();
1646 if (const PointerType *PT = LVType->getAs<PointerType>())
1647 LVType = PT->getPointeeType();
1648 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1649 assert(RD && "member pointer access on non-class-type expression");
1650 // The first class in the path is that of the lvalue.
1651 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1652 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001653 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001654 RD = Base;
1655 }
1656 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001657 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001658 }
1659
1660 // Add the member. Note that we cannot build bound member functions here.
1661 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001662 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1663 HandleLValueMember(Info, BO, LV, FD);
1664 else if (const IndirectFieldDecl *IFD =
1665 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1666 HandleLValueIndirectMember(Info, BO, LV, IFD);
1667 else
1668 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001669 }
1670
1671 return MemPtr.getDecl();
1672}
1673
1674/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1675/// the provided lvalue, which currently refers to the base object.
1676static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1677 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001678 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001679 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001680 return false;
1681
Richard Smithb4e85ed2012-01-06 16:39:00 +00001682 QualType TargetQT = E->getType();
1683 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1684 TargetQT = PT->getPointeeType();
1685
1686 // Check this cast lands within the final derived-to-base subobject path.
1687 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1688 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1689 << D.MostDerivedType << TargetQT;
1690 return false;
1691 }
1692
Richard Smithe24f5fc2011-11-17 22:56:20 +00001693 // Check the type of the final cast. We don't need to check the path,
1694 // since a cast can only be formed if the path is unique.
1695 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001696 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1697 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001698 if (NewEntriesSize == D.MostDerivedPathLength)
1699 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1700 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001701 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001702 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1703 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1704 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001705 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001706 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001707
1708 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001709 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001710}
1711
Mike Stumpc4c90452009-10-27 22:09:17 +00001712namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001713enum EvalStmtResult {
1714 /// Evaluation failed.
1715 ESR_Failed,
1716 /// Hit a 'return' statement.
1717 ESR_Returned,
1718 /// Evaluation succeeded.
1719 ESR_Succeeded
1720};
1721}
1722
1723// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001724static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001725 const Stmt *S) {
1726 switch (S->getStmtClass()) {
1727 default:
1728 return ESR_Failed;
1729
1730 case Stmt::NullStmtClass:
1731 case Stmt::DeclStmtClass:
1732 return ESR_Succeeded;
1733
Richard Smithc1c5f272011-12-13 06:39:58 +00001734 case Stmt::ReturnStmtClass: {
1735 CCValue CCResult;
1736 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1737 if (!Evaluate(CCResult, Info, RetExpr) ||
1738 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1739 CCEK_ReturnValue))
1740 return ESR_Failed;
1741 return ESR_Returned;
1742 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001743
1744 case Stmt::CompoundStmtClass: {
1745 const CompoundStmt *CS = cast<CompoundStmt>(S);
1746 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1747 BE = CS->body_end(); BI != BE; ++BI) {
1748 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1749 if (ESR != ESR_Succeeded)
1750 return ESR;
1751 }
1752 return ESR_Succeeded;
1753 }
1754 }
1755}
1756
Richard Smith61802452011-12-22 02:22:31 +00001757/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1758/// default constructor. If so, we'll fold it whether or not it's marked as
1759/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1760/// so we need special handling.
1761static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001762 const CXXConstructorDecl *CD,
1763 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001764 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1765 return false;
1766
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001767 // Value-initialization does not call a trivial default constructor, so such a
1768 // call is a core constant expression whether or not the constructor is
1769 // constexpr.
1770 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001771 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001772 // FIXME: If DiagDecl is an implicitly-declared special member function,
1773 // we should be much more explicit about why it's not constexpr.
1774 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1775 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1776 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001777 } else {
1778 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1779 }
1780 }
1781 return true;
1782}
1783
Richard Smithc1c5f272011-12-13 06:39:58 +00001784/// CheckConstexprFunction - Check that a function can be called in a constant
1785/// expression.
1786static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1787 const FunctionDecl *Declaration,
1788 const FunctionDecl *Definition) {
1789 // Can we evaluate this function call?
1790 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1791 return true;
1792
1793 if (Info.getLangOpts().CPlusPlus0x) {
1794 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001795 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1796 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001797 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1798 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1799 << DiagDecl;
1800 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1801 } else {
1802 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1803 }
1804 return false;
1805}
1806
Richard Smith180f4792011-11-10 06:34:14 +00001807namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001808typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001809}
1810
1811/// EvaluateArgs - Evaluate the arguments to a function call.
1812static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1813 EvalInfo &Info) {
1814 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1815 I != E; ++I)
1816 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1817 return false;
1818 return true;
1819}
1820
Richard Smithd0dccea2011-10-28 22:34:42 +00001821/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001822static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1823 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001824 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001825 EvalInfo &Info, APValue &Result) {
1826 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001827 return false;
1828
Richard Smith180f4792011-11-10 06:34:14 +00001829 ArgVector ArgValues(Args.size());
1830 if (!EvaluateArgs(Args, ArgValues, Info))
1831 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001832
Richard Smith08d6e032011-12-16 19:06:07 +00001833 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1834 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001835 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1836}
1837
Richard Smith180f4792011-11-10 06:34:14 +00001838/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001839static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001840 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001841 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001842 EvalInfo &Info, APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001843 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001844 return false;
1845
1846 ArgVector ArgValues(Args.size());
1847 if (!EvaluateArgs(Args, ArgValues, Info))
1848 return false;
1849
Richard Smith08d6e032011-12-16 19:06:07 +00001850 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1851 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001852
1853 // If it's a delegating constructor, just delegate.
1854 if (Definition->isDelegatingConstructor()) {
1855 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1856 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1857 }
1858
Richard Smith610a60c2012-01-10 04:32:03 +00001859 // For a trivial copy or move constructor, perform an APValue copy. This is
1860 // essential for unions, where the operations performed by the constructor
1861 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001862 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001863 if (Definition->isDefaulted() &&
1864 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1865 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1866 LValue RHS;
1867 RHS.setFrom(ArgValues[0]);
1868 CCValue Value;
1869 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1870 RHS, Value) &&
1871 CheckConstantExpression(Info, CallExpr, Value, Result);
1872 }
1873
1874 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001875 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001876 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1877 std::distance(RD->field_begin(), RD->field_end()));
1878
1879 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1880
1881 unsigned BasesSeen = 0;
1882#ifndef NDEBUG
1883 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1884#endif
1885 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1886 E = Definition->init_end(); I != E; ++I) {
1887 if ((*I)->isBaseInitializer()) {
1888 QualType BaseType((*I)->getBaseClass(), 0);
1889#ifndef NDEBUG
1890 // Non-virtual base classes are initialized in the order in the class
1891 // definition. We cannot have a virtual base class for a literal type.
1892 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1893 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1894 "base class initializers not in expected order");
1895 ++BaseIt;
1896#endif
1897 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001898 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001899 BaseType->getAsCXXRecordDecl(), &Layout);
1900 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1901 Subobject, (*I)->getInit()))
1902 return false;
1903 } else if (FieldDecl *FD = (*I)->getMember()) {
1904 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001905 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001906 if (RD->isUnion()) {
1907 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001908 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1909 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001910 return false;
1911 } else if (!EvaluateConstantExpression(
1912 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001913 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001914 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00001915 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
1916 LValue Subobject = This;
1917 APValue *Value = &Result;
1918 // Walk the indirect field decl's chain to find the object to initialize,
1919 // and make sure we've initialized every step along it.
1920 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1921 CE = IFD->chain_end();
1922 C != CE; ++C) {
1923 FieldDecl *FD = cast<FieldDecl>(*C);
1924 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
1925 // Switch the union field if it differs. This happens if we had
1926 // preceding zero-initialization, and we're now initializing a union
1927 // subobject other than the first.
1928 // FIXME: In this case, the values of the other subobjects are
1929 // specified, since zero-initialization sets all padding bits to zero.
1930 if (Value->isUninit() ||
1931 (Value->isUnion() && Value->getUnionField() != FD)) {
1932 if (CD->isUnion())
1933 *Value = APValue(FD);
1934 else
1935 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
1936 std::distance(CD->field_begin(), CD->field_end()));
1937 }
1938 if (CD->isUnion())
1939 Value = &Value->getUnionValue();
1940 else
1941 Value = &Value->getStructField(FD->getFieldIndex());
1942 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
1943 }
1944 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
1945 CCEK_MemberInit))
1946 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001947 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001948 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00001949 }
1950 }
1951
1952 return true;
1953}
1954
Richard Smithd0dccea2011-10-28 22:34:42 +00001955namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001956class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001957 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001958 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001959public:
1960
Richard Smith1e12c592011-10-16 21:26:27 +00001961 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001962
1963 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001964 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001965 return true;
1966 }
1967
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001968 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1969 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001970 return Visit(E->getResultExpr());
1971 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001972 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001973 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001974 return true;
1975 return false;
1976 }
John McCallf85e1932011-06-15 23:02:42 +00001977 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001978 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001979 return true;
1980 return false;
1981 }
1982 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001983 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001984 return true;
1985 return false;
1986 }
1987
Mike Stumpc4c90452009-10-27 22:09:17 +00001988 // We don't want to evaluate BlockExprs multiple times, as they generate
1989 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001990 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1991 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1992 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001993 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001994 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1995 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1996 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1997 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1998 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1999 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002000 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002001 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002002 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002003 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002004 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002005 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2006 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2007 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2008 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002009 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002010 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2011 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2012 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2013 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2014 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002015 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002016 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002017 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002018 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002019 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002020
2021 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002022 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002023 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2024 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002025 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002026 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002027 return false;
2028 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002029
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002030 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002031};
2032
John McCall56ca35d2011-02-17 10:25:35 +00002033class OpaqueValueEvaluation {
2034 EvalInfo &info;
2035 OpaqueValueExpr *opaqueValue;
2036
2037public:
2038 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2039 Expr *value)
2040 : info(info), opaqueValue(opaqueValue) {
2041
2042 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002043 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002044 this->opaqueValue = 0;
2045 return;
2046 }
John McCall56ca35d2011-02-17 10:25:35 +00002047 }
2048
2049 bool hasError() const { return opaqueValue == 0; }
2050
2051 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002052 // FIXME: This will not work for recursive constexpr functions using opaque
2053 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002054 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2055 }
2056};
2057
Mike Stumpc4c90452009-10-27 22:09:17 +00002058} // end anonymous namespace
2059
Eli Friedman4efaa272008-11-12 09:44:48 +00002060//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002061// Generic Evaluation
2062//===----------------------------------------------------------------------===//
2063namespace {
2064
Richard Smithf48fdb02011-12-09 22:58:01 +00002065// FIXME: RetTy is always bool. Remove it.
2066template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002067class ExprEvaluatorBase
2068 : public ConstStmtVisitor<Derived, RetTy> {
2069private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002070 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002071 return static_cast<Derived*>(this)->Success(V, E);
2072 }
Richard Smith51201882011-12-30 21:15:51 +00002073 RetTy DerivedZeroInitialization(const Expr *E) {
2074 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002075 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002076
2077protected:
2078 EvalInfo &Info;
2079 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2080 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2081
Richard Smithdd1f29b2011-12-12 09:28:41 +00002082 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002083 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002084 }
2085
2086 /// Report an evaluation error. This should only be called when an error is
2087 /// first discovered. When propagating an error, just return false.
2088 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002089 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002090 return false;
2091 }
2092 bool Error(const Expr *E) {
2093 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2094 }
2095
Richard Smith51201882011-12-30 21:15:51 +00002096 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002097
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002098public:
2099 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2100
2101 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002102 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002103 }
2104 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002105 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002106 }
2107
2108 RetTy VisitParenExpr(const ParenExpr *E)
2109 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2110 RetTy VisitUnaryExtension(const UnaryOperator *E)
2111 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2112 RetTy VisitUnaryPlus(const UnaryOperator *E)
2113 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2114 RetTy VisitChooseExpr(const ChooseExpr *E)
2115 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2116 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2117 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002118 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2119 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002120 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2121 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002122 // We cannot create any objects for which cleanups are required, so there is
2123 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2124 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2125 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002126
Richard Smithc216a012011-12-12 12:46:16 +00002127 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2128 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2129 return static_cast<Derived*>(this)->VisitCastExpr(E);
2130 }
2131 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2132 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2133 return static_cast<Derived*>(this)->VisitCastExpr(E);
2134 }
2135
Richard Smithe24f5fc2011-11-17 22:56:20 +00002136 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2137 switch (E->getOpcode()) {
2138 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002139 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002140
2141 case BO_Comma:
2142 VisitIgnoredValue(E->getLHS());
2143 return StmtVisitorTy::Visit(E->getRHS());
2144
2145 case BO_PtrMemD:
2146 case BO_PtrMemI: {
2147 LValue Obj;
2148 if (!HandleMemberPointerAccess(Info, E, Obj))
2149 return false;
2150 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002151 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002152 return false;
2153 return DerivedSuccess(Result, E);
2154 }
2155 }
2156 }
2157
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002158 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2159 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2160 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002161 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002162
2163 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002164 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002165 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002166
2167 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2168 }
2169
2170 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2171 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002172 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002173 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002174
Richard Smithc49bd112011-10-28 17:51:58 +00002175 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002176 return StmtVisitorTy::Visit(EvalExpr);
2177 }
2178
2179 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002180 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002181 if (!Value) {
2182 const Expr *Source = E->getSourceExpr();
2183 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002184 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002185 if (Source == E) { // sanity checking.
2186 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002187 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002188 }
2189 return StmtVisitorTy::Visit(Source);
2190 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002191 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002192 }
Richard Smithf10d9172011-10-11 21:43:33 +00002193
Richard Smithd0dccea2011-10-28 22:34:42 +00002194 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002195 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002196 QualType CalleeType = Callee->getType();
2197
Richard Smithd0dccea2011-10-28 22:34:42 +00002198 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002199 LValue *This = 0, ThisVal;
2200 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002201
Richard Smith59efe262011-11-11 04:05:33 +00002202 // Extract function decl and 'this' pointer from the callee.
2203 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002204 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002205 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2206 // Explicit bound member calls, such as x.f() or p->g();
2207 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002208 return false;
2209 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002210 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002211 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2212 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002213 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2214 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002215 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002216 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002217 return Error(Callee);
2218
2219 FD = dyn_cast<FunctionDecl>(Member);
2220 if (!FD)
2221 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002222 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002223 LValue Call;
2224 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002225 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002226
Richard Smithb4e85ed2012-01-06 16:39:00 +00002227 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002228 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002229 FD = dyn_cast_or_null<FunctionDecl>(
2230 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002231 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002232 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002233
2234 // Overloaded operator calls to member functions are represented as normal
2235 // calls with '*this' as the first argument.
2236 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2237 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002238 // FIXME: When selecting an implicit conversion for an overloaded
2239 // operator delete, we sometimes try to evaluate calls to conversion
2240 // operators without a 'this' parameter!
2241 if (Args.empty())
2242 return Error(E);
2243
Richard Smith59efe262011-11-11 04:05:33 +00002244 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2245 return false;
2246 This = &ThisVal;
2247 Args = Args.slice(1);
2248 }
2249
2250 // Don't call function pointers which have been cast to some other type.
2251 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002252 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002253 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002254 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002255
Richard Smithc1c5f272011-12-13 06:39:58 +00002256 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002257 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002258 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002259
Richard Smithc1c5f272011-12-13 06:39:58 +00002260 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002261 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002262 return false;
2263
Richard Smithb4e85ed2012-01-06 16:39:00 +00002264 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002265 }
2266
Richard Smithc49bd112011-10-28 17:51:58 +00002267 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2268 return StmtVisitorTy::Visit(E->getInitializer());
2269 }
Richard Smithf10d9172011-10-11 21:43:33 +00002270 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002271 if (E->getNumInits() == 0)
2272 return DerivedZeroInitialization(E);
2273 if (E->getNumInits() == 1)
2274 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002275 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002276 }
2277 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002278 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002279 }
2280 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002281 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002282 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002283 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002284 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002285 }
Richard Smithf10d9172011-10-11 21:43:33 +00002286
Richard Smith180f4792011-11-10 06:34:14 +00002287 /// A member expression where the object is a prvalue is itself a prvalue.
2288 RetTy VisitMemberExpr(const MemberExpr *E) {
2289 assert(!E->isArrow() && "missing call to bound member function?");
2290
2291 CCValue Val;
2292 if (!Evaluate(Val, Info, E->getBase()))
2293 return false;
2294
2295 QualType BaseTy = E->getBase()->getType();
2296
2297 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002298 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002299 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2300 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2301 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2302
Richard Smithb4e85ed2012-01-06 16:39:00 +00002303 SubobjectDesignator Designator(BaseTy);
2304 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002305
Richard Smithf48fdb02011-12-09 22:58:01 +00002306 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002307 DerivedSuccess(Val, E);
2308 }
2309
Richard Smithc49bd112011-10-28 17:51:58 +00002310 RetTy VisitCastExpr(const CastExpr *E) {
2311 switch (E->getCastKind()) {
2312 default:
2313 break;
2314
David Chisnall7a7ee302012-01-16 17:27:18 +00002315 case CK_AtomicToNonAtomic:
2316 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002317 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002318 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002319 return StmtVisitorTy::Visit(E->getSubExpr());
2320
2321 case CK_LValueToRValue: {
2322 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002323 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2324 return false;
2325 CCValue RVal;
2326 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2327 return false;
2328 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002329 }
2330 }
2331
Richard Smithf48fdb02011-12-09 22:58:01 +00002332 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002333 }
2334
Richard Smith8327fad2011-10-24 18:44:57 +00002335 /// Visit a value which is evaluated, but whose value is ignored.
2336 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002337 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002338 if (!Evaluate(Scratch, Info, E))
2339 Info.EvalStatus.HasSideEffects = true;
2340 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002341};
2342
2343}
2344
2345//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002346// Common base class for lvalue and temporary evaluation.
2347//===----------------------------------------------------------------------===//
2348namespace {
2349template<class Derived>
2350class LValueExprEvaluatorBase
2351 : public ExprEvaluatorBase<Derived, bool> {
2352protected:
2353 LValue &Result;
2354 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2355 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2356
2357 bool Success(APValue::LValueBase B) {
2358 Result.set(B);
2359 return true;
2360 }
2361
2362public:
2363 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2364 ExprEvaluatorBaseTy(Info), Result(Result) {}
2365
2366 bool Success(const CCValue &V, const Expr *E) {
2367 Result.setFrom(V);
2368 return true;
2369 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002370
Richard Smithe24f5fc2011-11-17 22:56:20 +00002371 bool VisitMemberExpr(const MemberExpr *E) {
2372 // Handle non-static data members.
2373 QualType BaseTy;
2374 if (E->isArrow()) {
2375 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2376 return false;
2377 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002378 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002379 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002380 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2381 return false;
2382 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002383 } else {
2384 if (!this->Visit(E->getBase()))
2385 return false;
2386 BaseTy = E->getBase()->getType();
2387 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002388
Richard Smithd9b02e72012-01-25 22:15:11 +00002389 const ValueDecl *MD = E->getMemberDecl();
2390 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2391 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2392 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2393 (void)BaseTy;
2394 HandleLValueMember(this->Info, E, Result, FD);
2395 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2396 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2397 } else
2398 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002399
Richard Smithd9b02e72012-01-25 22:15:11 +00002400 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002401 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002402 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002403 RefValue))
2404 return false;
2405 return Success(RefValue, E);
2406 }
2407 return true;
2408 }
2409
2410 bool VisitBinaryOperator(const BinaryOperator *E) {
2411 switch (E->getOpcode()) {
2412 default:
2413 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2414
2415 case BO_PtrMemD:
2416 case BO_PtrMemI:
2417 return HandleMemberPointerAccess(this->Info, E, Result);
2418 }
2419 }
2420
2421 bool VisitCastExpr(const CastExpr *E) {
2422 switch (E->getCastKind()) {
2423 default:
2424 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2425
2426 case CK_DerivedToBase:
2427 case CK_UncheckedDerivedToBase: {
2428 if (!this->Visit(E->getSubExpr()))
2429 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002430
2431 // Now figure out the necessary offset to add to the base LV to get from
2432 // the derived class to the base class.
2433 QualType Type = E->getSubExpr()->getType();
2434
2435 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2436 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002437 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002438 *PathI))
2439 return false;
2440 Type = (*PathI)->getType();
2441 }
2442
2443 return true;
2444 }
2445 }
2446 }
2447};
2448}
2449
2450//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002451// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002452//
2453// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2454// function designators (in C), decl references to void objects (in C), and
2455// temporaries (if building with -Wno-address-of-temporary).
2456//
2457// LValue evaluation produces values comprising a base expression of one of the
2458// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002459// - Declarations
2460// * VarDecl
2461// * FunctionDecl
2462// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002463// * CompoundLiteralExpr in C
2464// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002465// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002466// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002467// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002468// * ObjCEncodeExpr
2469// * AddrLabelExpr
2470// * BlockExpr
2471// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002472// - Locals and temporaries
2473// * Any Expr, with a Frame indicating the function in which the temporary was
2474// evaluated.
2475// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002476//===----------------------------------------------------------------------===//
2477namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002478class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002479 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002480public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002481 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2482 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Richard Smithc49bd112011-10-28 17:51:58 +00002484 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2485
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002486 bool VisitDeclRefExpr(const DeclRefExpr *E);
2487 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002488 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002489 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2490 bool VisitMemberExpr(const MemberExpr *E);
2491 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2492 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002493 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002494 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2495 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002496
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002497 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002498 switch (E->getCastKind()) {
2499 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002501
Eli Friedmandb924222011-10-11 00:13:24 +00002502 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002503 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002504 if (!Visit(E->getSubExpr()))
2505 return false;
2506 Result.Designator.setInvalid();
2507 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002508
Richard Smithe24f5fc2011-11-17 22:56:20 +00002509 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002510 if (!Visit(E->getSubExpr()))
2511 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002513 }
2514 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002515
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002516 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002517
Eli Friedman4efaa272008-11-12 09:44:48 +00002518};
2519} // end anonymous namespace
2520
Richard Smithc49bd112011-10-28 17:51:58 +00002521/// Evaluate an expression as an lvalue. This can be legitimately called on
2522/// expressions which are not glvalues, in a few cases:
2523/// * function designators in C,
2524/// * "extern void" objects,
2525/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002526static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002527 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2528 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2529 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002530 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002531}
2532
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002533bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002534 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2535 return Success(FD);
2536 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002537 return VisitVarDecl(E, VD);
2538 return Error(E);
2539}
Richard Smith436c8892011-10-24 23:14:33 +00002540
Richard Smithc49bd112011-10-28 17:51:58 +00002541bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002542 if (!VD->getType()->isReferenceType()) {
2543 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002544 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002545 return true;
2546 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002547 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002548 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002549
Richard Smith47a1eed2011-10-29 20:57:55 +00002550 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002551 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2552 return false;
2553 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002554}
2555
Richard Smithbd552ef2011-10-31 05:52:43 +00002556bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2557 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002558 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002559 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002560 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2561
2562 Result.set(E, Info.CurrentCall);
2563 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2564 Result, E->GetTemporaryExpr());
2565 }
2566
2567 // Materialization of an lvalue temporary occurs when we need to force a copy
2568 // (for instance, if it's a bitfield).
2569 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2570 if (!Visit(E->GetTemporaryExpr()))
2571 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002573 Info.CurrentCall->Temporaries[E]))
2574 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002575 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002577}
2578
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002579bool
2580LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002581 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2582 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2583 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002584 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002585}
2586
Richard Smith47d21452011-12-27 12:18:28 +00002587bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2588 if (E->isTypeOperand())
2589 return Success(E);
2590 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2591 if (RD && RD->isPolymorphic()) {
2592 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2593 << E->getExprOperand()->getType()
2594 << E->getExprOperand()->getSourceRange();
2595 return false;
2596 }
2597 return Success(E);
2598}
2599
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002600bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002601 // Handle static data members.
2602 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2603 VisitIgnoredValue(E->getBase());
2604 return VisitVarDecl(E, VD);
2605 }
2606
Richard Smithd0dccea2011-10-28 22:34:42 +00002607 // Handle static member functions.
2608 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2609 if (MD->isStatic()) {
2610 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002611 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002612 }
2613 }
2614
Richard Smith180f4792011-11-10 06:34:14 +00002615 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002616 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002617}
2618
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002619bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002620 // FIXME: Deal with vectors as array subscript bases.
2621 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002622 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002623
Anders Carlsson3068d112008-11-16 19:01:22 +00002624 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002625 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Anders Carlsson3068d112008-11-16 19:01:22 +00002627 APSInt Index;
2628 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002629 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002630 int64_t IndexValue
2631 = Index.isSigned() ? Index.getSExtValue()
2632 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002633
Richard Smithb4e85ed2012-01-06 16:39:00 +00002634 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002635}
Eli Friedman4efaa272008-11-12 09:44:48 +00002636
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002637bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002638 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002639}
2640
Eli Friedman4efaa272008-11-12 09:44:48 +00002641//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002642// Pointer Evaluation
2643//===----------------------------------------------------------------------===//
2644
Anders Carlssonc754aa62008-07-08 05:13:58 +00002645namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002646class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002647 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002648 LValue &Result;
2649
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002650 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002651 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002652 return true;
2653 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002654public:
Mike Stump1eb44332009-09-09 15:08:12 +00002655
John McCallefdb83e2010-05-07 21:00:08 +00002656 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002657 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002658
Richard Smith47a1eed2011-10-29 20:57:55 +00002659 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002660 Result.setFrom(V);
2661 return true;
2662 }
Richard Smith51201882011-12-30 21:15:51 +00002663 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002664 return Success((Expr*)0);
2665 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002666
John McCallefdb83e2010-05-07 21:00:08 +00002667 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002668 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002669 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002670 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002671 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002672 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002673 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002674 bool VisitCallExpr(const CallExpr *E);
2675 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002676 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002677 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002678 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002679 }
Richard Smith180f4792011-11-10 06:34:14 +00002680 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2681 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002682 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002683 Result = *Info.CurrentCall->This;
2684 return true;
2685 }
John McCall56ca35d2011-02-17 10:25:35 +00002686
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002687 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002688};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002689} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002690
John McCallefdb83e2010-05-07 21:00:08 +00002691static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002692 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002693 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002694}
2695
John McCallefdb83e2010-05-07 21:00:08 +00002696bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002697 if (E->getOpcode() != BO_Add &&
2698 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002699 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002701 const Expr *PExp = E->getLHS();
2702 const Expr *IExp = E->getRHS();
2703 if (IExp->getType()->isPointerType())
2704 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002705
John McCallefdb83e2010-05-07 21:00:08 +00002706 if (!EvaluatePointer(PExp, Result, Info))
2707 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002708
John McCallefdb83e2010-05-07 21:00:08 +00002709 llvm::APSInt Offset;
2710 if (!EvaluateInteger(IExp, Offset, Info))
2711 return false;
2712 int64_t AdditionalOffset
2713 = Offset.isSigned() ? Offset.getSExtValue()
2714 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002715 if (E->getOpcode() == BO_Sub)
2716 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002717
Richard Smith180f4792011-11-10 06:34:14 +00002718 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002719 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2720 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002721}
Eli Friedman4efaa272008-11-12 09:44:48 +00002722
John McCallefdb83e2010-05-07 21:00:08 +00002723bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2724 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002725}
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002727bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2728 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002729
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002730 switch (E->getCastKind()) {
2731 default:
2732 break;
2733
John McCall2de56d12010-08-25 11:45:40 +00002734 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002735 case CK_CPointerToObjCPointerCast:
2736 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002737 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002738 if (!Visit(SubExpr))
2739 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002740 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2741 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2742 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002743 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002744 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002745 if (SubExpr->getType()->isVoidPointerType())
2746 CCEDiag(E, diag::note_constexpr_invalid_cast)
2747 << 3 << SubExpr->getType();
2748 else
2749 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2750 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002751 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002752
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002753 case CK_DerivedToBase:
2754 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002755 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002756 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002757 if (!Result.Base && Result.Offset.isZero())
2758 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002759
Richard Smith180f4792011-11-10 06:34:14 +00002760 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002761 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002762 QualType Type =
2763 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002764
Richard Smith180f4792011-11-10 06:34:14 +00002765 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002766 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002767 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2768 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002769 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002770 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002771 }
2772
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002773 return true;
2774 }
2775
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776 case CK_BaseToDerived:
2777 if (!Visit(E->getSubExpr()))
2778 return false;
2779 if (!Result.Base && Result.Offset.isZero())
2780 return true;
2781 return HandleBaseToDerivedCast(Info, E, Result);
2782
Richard Smith47a1eed2011-10-29 20:57:55 +00002783 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002784 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002785
John McCall2de56d12010-08-25 11:45:40 +00002786 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002787 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2788
Richard Smith47a1eed2011-10-29 20:57:55 +00002789 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002790 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002791 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002792
John McCallefdb83e2010-05-07 21:00:08 +00002793 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002794 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2795 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002796 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002797 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002798 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002799 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002800 return true;
2801 } else {
2802 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002803 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002804 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002805 }
2806 }
John McCall2de56d12010-08-25 11:45:40 +00002807 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002808 if (SubExpr->isGLValue()) {
2809 if (!EvaluateLValue(SubExpr, Result, Info))
2810 return false;
2811 } else {
2812 Result.set(SubExpr, Info.CurrentCall);
2813 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2814 Info, Result, SubExpr))
2815 return false;
2816 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002817 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002818 if (const ConstantArrayType *CAT
2819 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2820 Result.addArray(Info, E, CAT);
2821 else
2822 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002823 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002824
John McCall2de56d12010-08-25 11:45:40 +00002825 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002826 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002827 }
2828
Richard Smithc49bd112011-10-28 17:51:58 +00002829 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002830}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002831
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002832bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002833 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002834 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002835
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002836 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002837}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002838
2839//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002840// Member Pointer Evaluation
2841//===----------------------------------------------------------------------===//
2842
2843namespace {
2844class MemberPointerExprEvaluator
2845 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2846 MemberPtr &Result;
2847
2848 bool Success(const ValueDecl *D) {
2849 Result = MemberPtr(D);
2850 return true;
2851 }
2852public:
2853
2854 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2855 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2856
2857 bool Success(const CCValue &V, const Expr *E) {
2858 Result.setFrom(V);
2859 return true;
2860 }
Richard Smith51201882011-12-30 21:15:51 +00002861 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 return Success((const ValueDecl*)0);
2863 }
2864
2865 bool VisitCastExpr(const CastExpr *E);
2866 bool VisitUnaryAddrOf(const UnaryOperator *E);
2867};
2868} // end anonymous namespace
2869
2870static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2871 EvalInfo &Info) {
2872 assert(E->isRValue() && E->getType()->isMemberPointerType());
2873 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2874}
2875
2876bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2877 switch (E->getCastKind()) {
2878 default:
2879 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2880
2881 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002882 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883
2884 case CK_BaseToDerivedMemberPointer: {
2885 if (!Visit(E->getSubExpr()))
2886 return false;
2887 if (E->path_empty())
2888 return true;
2889 // Base-to-derived member pointer casts store the path in derived-to-base
2890 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2891 // the wrong end of the derived->base arc, so stagger the path by one class.
2892 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2893 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2894 PathI != PathE; ++PathI) {
2895 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2896 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2897 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002898 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002899 }
2900 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2901 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002902 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002903 return true;
2904 }
2905
2906 case CK_DerivedToBaseMemberPointer:
2907 if (!Visit(E->getSubExpr()))
2908 return false;
2909 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2910 PathE = E->path_end(); PathI != PathE; ++PathI) {
2911 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2912 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2913 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002914 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002915 }
2916 return true;
2917 }
2918}
2919
2920bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2921 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2922 // member can be formed.
2923 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2924}
2925
2926//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002927// Record Evaluation
2928//===----------------------------------------------------------------------===//
2929
2930namespace {
2931 class RecordExprEvaluator
2932 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2933 const LValue &This;
2934 APValue &Result;
2935 public:
2936
2937 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2938 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2939
2940 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002941 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002942 }
Richard Smith51201882011-12-30 21:15:51 +00002943 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002944
Richard Smith59efe262011-11-11 04:05:33 +00002945 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002946 bool VisitInitListExpr(const InitListExpr *E);
2947 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2948 };
2949}
2950
Richard Smith51201882011-12-30 21:15:51 +00002951/// Perform zero-initialization on an object of non-union class type.
2952/// C++11 [dcl.init]p5:
2953/// To zero-initialize an object or reference of type T means:
2954/// [...]
2955/// -- if T is a (possibly cv-qualified) non-union class type,
2956/// each non-static data member and each base-class subobject is
2957/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00002958static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2959 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00002960 const LValue &This, APValue &Result) {
2961 assert(!RD->isUnion() && "Expected non-union class type");
2962 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2963 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2964 std::distance(RD->field_begin(), RD->field_end()));
2965
2966 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2967
2968 if (CD) {
2969 unsigned Index = 0;
2970 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00002971 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00002972 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2973 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002974 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2975 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00002976 Result.getStructBase(Index)))
2977 return false;
2978 }
2979 }
2980
Richard Smithb4e85ed2012-01-06 16:39:00 +00002981 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2982 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00002983 // -- if T is a reference type, no initialization is performed.
2984 if ((*I)->getType()->isReferenceType())
2985 continue;
2986
2987 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002988 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00002989
2990 ImplicitValueInitExpr VIE((*I)->getType());
2991 if (!EvaluateConstantExpression(
2992 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2993 return false;
2994 }
2995
2996 return true;
2997}
2998
2999bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3000 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3001 if (RD->isUnion()) {
3002 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3003 // object's first non-static named data member is zero-initialized
3004 RecordDecl::field_iterator I = RD->field_begin();
3005 if (I == RD->field_end()) {
3006 Result = APValue((const FieldDecl*)0);
3007 return true;
3008 }
3009
3010 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003011 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003012 Result = APValue(*I);
3013 ImplicitValueInitExpr VIE((*I)->getType());
3014 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3015 Subobject, &VIE);
3016 }
3017
Richard Smithb4e85ed2012-01-06 16:39:00 +00003018 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003019}
3020
Richard Smith59efe262011-11-11 04:05:33 +00003021bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3022 switch (E->getCastKind()) {
3023 default:
3024 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3025
3026 case CK_ConstructorConversion:
3027 return Visit(E->getSubExpr());
3028
3029 case CK_DerivedToBase:
3030 case CK_UncheckedDerivedToBase: {
3031 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003032 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003033 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003034 if (!DerivedObject.isStruct())
3035 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003036
3037 // Derived-to-base rvalue conversion: just slice off the derived part.
3038 APValue *Value = &DerivedObject;
3039 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3040 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3041 PathE = E->path_end(); PathI != PathE; ++PathI) {
3042 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3043 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3044 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3045 RD = Base;
3046 }
3047 Result = *Value;
3048 return true;
3049 }
3050 }
3051}
3052
Richard Smith180f4792011-11-10 06:34:14 +00003053bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3054 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3055 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3056
3057 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003058 const FieldDecl *Field = E->getInitializedFieldInUnion();
3059 Result = APValue(Field);
3060 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003061 return true;
Richard Smithec789162012-01-12 18:54:33 +00003062
3063 // If the initializer list for a union does not contain any elements, the
3064 // first element of the union is value-initialized.
3065 ImplicitValueInitExpr VIE(Field->getType());
3066 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3067
Richard Smith180f4792011-11-10 06:34:14 +00003068 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003069 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003070 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003071 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003072 }
3073
3074 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3075 "initializer list for class with base classes");
3076 Result = APValue(APValue::UninitStruct(), 0,
3077 std::distance(RD->field_begin(), RD->field_end()));
3078 unsigned ElementNo = 0;
3079 for (RecordDecl::field_iterator Field = RD->field_begin(),
3080 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3081 // Anonymous bit-fields are not considered members of the class for
3082 // purposes of aggregate initialization.
3083 if (Field->isUnnamedBitfield())
3084 continue;
3085
3086 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003087
3088 if (ElementNo < E->getNumInits()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003089 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3090 &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003091 if (!EvaluateConstantExpression(
3092 Result.getStructField((*Field)->getFieldIndex()),
3093 Info, Subobject, E->getInit(ElementNo++)))
3094 return false;
3095 } else {
3096 // Perform an implicit value-initialization for members beyond the end of
3097 // the initializer list.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003098 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003099 ImplicitValueInitExpr VIE(Field->getType());
3100 if (!EvaluateConstantExpression(
3101 Result.getStructField((*Field)->getFieldIndex()),
3102 Info, Subobject, &VIE))
3103 return false;
3104 }
3105 }
3106
3107 return true;
3108}
3109
3110bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3111 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003112 bool ZeroInit = E->requiresZeroInitialization();
3113 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003114 // If we've already performed zero-initialization, we're already done.
3115 if (!Result.isUninit())
3116 return true;
3117
Richard Smith51201882011-12-30 21:15:51 +00003118 if (ZeroInit)
3119 return ZeroInitialization(E);
3120
Richard Smith61802452011-12-22 02:22:31 +00003121 const CXXRecordDecl *RD = FD->getParent();
3122 if (RD->isUnion())
3123 Result = APValue((FieldDecl*)0);
3124 else
3125 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3126 std::distance(RD->field_begin(), RD->field_end()));
3127 return true;
3128 }
3129
Richard Smith180f4792011-11-10 06:34:14 +00003130 const FunctionDecl *Definition = 0;
3131 FD->getBody(Definition);
3132
Richard Smithc1c5f272011-12-13 06:39:58 +00003133 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3134 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003135
Richard Smith610a60c2012-01-10 04:32:03 +00003136 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003137 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003138 if (const MaterializeTemporaryExpr *ME
3139 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3140 return Visit(ME->GetTemporaryExpr());
3141
Richard Smith51201882011-12-30 21:15:51 +00003142 if (ZeroInit && !ZeroInitialization(E))
3143 return false;
3144
Richard Smith180f4792011-11-10 06:34:14 +00003145 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003146 return HandleConstructorCall(E, This, Args,
3147 cast<CXXConstructorDecl>(Definition), Info,
3148 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003149}
3150
3151static bool EvaluateRecord(const Expr *E, const LValue &This,
3152 APValue &Result, EvalInfo &Info) {
3153 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003154 "can't evaluate expression as a record rvalue");
3155 return RecordExprEvaluator(Info, This, Result).Visit(E);
3156}
3157
3158//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003159// Temporary Evaluation
3160//
3161// Temporaries are represented in the AST as rvalues, but generally behave like
3162// lvalues. The full-object of which the temporary is a subobject is implicitly
3163// materialized so that a reference can bind to it.
3164//===----------------------------------------------------------------------===//
3165namespace {
3166class TemporaryExprEvaluator
3167 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3168public:
3169 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3170 LValueExprEvaluatorBaseTy(Info, Result) {}
3171
3172 /// Visit an expression which constructs the value of this temporary.
3173 bool VisitConstructExpr(const Expr *E) {
3174 Result.set(E, Info.CurrentCall);
3175 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3176 Result, E);
3177 }
3178
3179 bool VisitCastExpr(const CastExpr *E) {
3180 switch (E->getCastKind()) {
3181 default:
3182 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3183
3184 case CK_ConstructorConversion:
3185 return VisitConstructExpr(E->getSubExpr());
3186 }
3187 }
3188 bool VisitInitListExpr(const InitListExpr *E) {
3189 return VisitConstructExpr(E);
3190 }
3191 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3192 return VisitConstructExpr(E);
3193 }
3194 bool VisitCallExpr(const CallExpr *E) {
3195 return VisitConstructExpr(E);
3196 }
3197};
3198} // end anonymous namespace
3199
3200/// Evaluate an expression of record type as a temporary.
3201static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003202 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003203 return TemporaryExprEvaluator(Info, Result).Visit(E);
3204}
3205
3206//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003207// Vector Evaluation
3208//===----------------------------------------------------------------------===//
3209
3210namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003211 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003212 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3213 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003214 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Richard Smith07fc6572011-10-22 21:10:00 +00003216 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3217 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Richard Smith07fc6572011-10-22 21:10:00 +00003219 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3220 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3221 // FIXME: remove this APValue copy.
3222 Result = APValue(V.data(), V.size());
3223 return true;
3224 }
Richard Smith69c2c502011-11-04 05:33:44 +00003225 bool Success(const CCValue &V, const Expr *E) {
3226 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003227 Result = V;
3228 return true;
3229 }
Richard Smith51201882011-12-30 21:15:51 +00003230 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Richard Smith07fc6572011-10-22 21:10:00 +00003232 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003233 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003234 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003235 bool VisitInitListExpr(const InitListExpr *E);
3236 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003237 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003238 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003239 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003240 };
3241} // end anonymous namespace
3242
3243static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003244 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003245 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003246}
3247
Richard Smith07fc6572011-10-22 21:10:00 +00003248bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3249 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003250 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Richard Smithd62ca372011-12-06 22:44:34 +00003252 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003253 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003254
Eli Friedman46a52322011-03-25 00:43:55 +00003255 switch (E->getCastKind()) {
3256 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003257 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003258 if (SETy->isIntegerType()) {
3259 APSInt IntResult;
3260 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003261 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003262 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003263 } else if (SETy->isRealFloatingType()) {
3264 APFloat F(0.0);
3265 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003266 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003267 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003268 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003269 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003270 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003271
3272 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003273 SmallVector<APValue, 4> Elts(NElts, Val);
3274 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003275 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003276 case CK_BitCast: {
3277 // Evaluate the operand into an APInt we can extract from.
3278 llvm::APInt SValInt;
3279 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3280 return false;
3281 // Extract the elements
3282 QualType EltTy = VTy->getElementType();
3283 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3284 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3285 SmallVector<APValue, 4> Elts;
3286 if (EltTy->isRealFloatingType()) {
3287 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3288 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3289 unsigned FloatEltSize = EltSize;
3290 if (&Sem == &APFloat::x87DoubleExtended)
3291 FloatEltSize = 80;
3292 for (unsigned i = 0; i < NElts; i++) {
3293 llvm::APInt Elt;
3294 if (BigEndian)
3295 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3296 else
3297 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3298 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3299 }
3300 } else if (EltTy->isIntegerType()) {
3301 for (unsigned i = 0; i < NElts; i++) {
3302 llvm::APInt Elt;
3303 if (BigEndian)
3304 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3305 else
3306 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3307 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3308 }
3309 } else {
3310 return Error(E);
3311 }
3312 return Success(Elts, E);
3313 }
Eli Friedman46a52322011-03-25 00:43:55 +00003314 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003315 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003316 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003317}
3318
Richard Smith07fc6572011-10-22 21:10:00 +00003319bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003320VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003321 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003322 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003323 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Nate Begeman59b5da62009-01-18 03:20:47 +00003325 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003326 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003327
Eli Friedman3edd5a92012-01-03 23:24:20 +00003328 // The number of initializers can be less than the number of
3329 // vector elements. For OpenCL, this can be due to nested vector
3330 // initialization. For GCC compatibility, missing trailing elements
3331 // should be initialized with zeroes.
3332 unsigned CountInits = 0, CountElts = 0;
3333 while (CountElts < NumElements) {
3334 // Handle nested vector initialization.
3335 if (CountInits < NumInits
3336 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3337 APValue v;
3338 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3339 return Error(E);
3340 unsigned vlen = v.getVectorLength();
3341 for (unsigned j = 0; j < vlen; j++)
3342 Elements.push_back(v.getVectorElt(j));
3343 CountElts += vlen;
3344 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003345 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003346 if (CountInits < NumInits) {
3347 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3348 return Error(E);
3349 } else // trailing integer zero.
3350 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3351 Elements.push_back(APValue(sInt));
3352 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003353 } else {
3354 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003355 if (CountInits < NumInits) {
3356 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3357 return Error(E);
3358 } else // trailing float zero.
3359 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3360 Elements.push_back(APValue(f));
3361 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003362 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003363 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003364 }
Richard Smith07fc6572011-10-22 21:10:00 +00003365 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003366}
3367
Richard Smith07fc6572011-10-22 21:10:00 +00003368bool
Richard Smith51201882011-12-30 21:15:51 +00003369VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003370 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003371 QualType EltTy = VT->getElementType();
3372 APValue ZeroElement;
3373 if (EltTy->isIntegerType())
3374 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3375 else
3376 ZeroElement =
3377 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3378
Chris Lattner5f9e2722011-07-23 10:55:15 +00003379 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003380 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003381}
3382
Richard Smith07fc6572011-10-22 21:10:00 +00003383bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003384 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003385 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003386}
3387
Nate Begeman59b5da62009-01-18 03:20:47 +00003388//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003389// Array Evaluation
3390//===----------------------------------------------------------------------===//
3391
3392namespace {
3393 class ArrayExprEvaluator
3394 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003395 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003396 APValue &Result;
3397 public:
3398
Richard Smith180f4792011-11-10 06:34:14 +00003399 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3400 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003401
3402 bool Success(const APValue &V, const Expr *E) {
3403 assert(V.isArray() && "Expected array type");
3404 Result = V;
3405 return true;
3406 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003407
Richard Smith51201882011-12-30 21:15:51 +00003408 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003409 const ConstantArrayType *CAT =
3410 Info.Ctx.getAsConstantArrayType(E->getType());
3411 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003412 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003413
3414 Result = APValue(APValue::UninitArray(), 0,
3415 CAT->getSize().getZExtValue());
3416 if (!Result.hasArrayFiller()) return true;
3417
Richard Smith51201882011-12-30 21:15:51 +00003418 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003419 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003420 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003421 ImplicitValueInitExpr VIE(CAT->getElementType());
3422 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3423 Subobject, &VIE);
3424 }
3425
Richard Smithcc5d4f62011-11-07 09:22:26 +00003426 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003427 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003428 };
3429} // end anonymous namespace
3430
Richard Smith180f4792011-11-10 06:34:14 +00003431static bool EvaluateArray(const Expr *E, const LValue &This,
3432 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003433 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003434 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003435}
3436
3437bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3438 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3439 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003440 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003441
Richard Smith974c5f92011-12-22 01:07:19 +00003442 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3443 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003444 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003445 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3446 LValue LV;
3447 if (!EvaluateLValue(E->getInit(0), LV, Info))
3448 return false;
3449 uint64_t NumElements = CAT->getSize().getZExtValue();
3450 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3451
3452 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003453 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003454 for (uint64_t I = 0; I < NumElements; ++I) {
3455 CCValue Char;
3456 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3457 CAT->getElementType(), LV, Char))
3458 return false;
3459 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3460 Result.getArrayInitializedElt(I)))
3461 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003462 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3463 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003464 return false;
3465 }
3466 return true;
3467 }
3468
Richard Smithcc5d4f62011-11-07 09:22:26 +00003469 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3470 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003471 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003472 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003473 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003474 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003475 I != End; ++I, ++Index) {
3476 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3477 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003478 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003479 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3480 CAT->getElementType(), 1))
Richard Smith180f4792011-11-10 06:34:14 +00003481 return false;
3482 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003483
3484 if (!Result.hasArrayFiller()) return true;
3485 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003486 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3487 // but sometimes does:
3488 // struct S { constexpr S() : p(&p) {} void *p; };
3489 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003490 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003491 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003492}
3493
Richard Smithe24f5fc2011-11-17 22:56:20 +00003494bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3495 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3496 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003497 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003498
Richard Smithec789162012-01-12 18:54:33 +00003499 bool HadZeroInit = !Result.isUninit();
3500 if (!HadZeroInit)
3501 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003502 if (!Result.hasArrayFiller())
3503 return true;
3504
3505 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003506
Richard Smith51201882011-12-30 21:15:51 +00003507 bool ZeroInit = E->requiresZeroInitialization();
3508 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003509 if (HadZeroInit)
3510 return true;
3511
Richard Smith51201882011-12-30 21:15:51 +00003512 if (ZeroInit) {
3513 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003514 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003515 ImplicitValueInitExpr VIE(CAT->getElementType());
3516 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3517 Subobject, &VIE);
3518 }
3519
Richard Smith61802452011-12-22 02:22:31 +00003520 const CXXRecordDecl *RD = FD->getParent();
3521 if (RD->isUnion())
3522 Result.getArrayFiller() = APValue((FieldDecl*)0);
3523 else
3524 Result.getArrayFiller() =
3525 APValue(APValue::UninitStruct(), RD->getNumBases(),
3526 std::distance(RD->field_begin(), RD->field_end()));
3527 return true;
3528 }
3529
Richard Smithe24f5fc2011-11-17 22:56:20 +00003530 const FunctionDecl *Definition = 0;
3531 FD->getBody(Definition);
3532
Richard Smithc1c5f272011-12-13 06:39:58 +00003533 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3534 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003535
3536 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3537 // but sometimes does:
3538 // struct S { constexpr S() : p(&p) {} void *p; };
3539 // S s[10];
3540 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003541 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003542
Richard Smithec789162012-01-12 18:54:33 +00003543 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003544 ImplicitValueInitExpr VIE(CAT->getElementType());
3545 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3546 &VIE))
3547 return false;
3548 }
3549
Richard Smithe24f5fc2011-11-17 22:56:20 +00003550 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003551 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003552 cast<CXXConstructorDecl>(Definition),
3553 Info, Result.getArrayFiller());
3554}
3555
Richard Smithcc5d4f62011-11-07 09:22:26 +00003556//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003557// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003558//
3559// As a GNU extension, we support casting pointers to sufficiently-wide integer
3560// types and back in constant folding. Integer values are thus represented
3561// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003562//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003563
3564namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003565class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003566 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003567 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003568public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003569 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003570 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003571
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003572 bool Success(const llvm::APSInt &SI, const Expr *E) {
3573 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003574 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003575 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003576 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003577 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003578 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003579 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003580 return true;
3581 }
3582
Daniel Dunbar131eb432009-02-19 09:06:44 +00003583 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003584 assert(E->getType()->isIntegralOrEnumerationType() &&
3585 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003586 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003587 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003588 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003589 Result.getInt().setIsUnsigned(
3590 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003591 return true;
3592 }
3593
3594 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003595 assert(E->getType()->isIntegralOrEnumerationType() &&
3596 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003597 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003598 return true;
3599 }
3600
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003601 bool Success(CharUnits Size, const Expr *E) {
3602 return Success(Size.getQuantity(), E);
3603 }
3604
Richard Smith47a1eed2011-10-29 20:57:55 +00003605 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003606 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003607 Result = V;
3608 return true;
3609 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003610 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003611 }
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Richard Smith51201882011-12-30 21:15:51 +00003613 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003614
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003615 //===--------------------------------------------------------------------===//
3616 // Visitor Methods
3617 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003618
Chris Lattner4c4867e2008-07-12 00:38:25 +00003619 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003620 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003621 }
3622 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003623 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003624 }
Eli Friedman04309752009-11-24 05:28:59 +00003625
3626 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3627 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003628 if (CheckReferencedDecl(E, E->getDecl()))
3629 return true;
3630
3631 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003632 }
3633 bool VisitMemberExpr(const MemberExpr *E) {
3634 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003635 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003636 return true;
3637 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003638
3639 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003640 }
3641
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003642 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003643 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003644 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003645 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003646
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003647 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003648 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003649
Anders Carlsson3068d112008-11-16 19:01:22 +00003650 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003651 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003652 }
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Richard Smithf10d9172011-10-11 21:43:33 +00003654 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003655 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003656 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003657 }
3658
Sebastian Redl64b45f72009-01-05 20:52:13 +00003659 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003660 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003661 }
3662
Francois Pichet6ad6f282010-12-07 00:08:36 +00003663 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3664 return Success(E->getValue(), E);
3665 }
3666
John Wiegley21ff2e52011-04-28 00:16:57 +00003667 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3668 return Success(E->getValue(), E);
3669 }
3670
John Wiegley55262202011-04-25 06:54:41 +00003671 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3672 return Success(E->getValue(), E);
3673 }
3674
Eli Friedman722c7172009-02-28 03:59:05 +00003675 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003676 bool VisitUnaryImag(const UnaryOperator *E);
3677
Sebastian Redl295995c2010-09-10 20:55:47 +00003678 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003679 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003680
Chris Lattnerfcee0012008-07-11 21:24:13 +00003681private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003682 CharUnits GetAlignOfExpr(const Expr *E);
3683 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003684 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003685 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003686 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003687};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003688} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003689
Richard Smithc49bd112011-10-28 17:51:58 +00003690/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3691/// produce either the integer value or a pointer.
3692///
3693/// GCC has a heinous extension which folds casts between pointer types and
3694/// pointer-sized integral types. We support this by allowing the evaluation of
3695/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3696/// Some simple arithmetic on such values is supported (they are treated much
3697/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003698static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003699 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003700 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003701 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003702}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003703
Richard Smithf48fdb02011-12-09 22:58:01 +00003704static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003705 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003706 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003707 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003708 if (!Val.isInt()) {
3709 // FIXME: It would be better to produce the diagnostic for casting
3710 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003711 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003712 return false;
3713 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003714 Result = Val.getInt();
3715 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003716}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003717
Richard Smithf48fdb02011-12-09 22:58:01 +00003718/// Check whether the given declaration can be directly converted to an integral
3719/// rvalue. If not, no diagnostic is produced; there are other things we can
3720/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003721bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003722 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003723 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003724 // Check for signedness/width mismatches between E type and ECD value.
3725 bool SameSign = (ECD->getInitVal().isSigned()
3726 == E->getType()->isSignedIntegerOrEnumerationType());
3727 bool SameWidth = (ECD->getInitVal().getBitWidth()
3728 == Info.Ctx.getIntWidth(E->getType()));
3729 if (SameSign && SameWidth)
3730 return Success(ECD->getInitVal(), E);
3731 else {
3732 // Get rid of mismatch (otherwise Success assertions will fail)
3733 // by computing a new value matching the type of E.
3734 llvm::APSInt Val = ECD->getInitVal();
3735 if (!SameSign)
3736 Val.setIsSigned(!ECD->getInitVal().isSigned());
3737 if (!SameWidth)
3738 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3739 return Success(Val, E);
3740 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003741 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003742 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003743}
3744
Chris Lattnera4d55d82008-10-06 06:40:35 +00003745/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3746/// as GCC.
3747static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3748 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003749 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003750 enum gcc_type_class {
3751 no_type_class = -1,
3752 void_type_class, integer_type_class, char_type_class,
3753 enumeral_type_class, boolean_type_class,
3754 pointer_type_class, reference_type_class, offset_type_class,
3755 real_type_class, complex_type_class,
3756 function_type_class, method_type_class,
3757 record_type_class, union_type_class,
3758 array_type_class, string_type_class,
3759 lang_type_class
3760 };
Mike Stump1eb44332009-09-09 15:08:12 +00003761
3762 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003763 // ideal, however it is what gcc does.
3764 if (E->getNumArgs() == 0)
3765 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Chris Lattnera4d55d82008-10-06 06:40:35 +00003767 QualType ArgTy = E->getArg(0)->getType();
3768 if (ArgTy->isVoidType())
3769 return void_type_class;
3770 else if (ArgTy->isEnumeralType())
3771 return enumeral_type_class;
3772 else if (ArgTy->isBooleanType())
3773 return boolean_type_class;
3774 else if (ArgTy->isCharType())
3775 return string_type_class; // gcc doesn't appear to use char_type_class
3776 else if (ArgTy->isIntegerType())
3777 return integer_type_class;
3778 else if (ArgTy->isPointerType())
3779 return pointer_type_class;
3780 else if (ArgTy->isReferenceType())
3781 return reference_type_class;
3782 else if (ArgTy->isRealType())
3783 return real_type_class;
3784 else if (ArgTy->isComplexType())
3785 return complex_type_class;
3786 else if (ArgTy->isFunctionType())
3787 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003788 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003789 return record_type_class;
3790 else if (ArgTy->isUnionType())
3791 return union_type_class;
3792 else if (ArgTy->isArrayType())
3793 return array_type_class;
3794 else if (ArgTy->isUnionType())
3795 return union_type_class;
3796 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003797 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003798}
3799
Richard Smith80d4b552011-12-28 19:48:30 +00003800/// EvaluateBuiltinConstantPForLValue - Determine the result of
3801/// __builtin_constant_p when applied to the given lvalue.
3802///
3803/// An lvalue is only "constant" if it is a pointer or reference to the first
3804/// character of a string literal.
3805template<typename LValue>
3806static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3807 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3808 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3809}
3810
3811/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3812/// GCC as we can manage.
3813static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3814 QualType ArgType = Arg->getType();
3815
3816 // __builtin_constant_p always has one operand. The rules which gcc follows
3817 // are not precisely documented, but are as follows:
3818 //
3819 // - If the operand is of integral, floating, complex or enumeration type,
3820 // and can be folded to a known value of that type, it returns 1.
3821 // - If the operand and can be folded to a pointer to the first character
3822 // of a string literal (or such a pointer cast to an integral type), it
3823 // returns 1.
3824 //
3825 // Otherwise, it returns 0.
3826 //
3827 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3828 // its support for this does not currently work.
3829 if (ArgType->isIntegralOrEnumerationType()) {
3830 Expr::EvalResult Result;
3831 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3832 return false;
3833
3834 APValue &V = Result.Val;
3835 if (V.getKind() == APValue::Int)
3836 return true;
3837
3838 return EvaluateBuiltinConstantPForLValue(V);
3839 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3840 return Arg->isEvaluatable(Ctx);
3841 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3842 LValue LV;
3843 Expr::EvalStatus Status;
3844 EvalInfo Info(Ctx, Status);
3845 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3846 : EvaluatePointer(Arg, LV, Info)) &&
3847 !Status.HasSideEffects)
3848 return EvaluateBuiltinConstantPForLValue(LV);
3849 }
3850
3851 // Anything else isn't considered to be sufficiently constant.
3852 return false;
3853}
3854
John McCall42c8f872010-05-10 23:27:23 +00003855/// Retrieves the "underlying object type" of the given expression,
3856/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003857QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3858 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3859 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003860 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003861 } else if (const Expr *E = B.get<const Expr*>()) {
3862 if (isa<CompoundLiteralExpr>(E))
3863 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003864 }
3865
3866 return QualType();
3867}
3868
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003869bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003870 // TODO: Perhaps we should let LLVM lower this?
3871 LValue Base;
3872 if (!EvaluatePointer(E->getArg(0), Base, Info))
3873 return false;
3874
3875 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003876 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003877
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003878 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003879 if (T.isNull() ||
3880 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003881 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003882 T->isVariablyModifiedType() ||
3883 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003884 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003885
3886 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3887 CharUnits Offset = Base.getLValueOffset();
3888
3889 if (!Offset.isNegative() && Offset <= Size)
3890 Size -= Offset;
3891 else
3892 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003893 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003894}
3895
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003896bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003897 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003898 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003899 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003900
3901 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003902 if (TryEvaluateBuiltinObjectSize(E))
3903 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003904
Eric Christopherb2aaf512010-01-19 22:58:35 +00003905 // If evaluating the argument has side-effects we can't determine
3906 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003907 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003908 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003909 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003910 return Success(0, E);
3911 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003912
Richard Smithf48fdb02011-12-09 22:58:01 +00003913 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003914 }
3915
Chris Lattner019f4e82008-10-06 05:28:25 +00003916 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003917 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Richard Smith80d4b552011-12-28 19:48:30 +00003919 case Builtin::BI__builtin_constant_p:
3920 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00003921
Chris Lattner21fb98e2009-09-23 06:06:36 +00003922 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003923 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003924 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003925 return Success(Operand, E);
3926 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003927
3928 case Builtin::BI__builtin_expect:
3929 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00003930
Douglas Gregor5726d402010-09-10 06:27:15 +00003931 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00003932 // A call to strlen is not a constant expression.
3933 if (Info.getLangOpts().CPlusPlus0x)
3934 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
3935 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
3936 else
3937 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
3938 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00003939 case Builtin::BI__builtin_strlen:
3940 // As an extension, we support strlen() and __builtin_strlen() as constant
3941 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003942 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003943 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3944 // The string literal may have embedded null characters. Find the first
3945 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003946 StringRef Str = S->getString();
3947 StringRef::size_type Pos = Str.find(0);
3948 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003949 Str = Str.substr(0, Pos);
3950
3951 return Success(Str.size(), E);
3952 }
3953
Richard Smithf48fdb02011-12-09 22:58:01 +00003954 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003955
3956 case Builtin::BI__atomic_is_lock_free: {
3957 APSInt SizeVal;
3958 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3959 return false;
3960
3961 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3962 // of two less than the maximum inline atomic width, we know it is
3963 // lock-free. If the size isn't a power of two, or greater than the
3964 // maximum alignment where we promote atomics, we know it is not lock-free
3965 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3966 // the answer can only be determined at runtime; for example, 16-byte
3967 // atomics have lock-free implementations on some, but not all,
3968 // x86-64 processors.
3969
3970 // Check power-of-two.
3971 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3972 if (!Size.isPowerOfTwo())
3973#if 0
3974 // FIXME: Suppress this folding until the ABI for the promotion width
3975 // settles.
3976 return Success(0, E);
3977#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003978 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003979#endif
3980
3981#if 0
3982 // Check against promotion width.
3983 // FIXME: Suppress this folding until the ABI for the promotion width
3984 // settles.
3985 unsigned PromoteWidthBits =
3986 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3987 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3988 return Success(0, E);
3989#endif
3990
3991 // Check against inlining width.
3992 unsigned InlineWidthBits =
3993 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3994 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3995 return Success(1, E);
3996
Richard Smithf48fdb02011-12-09 22:58:01 +00003997 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003998 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003999 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004000}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004001
Richard Smith625b8072011-10-31 01:37:14 +00004002static bool HasSameBase(const LValue &A, const LValue &B) {
4003 if (!A.getLValueBase())
4004 return !B.getLValueBase();
4005 if (!B.getLValueBase())
4006 return false;
4007
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004008 if (A.getLValueBase().getOpaqueValue() !=
4009 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004010 const Decl *ADecl = GetLValueBaseDecl(A);
4011 if (!ADecl)
4012 return false;
4013 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004014 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004015 return false;
4016 }
4017
4018 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004019 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004020}
4021
Chris Lattnerb542afe2008-07-11 19:10:17 +00004022bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004023 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004024 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004025
John McCall2de56d12010-08-25 11:45:40 +00004026 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004027 VisitIgnoredValue(E->getLHS());
4028 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004029 }
4030
4031 if (E->isLogicalOp()) {
4032 // These need to be handled specially because the operands aren't
4033 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004034 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Richard Smithc49bd112011-10-28 17:51:58 +00004036 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004037 // We were able to evaluate the LHS, see if we can get away with not
4038 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004039 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004040 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004041
Richard Smithc49bd112011-10-28 17:51:58 +00004042 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004043 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004044 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004045 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004046 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004047 }
4048 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004049 // FIXME: If both evaluations fail, we should produce the diagnostic from
4050 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4051 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004052 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004053 // We can't evaluate the LHS; however, sometimes the result
4054 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004055 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004056 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004057 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004058 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004059
4060 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004061 }
4062 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004063 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004064
Eli Friedmana6afa762008-11-13 06:09:17 +00004065 return false;
4066 }
4067
Anders Carlsson286f85e2008-11-16 07:17:21 +00004068 QualType LHSTy = E->getLHS()->getType();
4069 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004070
4071 if (LHSTy->isAnyComplexType()) {
4072 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004073 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004074
4075 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4076 return false;
4077
4078 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4079 return false;
4080
4081 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004082 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004083 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004084 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004085 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4086
John McCall2de56d12010-08-25 11:45:40 +00004087 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004088 return Success((CR_r == APFloat::cmpEqual &&
4089 CR_i == APFloat::cmpEqual), E);
4090 else {
John McCall2de56d12010-08-25 11:45:40 +00004091 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004092 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004093 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004094 CR_r == APFloat::cmpLessThan ||
4095 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004096 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004097 CR_i == APFloat::cmpLessThan ||
4098 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004099 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004100 } else {
John McCall2de56d12010-08-25 11:45:40 +00004101 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004102 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4103 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4104 else {
John McCall2de56d12010-08-25 11:45:40 +00004105 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004106 "Invalid compex comparison.");
4107 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4108 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4109 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004110 }
4111 }
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Anders Carlsson286f85e2008-11-16 07:17:21 +00004113 if (LHSTy->isRealFloatingType() &&
4114 RHSTy->isRealFloatingType()) {
4115 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Anders Carlsson286f85e2008-11-16 07:17:21 +00004117 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4118 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Anders Carlsson286f85e2008-11-16 07:17:21 +00004120 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4121 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Anders Carlsson286f85e2008-11-16 07:17:21 +00004123 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004124
Anders Carlsson286f85e2008-11-16 07:17:21 +00004125 switch (E->getOpcode()) {
4126 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004127 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004128 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004129 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004130 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004131 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004132 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004133 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004134 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004135 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004136 E);
John McCall2de56d12010-08-25 11:45:40 +00004137 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004138 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004139 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004140 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004141 || CR == APFloat::cmpLessThan
4142 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004143 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004144 }
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004146 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004147 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00004148 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004149 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4150 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004151
John McCallefdb83e2010-05-07 21:00:08 +00004152 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004153 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4154 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004155
Richard Smith625b8072011-10-31 01:37:14 +00004156 // Reject differing bases from the normal codepath; we special-case
4157 // comparisons to null.
4158 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004159 if (E->getOpcode() == BO_Sub) {
4160 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004161 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4162 return false;
4163 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4164 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4165 if (!LHSExpr || !RHSExpr)
4166 return false;
4167 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4168 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4169 if (!LHSAddrExpr || !RHSAddrExpr)
4170 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004171 // Make sure both labels come from the same function.
4172 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4173 RHSAddrExpr->getLabel()->getDeclContext())
4174 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004175 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4176 return true;
4177 }
Richard Smith9e36b532011-10-31 05:11:32 +00004178 // Inequalities and subtractions between unrelated pointers have
4179 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004180 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004181 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004182 // A constant address may compare equal to the address of a symbol.
4183 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004184 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004185 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4186 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004187 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004188 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004189 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004190 // distinct. However, we do know that the address of a literal will be
4191 // non-null.
4192 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4193 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004194 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004195 // We can't tell whether weak symbols will end up pointing to the same
4196 // object.
4197 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004198 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004199 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004200 // (Note that clang defaults to -fmerge-all-constants, which can
4201 // lead to inconsistent results for comparisons involving the address
4202 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004203 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004204 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004205
Richard Smithcc5d4f62011-11-07 09:22:26 +00004206 // FIXME: Implement the C++11 restrictions:
4207 // - Pointer subtractions must be on elements of the same array.
4208 // - Pointer comparisons must be between members with the same access.
4209
John McCall2de56d12010-08-25 11:45:40 +00004210 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004211 QualType Type = E->getLHS()->getType();
4212 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004213
Richard Smith180f4792011-11-10 06:34:14 +00004214 CharUnits ElementSize;
4215 if (!HandleSizeof(Info, ElementType, ElementSize))
4216 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004217
Richard Smith180f4792011-11-10 06:34:14 +00004218 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004219 RHSValue.getLValueOffset();
4220 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004221 }
Richard Smith625b8072011-10-31 01:37:14 +00004222
4223 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4224 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4225 switch (E->getOpcode()) {
4226 default: llvm_unreachable("missing comparison operator");
4227 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4228 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4229 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4230 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4231 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4232 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004233 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004234 }
4235 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004236 if (!LHSTy->isIntegralOrEnumerationType() ||
4237 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004238 // We can't continue from here for non-integral types.
4239 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004240 }
4241
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004242 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004243 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00004244 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00004245 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004246
Richard Smithc49bd112011-10-28 17:51:58 +00004247 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004248 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004249 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004250
4251 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004252 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004253 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4254 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004255 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004256 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004257 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004258 LHSVal.getLValueOffset() -= AdditionalOffset;
4259 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004260 return true;
4261 }
4262
4263 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004264 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004265 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004266 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4267 LHSVal.getInt().getZExtValue());
4268 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004269 return true;
4270 }
4271
Eli Friedman65639282012-01-04 23:13:47 +00004272 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4273 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004274 if (!LHSVal.getLValueOffset().isZero() ||
4275 !RHSVal.getLValueOffset().isZero())
4276 return false;
4277 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4278 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4279 if (!LHSExpr || !RHSExpr)
4280 return false;
4281 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4282 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4283 if (!LHSAddrExpr || !RHSAddrExpr)
4284 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004285 // Make sure both labels come from the same function.
4286 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4287 RHSAddrExpr->getLabel()->getDeclContext())
4288 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004289 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4290 return true;
4291 }
4292
Eli Friedman42edd0d2009-03-24 01:14:50 +00004293 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004294 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004295 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004296
Richard Smithc49bd112011-10-28 17:51:58 +00004297 APSInt &LHS = LHSVal.getInt();
4298 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004299
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004300 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004301 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004302 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004303 case BO_Mul: return Success(LHS * RHS, E);
4304 case BO_Add: return Success(LHS + RHS, E);
4305 case BO_Sub: return Success(LHS - RHS, E);
4306 case BO_And: return Success(LHS & RHS, E);
4307 case BO_Xor: return Success(LHS ^ RHS, E);
4308 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004309 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004310 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004311 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004312 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004313 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004314 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004315 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004316 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004317 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004318 // During constant-folding, a negative shift is an opposite shift.
4319 if (RHS.isSigned() && RHS.isNegative()) {
4320 RHS = -RHS;
4321 goto shift_right;
4322 }
4323
4324 shift_left:
4325 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004326 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4327 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004328 }
John McCall2de56d12010-08-25 11:45:40 +00004329 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004330 // During constant-folding, a negative shift is an opposite shift.
4331 if (RHS.isSigned() && RHS.isNegative()) {
4332 RHS = -RHS;
4333 goto shift_left;
4334 }
4335
4336 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004337 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004338 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4339 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004340 }
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Richard Smithc49bd112011-10-28 17:51:58 +00004342 case BO_LT: return Success(LHS < RHS, E);
4343 case BO_GT: return Success(LHS > RHS, E);
4344 case BO_LE: return Success(LHS <= RHS, E);
4345 case BO_GE: return Success(LHS >= RHS, E);
4346 case BO_EQ: return Success(LHS == RHS, E);
4347 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004348 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004349}
4350
Ken Dyck8b752f12010-01-27 17:10:57 +00004351CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004352 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4353 // the result is the size of the referenced type."
4354 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4355 // result shall be the alignment of the referenced type."
4356 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4357 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004358
4359 // __alignof is defined to return the preferred alignment.
4360 return Info.Ctx.toCharUnitsFromBits(
4361 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004362}
4363
Ken Dyck8b752f12010-01-27 17:10:57 +00004364CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004365 E = E->IgnoreParens();
4366
4367 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004368 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004369 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004370 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4371 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004372
Chris Lattneraf707ab2009-01-24 21:53:27 +00004373 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004374 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4375 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004376
Chris Lattnere9feb472009-01-24 21:09:06 +00004377 return GetAlignOfType(E->getType());
4378}
4379
4380
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004381/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4382/// a result as the expression's type.
4383bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4384 const UnaryExprOrTypeTraitExpr *E) {
4385 switch(E->getKind()) {
4386 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004387 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004388 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004389 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004390 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004391 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004392
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004393 case UETT_VecStep: {
4394 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004395
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004396 if (Ty->isVectorType()) {
4397 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004398
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004399 // The vec_step built-in functions that take a 3-component
4400 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4401 if (n == 3)
4402 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004403
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004404 return Success(n, E);
4405 } else
4406 return Success(1, E);
4407 }
4408
4409 case UETT_SizeOf: {
4410 QualType SrcTy = E->getTypeOfArgument();
4411 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4412 // the result is the size of the referenced type."
4413 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4414 // result shall be the alignment of the referenced type."
4415 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4416 SrcTy = Ref->getPointeeType();
4417
Richard Smith180f4792011-11-10 06:34:14 +00004418 CharUnits Sizeof;
4419 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004420 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004421 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004422 }
4423 }
4424
4425 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004426}
4427
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004428bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004429 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004430 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004431 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004432 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004433 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004434 for (unsigned i = 0; i != n; ++i) {
4435 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4436 switch (ON.getKind()) {
4437 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004438 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004439 APSInt IdxResult;
4440 if (!EvaluateInteger(Idx, IdxResult, Info))
4441 return false;
4442 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4443 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004444 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004445 CurrentType = AT->getElementType();
4446 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4447 Result += IdxResult.getSExtValue() * ElementSize;
4448 break;
4449 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004450
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004451 case OffsetOfExpr::OffsetOfNode::Field: {
4452 FieldDecl *MemberDecl = ON.getField();
4453 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004454 if (!RT)
4455 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004456 RecordDecl *RD = RT->getDecl();
4457 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004458 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004459 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004460 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004461 CurrentType = MemberDecl->getType().getNonReferenceType();
4462 break;
4463 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004464
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004465 case OffsetOfExpr::OffsetOfNode::Identifier:
4466 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004467
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004468 case OffsetOfExpr::OffsetOfNode::Base: {
4469 CXXBaseSpecifier *BaseSpec = ON.getBase();
4470 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004471 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004472
4473 // Find the layout of the class whose base we are looking into.
4474 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004475 if (!RT)
4476 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004477 RecordDecl *RD = RT->getDecl();
4478 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4479
4480 // Find the base class itself.
4481 CurrentType = BaseSpec->getType();
4482 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4483 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004484 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004485
4486 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004487 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004488 break;
4489 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004490 }
4491 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004492 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004493}
4494
Chris Lattnerb542afe2008-07-11 19:10:17 +00004495bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004496 switch (E->getOpcode()) {
4497 default:
4498 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4499 // See C99 6.6p3.
4500 return Error(E);
4501 case UO_Extension:
4502 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4503 // If so, we could clear the diagnostic ID.
4504 return Visit(E->getSubExpr());
4505 case UO_Plus:
4506 // The result is just the value.
4507 return Visit(E->getSubExpr());
4508 case UO_Minus: {
4509 if (!Visit(E->getSubExpr()))
4510 return false;
4511 if (!Result.isInt()) return Error(E);
4512 return Success(-Result.getInt(), E);
4513 }
4514 case UO_Not: {
4515 if (!Visit(E->getSubExpr()))
4516 return false;
4517 if (!Result.isInt()) return Error(E);
4518 return Success(~Result.getInt(), E);
4519 }
4520 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004521 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004522 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004523 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004524 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004525 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004526 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004527}
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Chris Lattner732b2232008-07-12 01:15:53 +00004529/// HandleCast - This is used to evaluate implicit or explicit casts where the
4530/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004531bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4532 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004533 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004534 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004535
Eli Friedman46a52322011-03-25 00:43:55 +00004536 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004537 case CK_BaseToDerived:
4538 case CK_DerivedToBase:
4539 case CK_UncheckedDerivedToBase:
4540 case CK_Dynamic:
4541 case CK_ToUnion:
4542 case CK_ArrayToPointerDecay:
4543 case CK_FunctionToPointerDecay:
4544 case CK_NullToPointer:
4545 case CK_NullToMemberPointer:
4546 case CK_BaseToDerivedMemberPointer:
4547 case CK_DerivedToBaseMemberPointer:
4548 case CK_ConstructorConversion:
4549 case CK_IntegralToPointer:
4550 case CK_ToVoid:
4551 case CK_VectorSplat:
4552 case CK_IntegralToFloating:
4553 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004554 case CK_CPointerToObjCPointerCast:
4555 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004556 case CK_AnyPointerToBlockPointerCast:
4557 case CK_ObjCObjectLValueCast:
4558 case CK_FloatingRealToComplex:
4559 case CK_FloatingComplexToReal:
4560 case CK_FloatingComplexCast:
4561 case CK_FloatingComplexToIntegralComplex:
4562 case CK_IntegralRealToComplex:
4563 case CK_IntegralComplexCast:
4564 case CK_IntegralComplexToFloatingComplex:
4565 llvm_unreachable("invalid cast kind for integral value");
4566
Eli Friedmane50c2972011-03-25 19:07:11 +00004567 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004568 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004569 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004570 case CK_ARCProduceObject:
4571 case CK_ARCConsumeObject:
4572 case CK_ARCReclaimReturnedObject:
4573 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004574 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004575
Richard Smith7d580a42012-01-17 21:17:26 +00004576 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004577 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004578 case CK_AtomicToNonAtomic:
4579 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004580 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004581 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004582
4583 case CK_MemberPointerToBoolean:
4584 case CK_PointerToBoolean:
4585 case CK_IntegralToBoolean:
4586 case CK_FloatingToBoolean:
4587 case CK_FloatingComplexToBoolean:
4588 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004589 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004590 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004591 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004592 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004593 }
4594
Eli Friedman46a52322011-03-25 00:43:55 +00004595 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004596 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004597 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004598
Eli Friedmanbe265702009-02-20 01:15:07 +00004599 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004600 // Allow casts of address-of-label differences if they are no-ops
4601 // or narrowing. (The narrowing case isn't actually guaranteed to
4602 // be constant-evaluatable except in some narrow cases which are hard
4603 // to detect here. We let it through on the assumption the user knows
4604 // what they are doing.)
4605 if (Result.isAddrLabelDiff())
4606 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004607 // Only allow casts of lvalues if they are lossless.
4608 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4609 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004610
Daniel Dunbardd211642009-02-19 22:24:01 +00004611 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004612 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004613 }
Mike Stump1eb44332009-09-09 15:08:12 +00004614
Eli Friedman46a52322011-03-25 00:43:55 +00004615 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004616 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4617
John McCallefdb83e2010-05-07 21:00:08 +00004618 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004619 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004620 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004621
Daniel Dunbardd211642009-02-19 22:24:01 +00004622 if (LV.getLValueBase()) {
4623 // Only allow based lvalue casts if they are lossless.
4624 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004625 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004626
Richard Smithb755a9d2011-11-16 07:18:12 +00004627 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004628 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004629 return true;
4630 }
4631
Ken Dycka7305832010-01-15 12:37:54 +00004632 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4633 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004634 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004635 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004636
Eli Friedman46a52322011-03-25 00:43:55 +00004637 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004638 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004639 if (!EvaluateComplex(SubExpr, C, Info))
4640 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004641 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004642 }
Eli Friedman2217c872009-02-22 11:46:18 +00004643
Eli Friedman46a52322011-03-25 00:43:55 +00004644 case CK_FloatingToIntegral: {
4645 APFloat F(0.0);
4646 if (!EvaluateFloat(SubExpr, F, Info))
4647 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004648
Richard Smithc1c5f272011-12-13 06:39:58 +00004649 APSInt Value;
4650 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4651 return false;
4652 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004653 }
4654 }
Mike Stump1eb44332009-09-09 15:08:12 +00004655
Eli Friedman46a52322011-03-25 00:43:55 +00004656 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004657}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004658
Eli Friedman722c7172009-02-28 03:59:05 +00004659bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4660 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004661 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004662 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4663 return false;
4664 if (!LV.isComplexInt())
4665 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004666 return Success(LV.getComplexIntReal(), E);
4667 }
4668
4669 return Visit(E->getSubExpr());
4670}
4671
Eli Friedman664a1042009-02-27 04:45:43 +00004672bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004673 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004674 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004675 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4676 return false;
4677 if (!LV.isComplexInt())
4678 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004679 return Success(LV.getComplexIntImag(), E);
4680 }
4681
Richard Smith8327fad2011-10-24 18:44:57 +00004682 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004683 return Success(0, E);
4684}
4685
Douglas Gregoree8aff02011-01-04 17:33:58 +00004686bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4687 return Success(E->getPackLength(), E);
4688}
4689
Sebastian Redl295995c2010-09-10 20:55:47 +00004690bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4691 return Success(E->getValue(), E);
4692}
4693
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004694//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004695// Float Evaluation
4696//===----------------------------------------------------------------------===//
4697
4698namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004699class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004700 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004701 APFloat &Result;
4702public:
4703 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004704 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004705
Richard Smith47a1eed2011-10-29 20:57:55 +00004706 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004707 Result = V.getFloat();
4708 return true;
4709 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004710
Richard Smith51201882011-12-30 21:15:51 +00004711 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004712 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4713 return true;
4714 }
4715
Chris Lattner019f4e82008-10-06 05:28:25 +00004716 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004717
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004718 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004719 bool VisitBinaryOperator(const BinaryOperator *E);
4720 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004721 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004722
John McCallabd3a852010-05-07 22:08:54 +00004723 bool VisitUnaryReal(const UnaryOperator *E);
4724 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004725
Richard Smith51201882011-12-30 21:15:51 +00004726 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004727};
4728} // end anonymous namespace
4729
4730static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004731 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004732 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004733}
4734
Jay Foad4ba2a172011-01-12 09:06:06 +00004735static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004736 QualType ResultTy,
4737 const Expr *Arg,
4738 bool SNaN,
4739 llvm::APFloat &Result) {
4740 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4741 if (!S) return false;
4742
4743 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4744
4745 llvm::APInt fill;
4746
4747 // Treat empty strings as if they were zero.
4748 if (S->getString().empty())
4749 fill = llvm::APInt(32, 0);
4750 else if (S->getString().getAsInteger(0, fill))
4751 return false;
4752
4753 if (SNaN)
4754 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4755 else
4756 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4757 return true;
4758}
4759
Chris Lattner019f4e82008-10-06 05:28:25 +00004760bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004761 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004762 default:
4763 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4764
Chris Lattner019f4e82008-10-06 05:28:25 +00004765 case Builtin::BI__builtin_huge_val:
4766 case Builtin::BI__builtin_huge_valf:
4767 case Builtin::BI__builtin_huge_vall:
4768 case Builtin::BI__builtin_inf:
4769 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004770 case Builtin::BI__builtin_infl: {
4771 const llvm::fltSemantics &Sem =
4772 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004773 Result = llvm::APFloat::getInf(Sem);
4774 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004775 }
Mike Stump1eb44332009-09-09 15:08:12 +00004776
John McCalldb7b72a2010-02-28 13:00:19 +00004777 case Builtin::BI__builtin_nans:
4778 case Builtin::BI__builtin_nansf:
4779 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004780 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4781 true, Result))
4782 return Error(E);
4783 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004784
Chris Lattner9e621712008-10-06 06:31:58 +00004785 case Builtin::BI__builtin_nan:
4786 case Builtin::BI__builtin_nanf:
4787 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004788 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004789 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004790 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4791 false, Result))
4792 return Error(E);
4793 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004794
4795 case Builtin::BI__builtin_fabs:
4796 case Builtin::BI__builtin_fabsf:
4797 case Builtin::BI__builtin_fabsl:
4798 if (!EvaluateFloat(E->getArg(0), Result, Info))
4799 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004800
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004801 if (Result.isNegative())
4802 Result.changeSign();
4803 return true;
4804
Mike Stump1eb44332009-09-09 15:08:12 +00004805 case Builtin::BI__builtin_copysign:
4806 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004807 case Builtin::BI__builtin_copysignl: {
4808 APFloat RHS(0.);
4809 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4810 !EvaluateFloat(E->getArg(1), RHS, Info))
4811 return false;
4812 Result.copySign(RHS);
4813 return true;
4814 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004815 }
4816}
4817
John McCallabd3a852010-05-07 22:08:54 +00004818bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004819 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4820 ComplexValue CV;
4821 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4822 return false;
4823 Result = CV.FloatReal;
4824 return true;
4825 }
4826
4827 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004828}
4829
4830bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004831 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4832 ComplexValue CV;
4833 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4834 return false;
4835 Result = CV.FloatImag;
4836 return true;
4837 }
4838
Richard Smith8327fad2011-10-24 18:44:57 +00004839 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004840 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4841 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004842 return true;
4843}
4844
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004845bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004846 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004847 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004848 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004849 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004850 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004851 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4852 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004853 Result.changeSign();
4854 return true;
4855 }
4856}
Chris Lattner019f4e82008-10-06 05:28:25 +00004857
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004858bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004859 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4860 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004861
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004862 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004863 if (!EvaluateFloat(E->getLHS(), Result, Info))
4864 return false;
4865 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4866 return false;
4867
4868 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004869 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004870 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004871 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4872 return true;
John McCall2de56d12010-08-25 11:45:40 +00004873 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004874 Result.add(RHS, APFloat::rmNearestTiesToEven);
4875 return true;
John McCall2de56d12010-08-25 11:45:40 +00004876 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004877 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4878 return true;
John McCall2de56d12010-08-25 11:45:40 +00004879 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004880 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4881 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004882 }
4883}
4884
4885bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4886 Result = E->getValue();
4887 return true;
4888}
4889
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004890bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4891 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004892
Eli Friedman2a523ee2011-03-25 00:54:52 +00004893 switch (E->getCastKind()) {
4894 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004895 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004896
4897 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004898 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004899 return EvaluateInteger(SubExpr, IntResult, Info) &&
4900 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4901 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004902 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004903
4904 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004905 if (!Visit(SubExpr))
4906 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004907 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4908 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004909 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004910
Eli Friedman2a523ee2011-03-25 00:54:52 +00004911 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004912 ComplexValue V;
4913 if (!EvaluateComplex(SubExpr, V, Info))
4914 return false;
4915 Result = V.getComplexFloatReal();
4916 return true;
4917 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004918 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004919}
4920
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004921//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004922// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004923//===----------------------------------------------------------------------===//
4924
4925namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004926class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004927 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004928 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004930public:
John McCallf4cf1a12010-05-07 17:22:02 +00004931 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004932 : ExprEvaluatorBaseTy(info), Result(Result) {}
4933
Richard Smith47a1eed2011-10-29 20:57:55 +00004934 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004935 Result.setFrom(V);
4936 return true;
4937 }
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Eli Friedman7ead5c72012-01-10 04:58:17 +00004939 bool ZeroInitialization(const Expr *E);
4940
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004941 //===--------------------------------------------------------------------===//
4942 // Visitor Methods
4943 //===--------------------------------------------------------------------===//
4944
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004945 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004946 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00004947 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004948 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00004949 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004950};
4951} // end anonymous namespace
4952
John McCallf4cf1a12010-05-07 17:22:02 +00004953static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4954 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004955 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004956 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004957}
4958
Eli Friedman7ead5c72012-01-10 04:58:17 +00004959bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00004960 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00004961 if (ElemTy->isRealFloatingType()) {
4962 Result.makeComplexFloat();
4963 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
4964 Result.FloatReal = Zero;
4965 Result.FloatImag = Zero;
4966 } else {
4967 Result.makeComplexInt();
4968 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
4969 Result.IntReal = Zero;
4970 Result.IntImag = Zero;
4971 }
4972 return true;
4973}
4974
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004975bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4976 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004977
4978 if (SubExpr->getType()->isRealFloatingType()) {
4979 Result.makeComplexFloat();
4980 APFloat &Imag = Result.FloatImag;
4981 if (!EvaluateFloat(SubExpr, Imag, Info))
4982 return false;
4983
4984 Result.FloatReal = APFloat(Imag.getSemantics());
4985 return true;
4986 } else {
4987 assert(SubExpr->getType()->isIntegerType() &&
4988 "Unexpected imaginary literal.");
4989
4990 Result.makeComplexInt();
4991 APSInt &Imag = Result.IntImag;
4992 if (!EvaluateInteger(SubExpr, Imag, Info))
4993 return false;
4994
4995 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4996 return true;
4997 }
4998}
4999
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005000bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005001
John McCall8786da72010-12-14 17:51:41 +00005002 switch (E->getCastKind()) {
5003 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005004 case CK_BaseToDerived:
5005 case CK_DerivedToBase:
5006 case CK_UncheckedDerivedToBase:
5007 case CK_Dynamic:
5008 case CK_ToUnion:
5009 case CK_ArrayToPointerDecay:
5010 case CK_FunctionToPointerDecay:
5011 case CK_NullToPointer:
5012 case CK_NullToMemberPointer:
5013 case CK_BaseToDerivedMemberPointer:
5014 case CK_DerivedToBaseMemberPointer:
5015 case CK_MemberPointerToBoolean:
5016 case CK_ConstructorConversion:
5017 case CK_IntegralToPointer:
5018 case CK_PointerToIntegral:
5019 case CK_PointerToBoolean:
5020 case CK_ToVoid:
5021 case CK_VectorSplat:
5022 case CK_IntegralCast:
5023 case CK_IntegralToBoolean:
5024 case CK_IntegralToFloating:
5025 case CK_FloatingToIntegral:
5026 case CK_FloatingToBoolean:
5027 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005028 case CK_CPointerToObjCPointerCast:
5029 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005030 case CK_AnyPointerToBlockPointerCast:
5031 case CK_ObjCObjectLValueCast:
5032 case CK_FloatingComplexToReal:
5033 case CK_FloatingComplexToBoolean:
5034 case CK_IntegralComplexToReal:
5035 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005036 case CK_ARCProduceObject:
5037 case CK_ARCConsumeObject:
5038 case CK_ARCReclaimReturnedObject:
5039 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005040 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005041
John McCall8786da72010-12-14 17:51:41 +00005042 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005043 case CK_AtomicToNonAtomic:
5044 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005045 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005046 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005047
5048 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005049 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005050 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005051 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005052
5053 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005054 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005055 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005056 return false;
5057
John McCall8786da72010-12-14 17:51:41 +00005058 Result.makeComplexFloat();
5059 Result.FloatImag = APFloat(Real.getSemantics());
5060 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005061 }
5062
John McCall8786da72010-12-14 17:51:41 +00005063 case CK_FloatingComplexCast: {
5064 if (!Visit(E->getSubExpr()))
5065 return false;
5066
5067 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5068 QualType From
5069 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5070
Richard Smithc1c5f272011-12-13 06:39:58 +00005071 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5072 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005073 }
5074
5075 case CK_FloatingComplexToIntegralComplex: {
5076 if (!Visit(E->getSubExpr()))
5077 return false;
5078
5079 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5080 QualType From
5081 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5082 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005083 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5084 To, Result.IntReal) &&
5085 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5086 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005087 }
5088
5089 case CK_IntegralRealToComplex: {
5090 APSInt &Real = Result.IntReal;
5091 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5092 return false;
5093
5094 Result.makeComplexInt();
5095 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5096 return true;
5097 }
5098
5099 case CK_IntegralComplexCast: {
5100 if (!Visit(E->getSubExpr()))
5101 return false;
5102
5103 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5104 QualType From
5105 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5106
5107 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5108 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5109 return true;
5110 }
5111
5112 case CK_IntegralComplexToFloatingComplex: {
5113 if (!Visit(E->getSubExpr()))
5114 return false;
5115
5116 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5117 QualType From
5118 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5119 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005120 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5121 To, Result.FloatReal) &&
5122 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5123 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005124 }
5125 }
5126
5127 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005128}
5129
John McCallf4cf1a12010-05-07 17:22:02 +00005130bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005131 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005132 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5133
John McCallf4cf1a12010-05-07 17:22:02 +00005134 if (!Visit(E->getLHS()))
5135 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005136
John McCallf4cf1a12010-05-07 17:22:02 +00005137 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005138 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00005139 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005140
Daniel Dunbar3f279872009-01-29 01:32:56 +00005141 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5142 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005143 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005144 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005145 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005146 if (Result.isComplexFloat()) {
5147 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5148 APFloat::rmNearestTiesToEven);
5149 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5150 APFloat::rmNearestTiesToEven);
5151 } else {
5152 Result.getComplexIntReal() += RHS.getComplexIntReal();
5153 Result.getComplexIntImag() += RHS.getComplexIntImag();
5154 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005155 break;
John McCall2de56d12010-08-25 11:45:40 +00005156 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005157 if (Result.isComplexFloat()) {
5158 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5159 APFloat::rmNearestTiesToEven);
5160 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5161 APFloat::rmNearestTiesToEven);
5162 } else {
5163 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5164 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5165 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005166 break;
John McCall2de56d12010-08-25 11:45:40 +00005167 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005168 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005169 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005170 APFloat &LHS_r = LHS.getComplexFloatReal();
5171 APFloat &LHS_i = LHS.getComplexFloatImag();
5172 APFloat &RHS_r = RHS.getComplexFloatReal();
5173 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005174
Daniel Dunbar3f279872009-01-29 01:32:56 +00005175 APFloat Tmp = LHS_r;
5176 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5177 Result.getComplexFloatReal() = Tmp;
5178 Tmp = LHS_i;
5179 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5180 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5181
5182 Tmp = LHS_r;
5183 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5184 Result.getComplexFloatImag() = Tmp;
5185 Tmp = LHS_i;
5186 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5187 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5188 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005189 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005190 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005191 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5192 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005193 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005194 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5195 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5196 }
5197 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005198 case BO_Div:
5199 if (Result.isComplexFloat()) {
5200 ComplexValue LHS = Result;
5201 APFloat &LHS_r = LHS.getComplexFloatReal();
5202 APFloat &LHS_i = LHS.getComplexFloatImag();
5203 APFloat &RHS_r = RHS.getComplexFloatReal();
5204 APFloat &RHS_i = RHS.getComplexFloatImag();
5205 APFloat &Res_r = Result.getComplexFloatReal();
5206 APFloat &Res_i = Result.getComplexFloatImag();
5207
5208 APFloat Den = RHS_r;
5209 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5210 APFloat Tmp = RHS_i;
5211 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5212 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5213
5214 Res_r = LHS_r;
5215 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5216 Tmp = LHS_i;
5217 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5218 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5219 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5220
5221 Res_i = LHS_i;
5222 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5223 Tmp = LHS_r;
5224 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5225 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5226 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5227 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005228 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5229 return Error(E, diag::note_expr_divide_by_zero);
5230
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005231 ComplexValue LHS = Result;
5232 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5233 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5234 Result.getComplexIntReal() =
5235 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5236 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5237 Result.getComplexIntImag() =
5238 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5239 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5240 }
5241 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005242 }
5243
John McCallf4cf1a12010-05-07 17:22:02 +00005244 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005245}
5246
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005247bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5248 // Get the operand value into 'Result'.
5249 if (!Visit(E->getSubExpr()))
5250 return false;
5251
5252 switch (E->getOpcode()) {
5253 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005254 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005255 case UO_Extension:
5256 return true;
5257 case UO_Plus:
5258 // The result is always just the subexpr.
5259 return true;
5260 case UO_Minus:
5261 if (Result.isComplexFloat()) {
5262 Result.getComplexFloatReal().changeSign();
5263 Result.getComplexFloatImag().changeSign();
5264 }
5265 else {
5266 Result.getComplexIntReal() = -Result.getComplexIntReal();
5267 Result.getComplexIntImag() = -Result.getComplexIntImag();
5268 }
5269 return true;
5270 case UO_Not:
5271 if (Result.isComplexFloat())
5272 Result.getComplexFloatImag().changeSign();
5273 else
5274 Result.getComplexIntImag() = -Result.getComplexIntImag();
5275 return true;
5276 }
5277}
5278
Eli Friedman7ead5c72012-01-10 04:58:17 +00005279bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5280 if (E->getNumInits() == 2) {
5281 if (E->getType()->isComplexType()) {
5282 Result.makeComplexFloat();
5283 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5284 return false;
5285 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5286 return false;
5287 } else {
5288 Result.makeComplexInt();
5289 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5290 return false;
5291 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5292 return false;
5293 }
5294 return true;
5295 }
5296 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5297}
5298
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005299//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005300// Void expression evaluation, primarily for a cast to void on the LHS of a
5301// comma operator
5302//===----------------------------------------------------------------------===//
5303
5304namespace {
5305class VoidExprEvaluator
5306 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5307public:
5308 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5309
5310 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005311
5312 bool VisitCastExpr(const CastExpr *E) {
5313 switch (E->getCastKind()) {
5314 default:
5315 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5316 case CK_ToVoid:
5317 VisitIgnoredValue(E->getSubExpr());
5318 return true;
5319 }
5320 }
5321};
5322} // end anonymous namespace
5323
5324static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5325 assert(E->isRValue() && E->getType()->isVoidType());
5326 return VoidExprEvaluator(Info).Visit(E);
5327}
5328
5329//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005330// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005331//===----------------------------------------------------------------------===//
5332
Richard Smith47a1eed2011-10-29 20:57:55 +00005333static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005334 // In C, function designators are not lvalues, but we evaluate them as if they
5335 // are.
5336 if (E->isGLValue() || E->getType()->isFunctionType()) {
5337 LValue LV;
5338 if (!EvaluateLValue(E, LV, Info))
5339 return false;
5340 LV.moveInto(Result);
5341 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005342 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005343 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005344 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005345 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005346 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005347 } else if (E->getType()->hasPointerRepresentation()) {
5348 LValue LV;
5349 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005350 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005351 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005352 } else if (E->getType()->isRealFloatingType()) {
5353 llvm::APFloat F(0.0);
5354 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005355 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005356 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005357 } else if (E->getType()->isAnyComplexType()) {
5358 ComplexValue C;
5359 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005360 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005361 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005362 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005363 MemberPtr P;
5364 if (!EvaluateMemberPointer(E, P, Info))
5365 return false;
5366 P.moveInto(Result);
5367 return true;
Richard Smith51201882011-12-30 21:15:51 +00005368 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005369 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005370 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005371 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005372 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005373 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005374 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005375 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005376 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005377 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5378 return false;
5379 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005380 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005381 if (Info.getLangOpts().CPlusPlus0x)
5382 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5383 << E->getType();
5384 else
5385 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005386 if (!EvaluateVoid(E, Info))
5387 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005388 } else if (Info.getLangOpts().CPlusPlus0x) {
5389 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5390 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005391 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005392 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005393 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005394 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005395
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005396 return true;
5397}
5398
Richard Smith69c2c502011-11-04 05:33:44 +00005399/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5400/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5401/// since later initializers for an object can indirectly refer to subobjects
5402/// which were initialized earlier.
5403static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005404 const LValue &This, const Expr *E,
5405 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005406 if (!CheckLiteralType(Info, E))
5407 return false;
5408
5409 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005410 // Evaluate arrays and record types in-place, so that later initializers can
5411 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005412 if (E->getType()->isArrayType())
5413 return EvaluateArray(E, This, Result, Info);
5414 else if (E->getType()->isRecordType())
5415 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005416 }
5417
5418 // For any other type, in-place evaluation is unimportant.
5419 CCValue CoreConstResult;
5420 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005421 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005422}
5423
Richard Smithf48fdb02011-12-09 22:58:01 +00005424/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5425/// lvalue-to-rvalue cast if it is an lvalue.
5426static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005427 if (!CheckLiteralType(Info, E))
5428 return false;
5429
Richard Smithf48fdb02011-12-09 22:58:01 +00005430 CCValue Value;
5431 if (!::Evaluate(Value, Info, E))
5432 return false;
5433
5434 if (E->isGLValue()) {
5435 LValue LV;
5436 LV.setFrom(Value);
5437 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5438 return false;
5439 }
5440
5441 // Check this core constant expression is a constant expression, and if so,
5442 // convert it to one.
5443 return CheckConstantExpression(Info, E, Value, Result);
5444}
Richard Smithc49bd112011-10-28 17:51:58 +00005445
Richard Smith51f47082011-10-29 00:50:52 +00005446/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005447/// any crazy technique (that has nothing to do with language standards) that
5448/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005449/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5450/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005451bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005452 // Fast-path evaluations of integer literals, since we sometimes see files
5453 // containing vast quantities of these.
5454 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5455 Result.Val = APValue(APSInt(L->getValue(),
5456 L->getType()->isUnsignedIntegerType()));
5457 return true;
5458 }
5459
Richard Smith2d6a5672012-01-14 04:30:29 +00005460 // FIXME: Evaluating values of large array and record types can cause
5461 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005462 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5463 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005464 return false;
5465
Richard Smithf48fdb02011-12-09 22:58:01 +00005466 EvalInfo Info(Ctx, Result);
5467 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005468}
5469
Jay Foad4ba2a172011-01-12 09:06:06 +00005470bool Expr::EvaluateAsBooleanCondition(bool &Result,
5471 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005472 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005473 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005474 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5475 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005476 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005477}
5478
Richard Smith80d4b552011-12-28 19:48:30 +00005479bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5480 SideEffectsKind AllowSideEffects) const {
5481 if (!getType()->isIntegralOrEnumerationType())
5482 return false;
5483
Richard Smithc49bd112011-10-28 17:51:58 +00005484 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005485 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5486 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005487 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005488
Richard Smithc49bd112011-10-28 17:51:58 +00005489 Result = ExprResult.Val.getInt();
5490 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005491}
5492
Jay Foad4ba2a172011-01-12 09:06:06 +00005493bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005494 EvalInfo Info(Ctx, Result);
5495
John McCallefdb83e2010-05-07 21:00:08 +00005496 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005497 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005498 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5499 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005500}
5501
Richard Smith099e7f62011-12-19 06:19:21 +00005502bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5503 const VarDecl *VD,
5504 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005505 // FIXME: Evaluating initializers for large array and record types can cause
5506 // performance problems. Only do so in C++11 for now.
5507 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5508 !Ctx.getLangOptions().CPlusPlus0x)
5509 return false;
5510
Richard Smith099e7f62011-12-19 06:19:21 +00005511 Expr::EvalStatus EStatus;
5512 EStatus.Diag = &Notes;
5513
5514 EvalInfo InitInfo(Ctx, EStatus);
5515 InitInfo.setEvaluatingDecl(VD, Value);
5516
Richard Smith51201882011-12-30 21:15:51 +00005517 if (!CheckLiteralType(InitInfo, this))
5518 return false;
5519
Richard Smith099e7f62011-12-19 06:19:21 +00005520 LValue LVal;
5521 LVal.set(VD);
5522
Richard Smith51201882011-12-30 21:15:51 +00005523 // C++11 [basic.start.init]p2:
5524 // Variables with static storage duration or thread storage duration shall be
5525 // zero-initialized before any other initialization takes place.
5526 // This behavior is not present in C.
5527 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5528 !VD->getType()->isReferenceType()) {
5529 ImplicitValueInitExpr VIE(VD->getType());
5530 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5531 return false;
5532 }
5533
Richard Smith099e7f62011-12-19 06:19:21 +00005534 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5535 !EStatus.HasSideEffects;
5536}
5537
Richard Smith51f47082011-10-29 00:50:52 +00005538/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5539/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005540bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005541 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005542 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005543}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005544
Jay Foad4ba2a172011-01-12 09:06:06 +00005545bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005546 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005547}
5548
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005549APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005550 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005551 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005552 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005553 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005554 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005555
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005556 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005557}
John McCalld905f5a2010-05-07 05:32:02 +00005558
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005559 bool Expr::EvalResult::isGlobalLValue() const {
5560 assert(Val.isLValue());
5561 return IsGlobalLValue(Val.getLValueBase());
5562 }
5563
5564
John McCalld905f5a2010-05-07 05:32:02 +00005565/// isIntegerConstantExpr - this recursive routine will test if an expression is
5566/// an integer constant expression.
5567
5568/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5569/// comma, etc
5570///
5571/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5572/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5573/// cast+dereference.
5574
5575// CheckICE - This function does the fundamental ICE checking: the returned
5576// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5577// Note that to reduce code duplication, this helper does no evaluation
5578// itself; the caller checks whether the expression is evaluatable, and
5579// in the rare cases where CheckICE actually cares about the evaluated
5580// value, it calls into Evalute.
5581//
5582// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005583// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005584// 1: This expression is not an ICE, but if it isn't evaluated, it's
5585// a legal subexpression for an ICE. This return value is used to handle
5586// the comma operator in C99 mode.
5587// 2: This expression is not an ICE, and is not a legal subexpression for one.
5588
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005589namespace {
5590
John McCalld905f5a2010-05-07 05:32:02 +00005591struct ICEDiag {
5592 unsigned Val;
5593 SourceLocation Loc;
5594
5595 public:
5596 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5597 ICEDiag() : Val(0) {}
5598};
5599
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005600}
5601
5602static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005603
5604static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5605 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005606 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005607 !EVResult.Val.isInt()) {
5608 return ICEDiag(2, E->getLocStart());
5609 }
5610 return NoDiag();
5611}
5612
5613static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5614 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005615 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005616 return ICEDiag(2, E->getLocStart());
5617 }
5618
5619 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005620#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005621#define STMT(Node, Base) case Expr::Node##Class:
5622#define EXPR(Node, Base)
5623#include "clang/AST/StmtNodes.inc"
5624 case Expr::PredefinedExprClass:
5625 case Expr::FloatingLiteralClass:
5626 case Expr::ImaginaryLiteralClass:
5627 case Expr::StringLiteralClass:
5628 case Expr::ArraySubscriptExprClass:
5629 case Expr::MemberExprClass:
5630 case Expr::CompoundAssignOperatorClass:
5631 case Expr::CompoundLiteralExprClass:
5632 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005633 case Expr::DesignatedInitExprClass:
5634 case Expr::ImplicitValueInitExprClass:
5635 case Expr::ParenListExprClass:
5636 case Expr::VAArgExprClass:
5637 case Expr::AddrLabelExprClass:
5638 case Expr::StmtExprClass:
5639 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005640 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005641 case Expr::CXXDynamicCastExprClass:
5642 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005643 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005644 case Expr::CXXNullPtrLiteralExprClass:
5645 case Expr::CXXThisExprClass:
5646 case Expr::CXXThrowExprClass:
5647 case Expr::CXXNewExprClass:
5648 case Expr::CXXDeleteExprClass:
5649 case Expr::CXXPseudoDestructorExprClass:
5650 case Expr::UnresolvedLookupExprClass:
5651 case Expr::DependentScopeDeclRefExprClass:
5652 case Expr::CXXConstructExprClass:
5653 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005654 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005655 case Expr::CXXTemporaryObjectExprClass:
5656 case Expr::CXXUnresolvedConstructExprClass:
5657 case Expr::CXXDependentScopeMemberExprClass:
5658 case Expr::UnresolvedMemberExprClass:
5659 case Expr::ObjCStringLiteralClass:
5660 case Expr::ObjCEncodeExprClass:
5661 case Expr::ObjCMessageExprClass:
5662 case Expr::ObjCSelectorExprClass:
5663 case Expr::ObjCProtocolExprClass:
5664 case Expr::ObjCIvarRefExprClass:
5665 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005666 case Expr::ObjCIsaExprClass:
5667 case Expr::ShuffleVectorExprClass:
5668 case Expr::BlockExprClass:
5669 case Expr::BlockDeclRefExprClass:
5670 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005671 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005672 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005673 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005674 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005675 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005676 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005677 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005678 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005679 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005680 return ICEDiag(2, E->getLocStart());
5681
Douglas Gregoree8aff02011-01-04 17:33:58 +00005682 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005683 case Expr::GNUNullExprClass:
5684 // GCC considers the GNU __null value to be an integral constant expression.
5685 return NoDiag();
5686
John McCall91a57552011-07-15 05:09:51 +00005687 case Expr::SubstNonTypeTemplateParmExprClass:
5688 return
5689 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5690
John McCalld905f5a2010-05-07 05:32:02 +00005691 case Expr::ParenExprClass:
5692 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005693 case Expr::GenericSelectionExprClass:
5694 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005695 case Expr::IntegerLiteralClass:
5696 case Expr::CharacterLiteralClass:
5697 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005698 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005699 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005700 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005701 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005702 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005703 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005704 return NoDiag();
5705 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005706 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005707 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5708 // constant expressions, but they can never be ICEs because an ICE cannot
5709 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005710 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005711 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005712 return CheckEvalInICE(E, Ctx);
5713 return ICEDiag(2, E->getLocStart());
5714 }
5715 case Expr::DeclRefExprClass:
5716 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5717 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005718 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005719 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5720
5721 // Parameter variables are never constants. Without this check,
5722 // getAnyInitializer() can find a default argument, which leads
5723 // to chaos.
5724 if (isa<ParmVarDecl>(D))
5725 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5726
5727 // C++ 7.1.5.1p2
5728 // A variable of non-volatile const-qualified integral or enumeration
5729 // type initialized by an ICE can be used in ICEs.
5730 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005731 if (!Dcl->getType()->isIntegralOrEnumerationType())
5732 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5733
Richard Smith099e7f62011-12-19 06:19:21 +00005734 const VarDecl *VD;
5735 // Look for a declaration of this variable that has an initializer, and
5736 // check whether it is an ICE.
5737 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5738 return NoDiag();
5739 else
5740 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005741 }
5742 }
5743 return ICEDiag(2, E->getLocStart());
5744 case Expr::UnaryOperatorClass: {
5745 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5746 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005747 case UO_PostInc:
5748 case UO_PostDec:
5749 case UO_PreInc:
5750 case UO_PreDec:
5751 case UO_AddrOf:
5752 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005753 // C99 6.6/3 allows increment and decrement within unevaluated
5754 // subexpressions of constant expressions, but they can never be ICEs
5755 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005756 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005757 case UO_Extension:
5758 case UO_LNot:
5759 case UO_Plus:
5760 case UO_Minus:
5761 case UO_Not:
5762 case UO_Real:
5763 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005764 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005765 }
5766
5767 // OffsetOf falls through here.
5768 }
5769 case Expr::OffsetOfExprClass: {
5770 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005771 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005772 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005773 // compliance: we should warn earlier for offsetof expressions with
5774 // array subscripts that aren't ICEs, and if the array subscripts
5775 // are ICEs, the value of the offsetof must be an integer constant.
5776 return CheckEvalInICE(E, Ctx);
5777 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005778 case Expr::UnaryExprOrTypeTraitExprClass: {
5779 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5780 if ((Exp->getKind() == UETT_SizeOf) &&
5781 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005782 return ICEDiag(2, E->getLocStart());
5783 return NoDiag();
5784 }
5785 case Expr::BinaryOperatorClass: {
5786 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5787 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005788 case BO_PtrMemD:
5789 case BO_PtrMemI:
5790 case BO_Assign:
5791 case BO_MulAssign:
5792 case BO_DivAssign:
5793 case BO_RemAssign:
5794 case BO_AddAssign:
5795 case BO_SubAssign:
5796 case BO_ShlAssign:
5797 case BO_ShrAssign:
5798 case BO_AndAssign:
5799 case BO_XorAssign:
5800 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005801 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5802 // constant expressions, but they can never be ICEs because an ICE cannot
5803 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005804 return ICEDiag(2, E->getLocStart());
5805
John McCall2de56d12010-08-25 11:45:40 +00005806 case BO_Mul:
5807 case BO_Div:
5808 case BO_Rem:
5809 case BO_Add:
5810 case BO_Sub:
5811 case BO_Shl:
5812 case BO_Shr:
5813 case BO_LT:
5814 case BO_GT:
5815 case BO_LE:
5816 case BO_GE:
5817 case BO_EQ:
5818 case BO_NE:
5819 case BO_And:
5820 case BO_Xor:
5821 case BO_Or:
5822 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005823 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5824 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005825 if (Exp->getOpcode() == BO_Div ||
5826 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005827 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005828 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005829 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005830 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005831 if (REval == 0)
5832 return ICEDiag(1, E->getLocStart());
5833 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005834 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005835 if (LEval.isMinSignedValue())
5836 return ICEDiag(1, E->getLocStart());
5837 }
5838 }
5839 }
John McCall2de56d12010-08-25 11:45:40 +00005840 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005841 if (Ctx.getLangOptions().C99) {
5842 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5843 // if it isn't evaluated.
5844 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5845 return ICEDiag(1, E->getLocStart());
5846 } else {
5847 // In both C89 and C++, commas in ICEs are illegal.
5848 return ICEDiag(2, E->getLocStart());
5849 }
5850 }
5851 if (LHSResult.Val >= RHSResult.Val)
5852 return LHSResult;
5853 return RHSResult;
5854 }
John McCall2de56d12010-08-25 11:45:40 +00005855 case BO_LAnd:
5856 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005857 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5858 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5859 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5860 // Rare case where the RHS has a comma "side-effect"; we need
5861 // to actually check the condition to see whether the side
5862 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005863 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005864 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005865 return RHSResult;
5866 return NoDiag();
5867 }
5868
5869 if (LHSResult.Val >= RHSResult.Val)
5870 return LHSResult;
5871 return RHSResult;
5872 }
5873 }
5874 }
5875 case Expr::ImplicitCastExprClass:
5876 case Expr::CStyleCastExprClass:
5877 case Expr::CXXFunctionalCastExprClass:
5878 case Expr::CXXStaticCastExprClass:
5879 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005880 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005881 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005882 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005883 if (isa<ExplicitCastExpr>(E)) {
5884 if (const FloatingLiteral *FL
5885 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5886 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5887 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5888 APSInt IgnoredVal(DestWidth, !DestSigned);
5889 bool Ignored;
5890 // If the value does not fit in the destination type, the behavior is
5891 // undefined, so we are not required to treat it as a constant
5892 // expression.
5893 if (FL->getValue().convertToInteger(IgnoredVal,
5894 llvm::APFloat::rmTowardZero,
5895 &Ignored) & APFloat::opInvalidOp)
5896 return ICEDiag(2, E->getLocStart());
5897 return NoDiag();
5898 }
5899 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005900 switch (cast<CastExpr>(E)->getCastKind()) {
5901 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005902 case CK_AtomicToNonAtomic:
5903 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005904 case CK_NoOp:
5905 case CK_IntegralToBoolean:
5906 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005907 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005908 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005909 return ICEDiag(2, E->getLocStart());
5910 }
John McCalld905f5a2010-05-07 05:32:02 +00005911 }
John McCall56ca35d2011-02-17 10:25:35 +00005912 case Expr::BinaryConditionalOperatorClass: {
5913 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5914 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5915 if (CommonResult.Val == 2) return CommonResult;
5916 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5917 if (FalseResult.Val == 2) return FalseResult;
5918 if (CommonResult.Val == 1) return CommonResult;
5919 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005920 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005921 return FalseResult;
5922 }
John McCalld905f5a2010-05-07 05:32:02 +00005923 case Expr::ConditionalOperatorClass: {
5924 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5925 // If the condition (ignoring parens) is a __builtin_constant_p call,
5926 // then only the true side is actually considered in an integer constant
5927 // expression, and it is fully evaluated. This is an important GNU
5928 // extension. See GCC PR38377 for discussion.
5929 if (const CallExpr *CallCE
5930 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00005931 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5932 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005933 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005934 if (CondResult.Val == 2)
5935 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005936
Richard Smithf48fdb02011-12-09 22:58:01 +00005937 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5938 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005939
John McCalld905f5a2010-05-07 05:32:02 +00005940 if (TrueResult.Val == 2)
5941 return TrueResult;
5942 if (FalseResult.Val == 2)
5943 return FalseResult;
5944 if (CondResult.Val == 1)
5945 return CondResult;
5946 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5947 return NoDiag();
5948 // Rare case where the diagnostics depend on which side is evaluated
5949 // Note that if we get here, CondResult is 0, and at least one of
5950 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005951 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005952 return FalseResult;
5953 }
5954 return TrueResult;
5955 }
5956 case Expr::CXXDefaultArgExprClass:
5957 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5958 case Expr::ChooseExprClass: {
5959 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5960 }
5961 }
5962
David Blaikie30263482012-01-20 21:50:17 +00005963 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00005964}
5965
Richard Smithf48fdb02011-12-09 22:58:01 +00005966/// Evaluate an expression as a C++11 integral constant expression.
5967static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5968 const Expr *E,
5969 llvm::APSInt *Value,
5970 SourceLocation *Loc) {
5971 if (!E->getType()->isIntegralOrEnumerationType()) {
5972 if (Loc) *Loc = E->getExprLoc();
5973 return false;
5974 }
5975
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005976 APValue Result;
5977 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00005978 return false;
5979
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005980 assert(Result.isInt() && "pointer cast to int is not an ICE");
5981 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00005982 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005983}
5984
Richard Smithdd1f29b2011-12-12 09:28:41 +00005985bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005986 if (Ctx.getLangOptions().CPlusPlus0x)
5987 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5988
John McCalld905f5a2010-05-07 05:32:02 +00005989 ICEDiag d = CheckICE(this, Ctx);
5990 if (d.Val != 0) {
5991 if (Loc) *Loc = d.Loc;
5992 return false;
5993 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005994 return true;
5995}
5996
5997bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5998 SourceLocation *Loc, bool isEvaluated) const {
5999 if (Ctx.getLangOptions().CPlusPlus0x)
6000 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6001
6002 if (!isIntegerConstantExpr(Ctx, Loc))
6003 return false;
6004 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006005 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006006 return true;
6007}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006008
6009bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6010 SourceLocation *Loc) const {
6011 // We support this checking in C++98 mode in order to diagnose compatibility
6012 // issues.
6013 assert(Ctx.getLangOptions().CPlusPlus);
6014
6015 Expr::EvalStatus Status;
6016 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6017 Status.Diag = &Diags;
6018 EvalInfo Info(Ctx, Status);
6019
6020 APValue Scratch;
6021 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6022
6023 if (!Diags.empty()) {
6024 IsConstExpr = false;
6025 if (Loc) *Loc = Diags[0].first;
6026 } else if (!IsConstExpr) {
6027 // FIXME: This shouldn't happen.
6028 if (Loc) *Loc = getExprLoc();
6029 }
6030
6031 return IsConstExpr;
6032}