blob: 3579e75d9451c0cfb05a4d65ca7005d37776a933 [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 Smith9a17a682011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith0a3bdb62011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith9a17a682011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith47a1eed2011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith08d6e032011-12-16 19:06:07 +0000234 /// CallLoc - The location of the call expression for this call.
235 SourceLocation CallLoc;
236
237 /// Callee - The function which was called.
238 const FunctionDecl *Callee;
239
Richard Smith180f4792011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smithd0dccea2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000246
Richard Smithbd552ef2011-10-31 05:52:43 +0000247 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
248 typedef MapTy::const_iterator temp_iterator;
249 /// Temporaries - Temporary lvalues materialized within this stack frame.
250 MapTy Temporaries;
251
Richard Smith08d6e032011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000256 };
257
Richard Smithdd1f29b2011-12-12 09:28:41 +0000258 /// A partial diagnostic which we might know in advance that we are not going
259 /// to emit.
260 class OptionalDiagnostic {
261 PartialDiagnostic *Diag;
262
263 public:
264 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
265
266 template<typename T>
267 OptionalDiagnostic &operator<<(const T &v) {
268 if (Diag)
269 *Diag << v;
270 return *this;
271 }
272 };
273
Richard Smithbd552ef2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000276
277 /// EvalStatus - Contains information about the evaluation.
278 Expr::EvalStatus &EvalStatus;
279
280 /// CurrentCall - The top of the constexpr call stack.
281 CallStackFrame *CurrentCall;
282
Richard Smithbd552ef2011-10-31 05:52:43 +0000283 /// CallStackDepth - The number of calls in the call stack right now.
284 unsigned CallStackDepth;
285
286 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
287 /// OpaqueValues - Values used as the common expression in a
288 /// BinaryConditionalOperator.
289 MapTy OpaqueValues;
290
291 /// BottomFrame - The frame in which evaluation started. This must be
292 /// initialized last.
293 CallStackFrame BottomFrame;
294
Richard Smith180f4792011-11-10 06:34:14 +0000295 /// EvaluatingDecl - This is the declaration whose initializer is being
296 /// evaluated, if any.
297 const VarDecl *EvaluatingDecl;
298
299 /// EvaluatingDeclValue - This is the value being constructed for the
300 /// declaration whose initializer is being evaluated, if any.
301 APValue *EvaluatingDeclValue;
302
Richard Smithc1c5f272011-12-13 06:39:58 +0000303 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
304 /// notes attached to it will also be stored, otherwise they will not be.
305 bool HasActiveDiagnostic;
306
Richard Smithbd552ef2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000312
Richard Smithbd552ef2011-10-31 05:52:43 +0000313 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
314 MapTy::const_iterator i = OpaqueValues.find(e);
315 if (i == OpaqueValues.end()) return 0;
316 return &i->second;
317 }
318
Richard Smith180f4792011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smithc18c4232011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smithc1c5f272011-12-13 06:39:58 +0000326 bool CheckCallLimit(SourceLocation Loc) {
327 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
328 return true;
329 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
330 << getLangOpts().ConstexprCallDepth;
331 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000332 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000333
Richard Smithc1c5f272011-12-13 06:39:58 +0000334 private:
335 /// Add a diagnostic to the diagnostics list.
336 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
337 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
338 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
339 return EvalStatus.Diag->back().second;
340 }
341
Richard Smith08d6e032011-12-16 19:06:07 +0000342 /// Add notes containing a call stack to the current point of evaluation.
343 void addCallStack(unsigned Limit);
344
Richard Smithc1c5f272011-12-13 06:39:58 +0000345 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000350 // If we have a prior diagnostic, it will be noting that the expression
351 // isn't a constant expression. This diagnostic is more important.
352 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000354 unsigned CallStackNotes = CallStackDepth - 1;
355 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
356 if (Limit)
357 CallStackNotes = std::min(CallStackNotes, Limit + 1);
358
Richard Smithc1c5f272011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000361 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
362 addDiag(Loc, DiagId);
363 addCallStack(Limit);
364 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000365 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000367 return OptionalDiagnostic();
368 }
369
370 /// Diagnose that the evaluation does not produce a C++11 core constant
371 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000378 return Diag(Loc, DiagId, ExtraNotes);
379 }
380
381 /// Add a note to a prior diagnostic.
382 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
383 if (!HasActiveDiagnostic)
384 return OptionalDiagnostic();
385 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000386 }
Richard Smith099e7f62011-12-19 06:19:21 +0000387
388 /// Add a stack of notes to a prior diagnostic.
389 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
390 if (HasActiveDiagnostic) {
391 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
392 Diags.begin(), Diags.end());
393 }
394 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000395 };
Richard Smith08d6e032011-12-16 19:06:07 +0000396}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smith08d6e032011-12-16 19:06:07 +0000398CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
399 const FunctionDecl *Callee, const LValue *This,
400 const CCValue *Arguments)
401 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
402 This(This), Arguments(Arguments) {
403 Info.CurrentCall = this;
404 ++Info.CallStackDepth;
405}
406
407CallStackFrame::~CallStackFrame() {
408 assert(Info.CurrentCall == this && "calls retired out of order");
409 --Info.CallStackDepth;
410 Info.CurrentCall = Caller;
411}
412
413/// Produce a string describing the given constexpr call.
414static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
415 unsigned ArgIndex = 0;
416 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
417 !isa<CXXConstructorDecl>(Frame->Callee);
418
419 if (!IsMemberCall)
420 Out << *Frame->Callee << '(';
421
422 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
423 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
424 if (ArgIndex > IsMemberCall)
425 Out << ", ";
426
427 const ParmVarDecl *Param = *I;
428 const CCValue &Arg = Frame->Arguments[ArgIndex];
429 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
430 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
431 else {
432 // Deliberately slice off the frame to form an APValue we can print.
433 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
434 Arg.getLValueDesignator().Entries,
435 Arg.getLValueDesignator().OnePastTheEnd);
436 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
437 }
438
439 if (ArgIndex == 0 && IsMemberCall)
440 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000441 }
442
Richard Smith08d6e032011-12-16 19:06:07 +0000443 Out << ')';
444}
445
446void EvalInfo::addCallStack(unsigned Limit) {
447 // Determine which calls to skip, if any.
448 unsigned ActiveCalls = CallStackDepth - 1;
449 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
450 if (Limit && Limit < ActiveCalls) {
451 SkipStart = Limit / 2 + Limit % 2;
452 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000453 }
454
Richard Smith08d6e032011-12-16 19:06:07 +0000455 // Walk the call stack and add the diagnostics.
456 unsigned CallIdx = 0;
457 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
458 Frame = Frame->Caller, ++CallIdx) {
459 // Skip this call?
460 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
461 if (CallIdx == SkipStart) {
462 // Note that we're skipping calls.
463 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
464 << unsigned(ActiveCalls - Limit);
465 }
466 continue;
467 }
468
469 llvm::SmallVector<char, 128> Buffer;
470 llvm::raw_svector_ostream Out(Buffer);
471 describeCall(Frame, Out);
472 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
473 }
474}
475
476namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000477 struct ComplexValue {
478 private:
479 bool IsInt;
480
481 public:
482 APSInt IntReal, IntImag;
483 APFloat FloatReal, FloatImag;
484
485 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
486
487 void makeComplexFloat() { IsInt = false; }
488 bool isComplexFloat() const { return !IsInt; }
489 APFloat &getComplexFloatReal() { return FloatReal; }
490 APFloat &getComplexFloatImag() { return FloatImag; }
491
492 void makeComplexInt() { IsInt = true; }
493 bool isComplexInt() const { return IsInt; }
494 APSInt &getComplexIntReal() { return IntReal; }
495 APSInt &getComplexIntImag() { return IntImag; }
496
Richard Smith47a1eed2011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000500 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000502 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000504 assert(v.isComplexFloat() || v.isComplexInt());
505 if (v.isComplexFloat()) {
506 makeComplexFloat();
507 FloatReal = v.getComplexFloatReal();
508 FloatImag = v.getComplexFloatImag();
509 } else {
510 makeComplexInt();
511 IntReal = v.getComplexIntReal();
512 IntImag = v.getComplexIntImag();
513 }
514 }
John McCallf4cf1a12010-05-07 17:22:02 +0000515 };
John McCallefdb83e2010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000522
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000529
Richard Smith47a1eed2011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000532 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000546 }
John McCallefdb83e2010-05-07 21:00:08 +0000547 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000548
549 struct MemberPtr {
550 MemberPtr() {}
551 explicit MemberPtr(const ValueDecl *Decl) :
552 DeclAndIsDerivedMember(Decl, false), Path() {}
553
554 /// The member or (direct or indirect) field referred to by this member
555 /// pointer, or 0 if this is a null member pointer.
556 const ValueDecl *getDecl() const {
557 return DeclAndIsDerivedMember.getPointer();
558 }
559 /// Is this actually a member of some type derived from the relevant class?
560 bool isDerivedMember() const {
561 return DeclAndIsDerivedMember.getInt();
562 }
563 /// Get the class which the declaration actually lives in.
564 const CXXRecordDecl *getContainingRecord() const {
565 return cast<CXXRecordDecl>(
566 DeclAndIsDerivedMember.getPointer()->getDeclContext());
567 }
568
569 void moveInto(CCValue &V) const {
570 V = CCValue(getDecl(), isDerivedMember(), Path);
571 }
572 void setFrom(const CCValue &V) {
573 assert(V.isMemberPointer());
574 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
575 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
576 Path.clear();
577 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
578 Path.insert(Path.end(), P.begin(), P.end());
579 }
580
581 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
582 /// whether the member is a member of some class derived from the class type
583 /// of the member pointer.
584 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
585 /// Path - The path of base/derived classes from the member declaration's
586 /// class (exclusive) to the class type of the member pointer (inclusive).
587 SmallVector<const CXXRecordDecl*, 4> Path;
588
589 /// Perform a cast towards the class of the Decl (either up or down the
590 /// hierarchy).
591 bool castBack(const CXXRecordDecl *Class) {
592 assert(!Path.empty());
593 const CXXRecordDecl *Expected;
594 if (Path.size() >= 2)
595 Expected = Path[Path.size() - 2];
596 else
597 Expected = getContainingRecord();
598 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
599 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
600 // if B does not contain the original member and is not a base or
601 // derived class of the class containing the original member, the result
602 // of the cast is undefined.
603 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
604 // (D::*). We consider that to be a language defect.
605 return false;
606 }
607 Path.pop_back();
608 return true;
609 }
610 /// Perform a base-to-derived member pointer cast.
611 bool castToDerived(const CXXRecordDecl *Derived) {
612 if (!getDecl())
613 return true;
614 if (!isDerivedMember()) {
615 Path.push_back(Derived);
616 return true;
617 }
618 if (!castBack(Derived))
619 return false;
620 if (Path.empty())
621 DeclAndIsDerivedMember.setInt(false);
622 return true;
623 }
624 /// Perform a derived-to-base member pointer cast.
625 bool castToBase(const CXXRecordDecl *Base) {
626 if (!getDecl())
627 return true;
628 if (Path.empty())
629 DeclAndIsDerivedMember.setInt(true);
630 if (isDerivedMember()) {
631 Path.push_back(Base);
632 return true;
633 }
634 return castBack(Base);
635 }
636 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000637
638 /// Kinds of constant expression checking, for diagnostics.
639 enum CheckConstantExpressionKind {
640 CCEK_Constant, ///< A normal constant.
641 CCEK_ReturnValue, ///< A constexpr function return value.
642 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
643 };
John McCallf4cf1a12010-05-07 17:22:02 +0000644}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000645
Richard Smith47a1eed2011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000651static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
652static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000653static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
654 EvalInfo &Info);
655static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smith180f4792011-11-10 06:34:14 +0000666/// Should this call expression be treated as a string literal?
667static bool IsStringLiteralCall(const CallExpr *E) {
668 unsigned Builtin = E->isBuiltinCall();
669 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
670 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
671}
672
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000674 // C++11 [expr.const]p3 An address constant expression is a prvalue core
675 // constant expression of pointer type that evaluates to...
676
677 // ... a null pointer value, or a prvalue core constant expression of type
678 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000680
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000681 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
682 // ... the address of an object with static storage duration,
683 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
684 return VD->hasGlobalStorage();
685 // ... the address of a function,
686 return isa<FunctionDecl>(D);
687 }
688
689 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000693 case Expr::CompoundLiteralExprClass:
694 return cast<CompoundLiteralExpr>(E)->isFileScope();
695 // A string literal has static storage duration.
696 case Expr::StringLiteralClass:
697 case Expr::PredefinedExprClass:
698 case Expr::ObjCStringLiteralClass:
699 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000700 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000701 return true;
702 case Expr::CallExprClass:
703 return IsStringLiteralCall(cast<CallExpr>(E));
704 // For GCC compatibility, &&label has static storage duration.
705 case Expr::AddrLabelExprClass:
706 return true;
707 // A Block literal expression may be used as the initialization value for
708 // Block variables at global or local static scope.
709 case Expr::BlockExprClass:
710 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
711 }
John McCall42c8f872010-05-10 23:27:23 +0000712}
713
Richard Smith9a17a682011-11-07 05:07:52 +0000714/// Check that this reference or pointer core constant expression is a valid
715/// value for a constant expression. Type T should be either LValue or CCValue.
716template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000717static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000718 const T &LVal, APValue &Value,
719 CheckConstantExpressionKind CCEK) {
720 APValue::LValueBase Base = LVal.getLValueBase();
721 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
722
723 if (!IsGlobalLValue(Base)) {
724 if (Info.getLangOpts().CPlusPlus0x) {
725 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
726 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
727 << E->isGLValue() << !Designator.Entries.empty()
728 << !!VD << CCEK << VD;
729 if (VD)
730 Info.Note(VD->getLocation(), diag::note_declared_at);
731 else
732 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
733 diag::note_constexpr_temporary_here);
734 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000735 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000736 }
Richard Smith9a17a682011-11-07 05:07:52 +0000737 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000738 }
Richard Smith9a17a682011-11-07 05:07:52 +0000739
Richard Smith9a17a682011-11-07 05:07:52 +0000740 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000741 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000742 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000743 // FIXME: This is not a core constant expression. We should have already
744 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000745 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
746 APValue::NoLValuePath());
747 return true;
748 }
749
Richard Smithc1c5f272011-12-13 06:39:58 +0000750 // Does this refer one past the end of some object?
751 // This is technically not an address constant expression nor a reference
752 // constant expression, but we allow it for address constant expressions.
753 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
754 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
755 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
756 << !Designator.Entries.empty() << !!VD << VD;
757 if (VD)
758 Info.Note(VD->getLocation(), diag::note_declared_at);
759 else
760 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
761 diag::note_constexpr_temporary_here);
762 return false;
763 }
764
Richard Smith9a17a682011-11-07 05:07:52 +0000765 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000766 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000767 return true;
768}
769
Richard Smitheba05b22011-12-25 20:00:17 +0000770/// Check that this core constant expression is of literal type, and if not,
771/// produce an appropriate diagnostic.
772static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
773 if (!E->isRValue() || E->getType()->isLiteralType())
774 return true;
775
776 // Prvalue constant expressions must be of literal types.
777 if (Info.getLangOpts().CPlusPlus0x)
778 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
779 << E->getType();
780 else
781 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
782 return false;
783}
784
Richard Smith47a1eed2011-10-29 20:57:55 +0000785/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000786/// constant expression, and if it is, produce the corresponding constant value.
Richard Smitheba05b22011-12-25 20:00:17 +0000787/// If not, report an appropriate diagnostic. Does not check that the expression
788/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000789static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000790 const CCValue &CCValue, APValue &Value,
791 CheckConstantExpressionKind CCEK
792 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000793 if (!CCValue.isLValue()) {
794 Value = CCValue;
795 return true;
796 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000797 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000798}
799
Richard Smith9e36b532011-10-31 05:11:32 +0000800const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000801 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000802}
803
804static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000805 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000806}
807
Richard Smith65ac5982011-11-01 21:06:14 +0000808static bool IsWeakLValue(const LValue &Value) {
809 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000810 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000811}
812
Richard Smithe24f5fc2011-11-17 22:56:20 +0000813static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000814 // A null base expression indicates a null pointer. These are always
815 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000816 if (!Value.getLValueBase()) {
817 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000818 return true;
819 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000820
John McCall42c8f872010-05-10 23:27:23 +0000821 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000822 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000823 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000824
Richard Smithe24f5fc2011-11-17 22:56:20 +0000825 // We have a non-null base. These are generally known to be true, but if it's
826 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000827 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000828 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000829 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000830}
831
Richard Smith47a1eed2011-10-29 20:57:55 +0000832static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000833 switch (Val.getKind()) {
834 case APValue::Uninitialized:
835 return false;
836 case APValue::Int:
837 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000838 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000839 case APValue::Float:
840 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000841 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000842 case APValue::ComplexInt:
843 Result = Val.getComplexIntReal().getBoolValue() ||
844 Val.getComplexIntImag().getBoolValue();
845 return true;
846 case APValue::ComplexFloat:
847 Result = !Val.getComplexFloatReal().isZero() ||
848 !Val.getComplexFloatImag().isZero();
849 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000850 case APValue::LValue:
851 return EvalPointerValueAsBool(Val, Result);
852 case APValue::MemberPointer:
853 Result = Val.getMemberPointerDecl();
854 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000855 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000856 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000857 case APValue::Struct:
858 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000859 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000860 }
861
Richard Smithc49bd112011-10-28 17:51:58 +0000862 llvm_unreachable("unknown APValue kind");
863}
864
865static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
866 EvalInfo &Info) {
867 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000868 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000869 if (!Evaluate(Val, Info, E))
870 return false;
871 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000872}
873
Richard Smithc1c5f272011-12-13 06:39:58 +0000874template<typename T>
875static bool HandleOverflow(EvalInfo &Info, const Expr *E,
876 const T &SrcValue, QualType DestType) {
877 llvm::SmallVector<char, 32> Buffer;
878 SrcValue.toString(Buffer);
879 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
880 << StringRef(Buffer.data(), Buffer.size()) << DestType;
881 return false;
882}
883
884static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
885 QualType SrcType, const APFloat &Value,
886 QualType DestType, APSInt &Result) {
887 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000888 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000889 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Richard Smithc1c5f272011-12-13 06:39:58 +0000891 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000892 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000893 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
894 & APFloat::opInvalidOp)
895 return HandleOverflow(Info, E, Value, DestType);
896 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000897}
898
Richard Smithc1c5f272011-12-13 06:39:58 +0000899static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
900 QualType SrcType, QualType DestType,
901 APFloat &Result) {
902 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000903 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000904 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
905 APFloat::rmNearestTiesToEven, &ignored)
906 & APFloat::opOverflow)
907 return HandleOverflow(Info, E, Value, DestType);
908 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000909}
910
Mike Stump1eb44332009-09-09 15:08:12 +0000911static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000912 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000913 unsigned DestWidth = Ctx.getIntWidth(DestType);
914 APSInt Result = Value;
915 // Figure out if this is a truncate, extend or noop cast.
916 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000917 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000918 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000919 return Result;
920}
921
Richard Smithc1c5f272011-12-13 06:39:58 +0000922static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
923 QualType SrcType, const APSInt &Value,
924 QualType DestType, APFloat &Result) {
925 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
926 if (Result.convertFromAPInt(Value, Value.isSigned(),
927 APFloat::rmNearestTiesToEven)
928 & APFloat::opOverflow)
929 return HandleOverflow(Info, E, Value, DestType);
930 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000931}
932
Eli Friedmane6a24e82011-12-22 03:51:45 +0000933static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
934 llvm::APInt &Res) {
935 CCValue SVal;
936 if (!Evaluate(SVal, Info, E))
937 return false;
938 if (SVal.isInt()) {
939 Res = SVal.getInt();
940 return true;
941 }
942 if (SVal.isFloat()) {
943 Res = SVal.getFloat().bitcastToAPInt();
944 return true;
945 }
946 if (SVal.isVector()) {
947 QualType VecTy = E->getType();
948 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
949 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
950 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
951 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
952 Res = llvm::APInt::getNullValue(VecSize);
953 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
954 APValue &Elt = SVal.getVectorElt(i);
955 llvm::APInt EltAsInt;
956 if (Elt.isInt()) {
957 EltAsInt = Elt.getInt();
958 } else if (Elt.isFloat()) {
959 EltAsInt = Elt.getFloat().bitcastToAPInt();
960 } else {
961 // Don't try to handle vectors of anything other than int or float
962 // (not sure if it's possible to hit this case).
963 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
964 return false;
965 }
966 unsigned BaseEltSize = EltAsInt.getBitWidth();
967 if (BigEndian)
968 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
969 else
970 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
971 }
972 return true;
973 }
974 // Give up if the input isn't an int, float, or vector. For example, we
975 // reject "(v4i16)(intptr_t)&a".
976 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
977 return false;
978}
979
Richard Smithe24f5fc2011-11-17 22:56:20 +0000980static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
981 const CXXRecordDecl *&MostDerivedType,
982 unsigned &MostDerivedPathLength,
983 bool &MostDerivedIsArrayElement) {
984 const SubobjectDesignator &D = LVal.Designator;
985 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000986 return false;
987
Richard Smithe24f5fc2011-11-17 22:56:20 +0000988 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000989
990 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000991 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000992 MostDerivedPathLength = 0;
993 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000994
995 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
996 bool IsArray = T && T->isArrayType();
997 if (IsArray)
998 T = T->getBaseElementTypeUnsafe();
999 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
1000 T = FD->getType().getTypePtr();
1001 else
1002 T = 0;
1003
1004 if (T) {
1005 MostDerivedType = T->getAsCXXRecordDecl();
1006 MostDerivedPathLength = I + 1;
1007 MostDerivedIsArrayElement = IsArray;
1008 }
1009 }
1010
Richard Smith180f4792011-11-10 06:34:14 +00001011 // (B*)&d + 1 has no most-derived object.
1012 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1013 return false;
1014
Richard Smithe24f5fc2011-11-17 22:56:20 +00001015 return MostDerivedType != 0;
1016}
1017
1018static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1019 const RecordDecl *TruncatedType,
1020 unsigned TruncatedElements,
1021 bool IsArrayElement) {
1022 SubobjectDesignator &D = Result.Designator;
1023 const RecordDecl *RD = TruncatedType;
1024 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001025 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1026 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001027 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001028 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001029 else
Richard Smith180f4792011-11-10 06:34:14 +00001030 Result.Offset -= Layout.getBaseClassOffset(Base);
1031 RD = Base;
1032 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001033 D.Entries.resize(TruncatedElements);
1034 D.ArrayElement = IsArrayElement;
1035}
1036
1037/// If the given LValue refers to a base subobject of some object, find the most
1038/// derived object and the corresponding complete record type. This is necessary
1039/// in order to find the offset of a virtual base class.
1040static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1041 const CXXRecordDecl *&MostDerivedType) {
1042 unsigned MostDerivedPathLength;
1043 bool MostDerivedIsArrayElement;
1044 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1045 MostDerivedPathLength, MostDerivedIsArrayElement))
1046 return false;
1047
1048 // Remove the trailing base class path entries and their offsets.
1049 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1050 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +00001051 return true;
1052}
1053
1054static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1055 const CXXRecordDecl *Derived,
1056 const CXXRecordDecl *Base,
1057 const ASTRecordLayout *RL = 0) {
1058 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1059 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1060 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1061}
1062
1063static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1064 const CXXRecordDecl *DerivedDecl,
1065 const CXXBaseSpecifier *Base) {
1066 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1067
1068 if (!Base->isVirtual()) {
1069 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1070 return true;
1071 }
1072
1073 // Extract most-derived object and corresponding type.
1074 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1075 return false;
1076
1077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1078 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1079 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1080 return true;
1081}
1082
1083/// Update LVal to refer to the given field, which must be a member of the type
1084/// currently described by LVal.
1085static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1086 const FieldDecl *FD,
1087 const ASTRecordLayout *RL = 0) {
1088 if (!RL)
1089 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1090
1091 unsigned I = FD->getFieldIndex();
1092 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1093 LVal.Designator.addDecl(FD);
1094}
1095
1096/// Get the size of the given type in char units.
1097static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1098 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1099 // extension.
1100 if (Type->isVoidType() || Type->isFunctionType()) {
1101 Size = CharUnits::One();
1102 return true;
1103 }
1104
1105 if (!Type->isConstantSizeType()) {
1106 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1107 return false;
1108 }
1109
1110 Size = Info.Ctx.getTypeSizeInChars(Type);
1111 return true;
1112}
1113
1114/// Update a pointer value to model pointer arithmetic.
1115/// \param Info - Information about the ongoing evaluation.
1116/// \param LVal - The pointer value to be updated.
1117/// \param EltTy - The pointee type represented by LVal.
1118/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1119static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1120 QualType EltTy, int64_t Adjustment) {
1121 CharUnits SizeOfPointee;
1122 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1123 return false;
1124
1125 // Compute the new offset in the appropriate width.
1126 LVal.Offset += Adjustment * SizeOfPointee;
1127 LVal.Designator.adjustIndex(Adjustment);
1128 return true;
1129}
1130
Richard Smith03f96112011-10-24 17:54:18 +00001131/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001132static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1133 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001134 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001135 // If this is a parameter to an active constexpr function call, perform
1136 // argument substitution.
1137 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001138 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001139 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001140 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001141 }
Richard Smith177dce72011-11-01 16:57:24 +00001142 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1143 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001144 }
Richard Smith03f96112011-10-24 17:54:18 +00001145
Richard Smith099e7f62011-12-19 06:19:21 +00001146 // Dig out the initializer, and use the declaration which it's attached to.
1147 const Expr *Init = VD->getAnyInitializer(VD);
1148 if (!Init || Init->isValueDependent()) {
1149 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1150 return false;
1151 }
1152
Richard Smith180f4792011-11-10 06:34:14 +00001153 // If we're currently evaluating the initializer of this declaration, use that
1154 // in-flight value.
1155 if (Info.EvaluatingDecl == VD) {
1156 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1157 return !Result.isUninit();
1158 }
1159
Richard Smith65ac5982011-11-01 21:06:14 +00001160 // Never evaluate the initializer of a weak variable. We can't be sure that
1161 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001162 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001163 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001164 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001165 }
Richard Smith65ac5982011-11-01 21:06:14 +00001166
Richard Smith099e7f62011-12-19 06:19:21 +00001167 // Check that we can fold the initializer. In C++, we will have already done
1168 // this in the cases where it matters for conformance.
1169 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1170 if (!VD->evaluateValue(Notes)) {
1171 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1172 Notes.size() + 1) << VD;
1173 Info.Note(VD->getLocation(), diag::note_declared_at);
1174 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001175 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001176 } else if (!VD->checkInitIsICE()) {
1177 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1178 Notes.size() + 1) << VD;
1179 Info.Note(VD->getLocation(), diag::note_declared_at);
1180 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001181 }
Richard Smith03f96112011-10-24 17:54:18 +00001182
Richard Smith099e7f62011-12-19 06:19:21 +00001183 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001184 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001185}
1186
Richard Smithc49bd112011-10-28 17:51:58 +00001187static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001188 Qualifiers Quals = T.getQualifiers();
1189 return Quals.hasConst() && !Quals.hasVolatile();
1190}
1191
Richard Smith59efe262011-11-11 04:05:33 +00001192/// Get the base index of the given base class within an APValue representing
1193/// the given derived class.
1194static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1195 const CXXRecordDecl *Base) {
1196 Base = Base->getCanonicalDecl();
1197 unsigned Index = 0;
1198 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1199 E = Derived->bases_end(); I != E; ++I, ++Index) {
1200 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1201 return Index;
1202 }
1203
1204 llvm_unreachable("base class missing from derived class's bases list");
1205}
1206
Richard Smithcc5d4f62011-11-07 09:22:26 +00001207/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001208static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1209 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001210 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001211 if (Sub.Invalid) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001212 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001213 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001214 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001215 if (Sub.OnePastTheEnd) {
1216 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001217 (unsigned)diag::note_constexpr_read_past_end :
1218 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001219 return false;
1220 }
Richard Smithf64699e2011-11-11 08:28:03 +00001221 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001222 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001223
1224 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1225 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001226 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001227 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001228 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001229 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001230 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001231 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001232 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001233 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001234 // Note, it should not be possible to form a pointer with a valid
1235 // designator which points more than one past the end of the array.
1236 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001237 (unsigned)diag::note_constexpr_read_past_end :
1238 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001239 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001240 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001241 if (O->getArrayInitializedElts() > Index)
1242 O = &O->getArrayInitializedElt(Index);
1243 else
1244 O = &O->getArrayFiller();
1245 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001246 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1247 // Next subobject is a class, struct or union field.
1248 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1249 if (RD->isUnion()) {
1250 const FieldDecl *UnionField = O->getUnionField();
1251 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001252 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001253 Info.Diag(E->getExprLoc(),
1254 diag::note_constexpr_read_inactive_union_member)
1255 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001256 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001257 }
Richard Smith180f4792011-11-10 06:34:14 +00001258 O = &O->getUnionValue();
1259 } else
1260 O = &O->getStructField(Field->getFieldIndex());
1261 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001262
1263 if (ObjType.isVolatileQualified()) {
1264 if (Info.getLangOpts().CPlusPlus) {
1265 // FIXME: Include a description of the path to the volatile subobject.
1266 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1267 << 2 << Field;
1268 Info.Note(Field->getLocation(), diag::note_declared_at);
1269 } else {
1270 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1271 }
1272 return false;
1273 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001274 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001275 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001276 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1277 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1278 O = &O->getStructBase(getBaseIndex(Derived, Base));
1279 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001280 }
Richard Smith180f4792011-11-10 06:34:14 +00001281
Richard Smithf48fdb02011-12-09 22:58:01 +00001282 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001283 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001284 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001285 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001286 }
1287
Richard Smithcc5d4f62011-11-07 09:22:26 +00001288 Obj = CCValue(*O, CCValue::GlobalValue());
1289 return true;
1290}
1291
Richard Smith180f4792011-11-10 06:34:14 +00001292/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1293/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1294/// for looking up the glvalue referred to by an entity of reference type.
1295///
1296/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001297/// \param Conv - The expression for which we are performing the conversion.
1298/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001299/// \param Type - The type we expect this conversion to produce.
1300/// \param LVal - The glvalue on which we are attempting to perform this action.
1301/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001302static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1303 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001304 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001305 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1306 if (!Info.getLangOpts().CPlusPlus)
1307 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1308
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001309 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001310 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001311 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001312
Richard Smithf48fdb02011-12-09 22:58:01 +00001313 if (!LVal.Base) {
1314 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001315 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1316 return false;
1317 }
1318
1319 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1320 // is not a constant expression (even if the object is non-volatile). We also
1321 // apply this rule to C++98, in order to conform to the expected 'volatile'
1322 // semantics.
1323 if (Type.isVolatileQualified()) {
1324 if (Info.getLangOpts().CPlusPlus)
1325 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1326 else
1327 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001328 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001329 }
Richard Smithc49bd112011-10-28 17:51:58 +00001330
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001331 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001332 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1333 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001334 // expressions are constant expressions too. Inside constexpr functions,
1335 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001336 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001337 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001338 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001339 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001340 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001341 }
1342
Richard Smith7098cbd2011-12-21 05:04:46 +00001343 // DR1313: If the object is volatile-qualified but the glvalue was not,
1344 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001345 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001346 if (VT.isVolatileQualified()) {
1347 if (Info.getLangOpts().CPlusPlus) {
1348 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1349 Info.Note(VD->getLocation(), diag::note_declared_at);
1350 } else {
1351 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001352 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001353 return false;
1354 }
1355
1356 if (!isa<ParmVarDecl>(VD)) {
1357 if (VD->isConstexpr()) {
1358 // OK, we can read this variable.
1359 } else if (VT->isIntegralOrEnumerationType()) {
1360 if (!VT.isConstQualified()) {
1361 if (Info.getLangOpts().CPlusPlus) {
1362 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1363 Info.Note(VD->getLocation(), diag::note_declared_at);
1364 } else {
1365 Info.Diag(Loc);
1366 }
1367 return false;
1368 }
1369 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1370 // We support folding of const floating-point types, in order to make
1371 // static const data members of such types (supported as an extension)
1372 // more useful.
1373 if (Info.getLangOpts().CPlusPlus0x) {
1374 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1375 Info.Note(VD->getLocation(), diag::note_declared_at);
1376 } else {
1377 Info.CCEDiag(Loc);
1378 }
1379 } else {
1380 // FIXME: Allow folding of values of any literal type in all languages.
1381 if (Info.getLangOpts().CPlusPlus0x) {
1382 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1383 Info.Note(VD->getLocation(), diag::note_declared_at);
1384 } else {
1385 Info.Diag(Loc);
1386 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001387 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001388 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001389 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001390
Richard Smithf48fdb02011-12-09 22:58:01 +00001391 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001392 return false;
1393
Richard Smith47a1eed2011-10-29 20:57:55 +00001394 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001395 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001396
1397 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1398 // conversion. This happens when the declaration and the lvalue should be
1399 // considered synonymous, for instance when initializing an array of char
1400 // from a string literal. Continue as if the initializer lvalue was the
1401 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001402 assert(RVal.getLValueOffset().isZero() &&
1403 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001404 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001405 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001406 }
1407
Richard Smith7098cbd2011-12-21 05:04:46 +00001408 // Volatile temporary objects cannot be read in constant expressions.
1409 if (Base->getType().isVolatileQualified()) {
1410 if (Info.getLangOpts().CPlusPlus) {
1411 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1412 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1413 } else {
1414 Info.Diag(Loc);
1415 }
1416 return false;
1417 }
1418
Richard Smith0a3bdb62011-11-04 02:25:55 +00001419 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1420 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1421 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001423 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001424 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001425 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001426
1427 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001428 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001429 const ConstantArrayType *CAT =
1430 Info.Ctx.getAsConstantArrayType(S->getType());
1431 if (Index >= CAT->getSize().getZExtValue()) {
1432 // Note, it should not be possible to form a pointer which points more
1433 // than one past the end of the array without producing a prior const expr
1434 // diagnostic.
1435 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001436 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001437 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001438 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1439 Type->isUnsignedIntegerType());
1440 if (Index < S->getLength())
1441 Value = S->getCodeUnit(Index);
1442 RVal = CCValue(Value);
1443 return true;
1444 }
1445
Richard Smithcc5d4f62011-11-07 09:22:26 +00001446 if (Frame) {
1447 // If this is a temporary expression with a nontrivial initializer, grab the
1448 // value from the relevant stack frame.
1449 RVal = Frame->Temporaries[Base];
1450 } else if (const CompoundLiteralExpr *CLE
1451 = dyn_cast<CompoundLiteralExpr>(Base)) {
1452 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1453 // initializer until now for such expressions. Such an expression can't be
1454 // an ICE in C, so this only matters for fold.
1455 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1456 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1457 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001458 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001459 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001460 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001461 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001462
Richard Smithf48fdb02011-12-09 22:58:01 +00001463 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1464 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001465}
1466
Richard Smith59efe262011-11-11 04:05:33 +00001467/// Build an lvalue for the object argument of a member function call.
1468static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1469 LValue &This) {
1470 if (Object->getType()->isPointerType())
1471 return EvaluatePointer(Object, This, Info);
1472
1473 if (Object->isGLValue())
1474 return EvaluateLValue(Object, This, Info);
1475
Richard Smithe24f5fc2011-11-17 22:56:20 +00001476 if (Object->getType()->isLiteralType())
1477 return EvaluateTemporary(Object, This, Info);
1478
1479 return false;
1480}
1481
1482/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1483/// lvalue referring to the result.
1484///
1485/// \param Info - Information about the ongoing evaluation.
1486/// \param BO - The member pointer access operation.
1487/// \param LV - Filled in with a reference to the resulting object.
1488/// \param IncludeMember - Specifies whether the member itself is included in
1489/// the resulting LValue subobject designator. This is not possible when
1490/// creating a bound member function.
1491/// \return The field or method declaration to which the member pointer refers,
1492/// or 0 if evaluation fails.
1493static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1494 const BinaryOperator *BO,
1495 LValue &LV,
1496 bool IncludeMember = true) {
1497 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1498
1499 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1500 return 0;
1501
1502 MemberPtr MemPtr;
1503 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1504 return 0;
1505
1506 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1507 // member value, the behavior is undefined.
1508 if (!MemPtr.getDecl())
1509 return 0;
1510
1511 if (MemPtr.isDerivedMember()) {
1512 // This is a member of some derived class. Truncate LV appropriately.
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1517 MostDerivedIsArrayElement))
1518 return 0;
1519
1520 // The end of the derived-to-base path for the base object must match the
1521 // derived-to-base path for the member pointer.
1522 if (MostDerivedPathLength + MemPtr.Path.size() >
1523 LV.Designator.Entries.size())
1524 return 0;
1525 unsigned PathLengthToMember =
1526 LV.Designator.Entries.size() - MemPtr.Path.size();
1527 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1528 const CXXRecordDecl *LVDecl = getAsBaseClass(
1529 LV.Designator.Entries[PathLengthToMember + I]);
1530 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1531 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1532 return 0;
1533 }
1534
1535 // Truncate the lvalue to the appropriate derived class.
1536 bool ResultIsArray = false;
1537 if (PathLengthToMember == MostDerivedPathLength)
1538 ResultIsArray = MostDerivedIsArrayElement;
1539 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1540 PathLengthToMember, ResultIsArray);
1541 } else if (!MemPtr.Path.empty()) {
1542 // Extend the LValue path with the member pointer's path.
1543 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1544 MemPtr.Path.size() + IncludeMember);
1545
1546 // Walk down to the appropriate base class.
1547 QualType LVType = BO->getLHS()->getType();
1548 if (const PointerType *PT = LVType->getAs<PointerType>())
1549 LVType = PT->getPointeeType();
1550 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1551 assert(RD && "member pointer access on non-class-type expression");
1552 // The first class in the path is that of the lvalue.
1553 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1554 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1555 HandleLValueDirectBase(Info, LV, RD, Base);
1556 RD = Base;
1557 }
1558 // Finally cast to the class containing the member.
1559 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1560 }
1561
1562 // Add the member. Note that we cannot build bound member functions here.
1563 if (IncludeMember) {
1564 // FIXME: Deal with IndirectFieldDecls.
1565 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1566 if (!FD) return 0;
1567 HandleLValueMember(Info, LV, FD);
1568 }
1569
1570 return MemPtr.getDecl();
1571}
1572
1573/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1574/// the provided lvalue, which currently refers to the base object.
1575static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1576 LValue &Result) {
1577 const CXXRecordDecl *MostDerivedType;
1578 unsigned MostDerivedPathLength;
1579 bool MostDerivedIsArrayElement;
1580
1581 // Check this cast doesn't take us outside the object.
1582 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1583 MostDerivedPathLength,
1584 MostDerivedIsArrayElement))
1585 return false;
1586 SubobjectDesignator &D = Result.Designator;
1587 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1588 return false;
1589
1590 // Check the type of the final cast. We don't need to check the path,
1591 // since a cast can only be formed if the path is unique.
1592 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1593 bool ResultIsArray = false;
1594 QualType TargetQT = E->getType();
1595 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1596 TargetQT = PT->getPointeeType();
1597 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1598 const CXXRecordDecl *FinalType;
1599 if (NewEntriesSize == MostDerivedPathLength) {
1600 ResultIsArray = MostDerivedIsArrayElement;
1601 FinalType = MostDerivedType;
1602 } else
1603 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1604 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1605 return false;
1606
1607 // Truncate the lvalue to the appropriate derived class.
1608 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1609 ResultIsArray);
1610 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001611}
1612
Mike Stumpc4c90452009-10-27 22:09:17 +00001613namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001614enum EvalStmtResult {
1615 /// Evaluation failed.
1616 ESR_Failed,
1617 /// Hit a 'return' statement.
1618 ESR_Returned,
1619 /// Evaluation succeeded.
1620 ESR_Succeeded
1621};
1622}
1623
1624// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001625static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001626 const Stmt *S) {
1627 switch (S->getStmtClass()) {
1628 default:
1629 return ESR_Failed;
1630
1631 case Stmt::NullStmtClass:
1632 case Stmt::DeclStmtClass:
1633 return ESR_Succeeded;
1634
Richard Smithc1c5f272011-12-13 06:39:58 +00001635 case Stmt::ReturnStmtClass: {
1636 CCValue CCResult;
1637 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1638 if (!Evaluate(CCResult, Info, RetExpr) ||
1639 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1640 CCEK_ReturnValue))
1641 return ESR_Failed;
1642 return ESR_Returned;
1643 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001644
1645 case Stmt::CompoundStmtClass: {
1646 const CompoundStmt *CS = cast<CompoundStmt>(S);
1647 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1648 BE = CS->body_end(); BI != BE; ++BI) {
1649 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1650 if (ESR != ESR_Succeeded)
1651 return ESR;
1652 }
1653 return ESR_Succeeded;
1654 }
1655 }
1656}
1657
Richard Smith61802452011-12-22 02:22:31 +00001658/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1659/// default constructor. If so, we'll fold it whether or not it's marked as
1660/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1661/// so we need special handling.
1662static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smitheba05b22011-12-25 20:00:17 +00001663 const CXXConstructorDecl *CD,
1664 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001665 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1666 return false;
1667
1668 if (!CD->isConstexpr()) {
1669 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smitheba05b22011-12-25 20:00:17 +00001670 // Value-initialization does not call a trivial default constructor, so
1671 // such a call is a core constant expression whether or not the
1672 // constructor is constexpr.
1673 if (!IsValueInitialization) {
1674 // FIXME: If DiagDecl is an implicitly-declared special member function,
1675 // we should be much more explicit about why it's not constexpr.
1676 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1677 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1678 Info.Note(CD->getLocation(), diag::note_declared_at);
1679 }
Richard Smith61802452011-12-22 02:22:31 +00001680 } else {
1681 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1682 }
1683 }
1684 return true;
1685}
1686
Richard Smithc1c5f272011-12-13 06:39:58 +00001687/// CheckConstexprFunction - Check that a function can be called in a constant
1688/// expression.
1689static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1690 const FunctionDecl *Declaration,
1691 const FunctionDecl *Definition) {
1692 // Can we evaluate this function call?
1693 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1694 return true;
1695
1696 if (Info.getLangOpts().CPlusPlus0x) {
1697 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001698 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1699 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001700 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1701 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1702 << DiagDecl;
1703 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1704 } else {
1705 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1706 }
1707 return false;
1708}
1709
Richard Smith180f4792011-11-10 06:34:14 +00001710namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001711typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001712}
1713
1714/// EvaluateArgs - Evaluate the arguments to a function call.
1715static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1716 EvalInfo &Info) {
1717 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1718 I != E; ++I)
1719 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1720 return false;
1721 return true;
1722}
1723
Richard Smithd0dccea2011-10-28 22:34:42 +00001724/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001725static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1726 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001727 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001728 EvalInfo &Info, APValue &Result) {
1729 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001730 return false;
1731
Richard Smith180f4792011-11-10 06:34:14 +00001732 ArgVector ArgValues(Args.size());
1733 if (!EvaluateArgs(Args, ArgValues, Info))
1734 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001735
Richard Smith08d6e032011-12-16 19:06:07 +00001736 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1737 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001738 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1739}
1740
Richard Smith180f4792011-11-10 06:34:14 +00001741/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001742static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001743 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001744 const CXXConstructorDecl *Definition,
Richard Smitheba05b22011-12-25 20:00:17 +00001745 EvalInfo &Info, APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001746 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001747 return false;
1748
1749 ArgVector ArgValues(Args.size());
1750 if (!EvaluateArgs(Args, ArgValues, Info))
1751 return false;
1752
Richard Smith08d6e032011-12-16 19:06:07 +00001753 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1754 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001755
1756 // If it's a delegating constructor, just delegate.
1757 if (Definition->isDelegatingConstructor()) {
1758 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1759 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1760 }
1761
1762 // Reserve space for the struct members.
1763 const CXXRecordDecl *RD = Definition->getParent();
Richard Smitheba05b22011-12-25 20:00:17 +00001764 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001765 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1766 std::distance(RD->field_begin(), RD->field_end()));
1767
1768 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1769
1770 unsigned BasesSeen = 0;
1771#ifndef NDEBUG
1772 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1773#endif
1774 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1775 E = Definition->init_end(); I != E; ++I) {
1776 if ((*I)->isBaseInitializer()) {
1777 QualType BaseType((*I)->getBaseClass(), 0);
1778#ifndef NDEBUG
1779 // Non-virtual base classes are initialized in the order in the class
1780 // definition. We cannot have a virtual base class for a literal type.
1781 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1782 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1783 "base class initializers not in expected order");
1784 ++BaseIt;
1785#endif
1786 LValue Subobject = This;
1787 HandleLValueDirectBase(Info, Subobject, RD,
1788 BaseType->getAsCXXRecordDecl(), &Layout);
1789 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1790 Subobject, (*I)->getInit()))
1791 return false;
1792 } else if (FieldDecl *FD = (*I)->getMember()) {
1793 LValue Subobject = This;
1794 HandleLValueMember(Info, Subobject, FD, &Layout);
1795 if (RD->isUnion()) {
1796 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001797 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1798 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001799 return false;
1800 } else if (!EvaluateConstantExpression(
1801 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001802 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001803 return false;
1804 } else {
1805 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001806 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001807 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001808 return false;
1809 }
1810 }
1811
1812 return true;
1813}
1814
Richard Smithd0dccea2011-10-28 22:34:42 +00001815namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001816class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001817 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001818 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001819public:
1820
Richard Smith1e12c592011-10-16 21:26:27 +00001821 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001822
1823 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001824 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001825 return true;
1826 }
1827
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001828 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1829 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001830 return Visit(E->getResultExpr());
1831 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001832 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001833 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001834 return true;
1835 return false;
1836 }
John McCallf85e1932011-06-15 23:02:42 +00001837 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001838 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001839 return true;
1840 return false;
1841 }
1842 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001843 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001844 return true;
1845 return false;
1846 }
1847
Mike Stumpc4c90452009-10-27 22:09:17 +00001848 // We don't want to evaluate BlockExprs multiple times, as they generate
1849 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001850 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1851 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1852 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001853 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001854 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1855 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1856 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1857 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1858 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1859 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001860 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001861 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001862 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001863 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001864 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001865 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1866 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1867 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1868 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001869 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001870 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1871 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1872 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1873 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1874 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001875 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001876 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001877 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001878 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001879 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001880
1881 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001882 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001883 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1884 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001885 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001886 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001887 return false;
1888 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001889
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001890 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001891};
1892
John McCall56ca35d2011-02-17 10:25:35 +00001893class OpaqueValueEvaluation {
1894 EvalInfo &info;
1895 OpaqueValueExpr *opaqueValue;
1896
1897public:
1898 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1899 Expr *value)
1900 : info(info), opaqueValue(opaqueValue) {
1901
1902 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001903 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001904 this->opaqueValue = 0;
1905 return;
1906 }
John McCall56ca35d2011-02-17 10:25:35 +00001907 }
1908
1909 bool hasError() const { return opaqueValue == 0; }
1910
1911 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001912 // FIXME: This will not work for recursive constexpr functions using opaque
1913 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001914 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1915 }
1916};
1917
Mike Stumpc4c90452009-10-27 22:09:17 +00001918} // end anonymous namespace
1919
Eli Friedman4efaa272008-11-12 09:44:48 +00001920//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001921// Generic Evaluation
1922//===----------------------------------------------------------------------===//
1923namespace {
1924
Richard Smithf48fdb02011-12-09 22:58:01 +00001925// FIXME: RetTy is always bool. Remove it.
1926template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001927class ExprEvaluatorBase
1928 : public ConstStmtVisitor<Derived, RetTy> {
1929private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001930 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001931 return static_cast<Derived*>(this)->Success(V, E);
1932 }
Richard Smitheba05b22011-12-25 20:00:17 +00001933 RetTy DerivedZeroInitialization(const Expr *E) {
1934 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00001935 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001936
1937protected:
1938 EvalInfo &Info;
1939 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1940 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1941
Richard Smithdd1f29b2011-12-12 09:28:41 +00001942 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001943 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001944 }
1945
1946 /// Report an evaluation error. This should only be called when an error is
1947 /// first discovered. When propagating an error, just return false.
1948 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001949 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001950 return false;
1951 }
1952 bool Error(const Expr *E) {
1953 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1954 }
1955
Richard Smitheba05b22011-12-25 20:00:17 +00001956 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001957
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001958public:
1959 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1960
1961 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001962 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001963 }
1964 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001965 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001966 }
1967
1968 RetTy VisitParenExpr(const ParenExpr *E)
1969 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1970 RetTy VisitUnaryExtension(const UnaryOperator *E)
1971 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1972 RetTy VisitUnaryPlus(const UnaryOperator *E)
1973 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1974 RetTy VisitChooseExpr(const ChooseExpr *E)
1975 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1976 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1977 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001978 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1979 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001980 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1981 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00001982 // We cannot create any objects for which cleanups are required, so there is
1983 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1984 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1985 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001986
Richard Smithc216a012011-12-12 12:46:16 +00001987 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1988 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1989 return static_cast<Derived*>(this)->VisitCastExpr(E);
1990 }
1991 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1992 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1993 return static_cast<Derived*>(this)->VisitCastExpr(E);
1994 }
1995
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1997 switch (E->getOpcode()) {
1998 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001999 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000
2001 case BO_Comma:
2002 VisitIgnoredValue(E->getLHS());
2003 return StmtVisitorTy::Visit(E->getRHS());
2004
2005 case BO_PtrMemD:
2006 case BO_PtrMemI: {
2007 LValue Obj;
2008 if (!HandleMemberPointerAccess(Info, E, Obj))
2009 return false;
2010 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002011 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002012 return false;
2013 return DerivedSuccess(Result, E);
2014 }
2015 }
2016 }
2017
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002018 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2019 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2020 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002021 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002022
2023 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002024 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002025 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002026
2027 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2028 }
2029
2030 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2031 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002032 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002033 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002034
Richard Smithc49bd112011-10-28 17:51:58 +00002035 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002036 return StmtVisitorTy::Visit(EvalExpr);
2037 }
2038
2039 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002040 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002041 if (!Value) {
2042 const Expr *Source = E->getSourceExpr();
2043 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002044 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002045 if (Source == E) { // sanity checking.
2046 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002047 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002048 }
2049 return StmtVisitorTy::Visit(Source);
2050 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002051 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002052 }
Richard Smithf10d9172011-10-11 21:43:33 +00002053
Richard Smithd0dccea2011-10-28 22:34:42 +00002054 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002055 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002056 QualType CalleeType = Callee->getType();
2057
Richard Smithd0dccea2011-10-28 22:34:42 +00002058 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002059 LValue *This = 0, ThisVal;
2060 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002061
Richard Smith59efe262011-11-11 04:05:33 +00002062 // Extract function decl and 'this' pointer from the callee.
2063 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002064 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2066 // Explicit bound member calls, such as x.f() or p->g();
2067 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002068 return false;
2069 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002070 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002071 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2072 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002073 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2074 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002075 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002076 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002077 return Error(Callee);
2078
2079 FD = dyn_cast<FunctionDecl>(Member);
2080 if (!FD)
2081 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002082 } else if (CalleeType->isFunctionPointerType()) {
2083 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00002084 if (!Evaluate(Call, Info, Callee))
2085 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002086
Richard Smithf48fdb02011-12-09 22:58:01 +00002087 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2088 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002089 FD = dyn_cast_or_null<FunctionDecl>(
2090 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002091 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002092 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002093
2094 // Overloaded operator calls to member functions are represented as normal
2095 // calls with '*this' as the first argument.
2096 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2097 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002098 // FIXME: When selecting an implicit conversion for an overloaded
2099 // operator delete, we sometimes try to evaluate calls to conversion
2100 // operators without a 'this' parameter!
2101 if (Args.empty())
2102 return Error(E);
2103
Richard Smith59efe262011-11-11 04:05:33 +00002104 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2105 return false;
2106 This = &ThisVal;
2107 Args = Args.slice(1);
2108 }
2109
2110 // Don't call function pointers which have been cast to some other type.
2111 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002112 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002113 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002114 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002115
Richard Smithc1c5f272011-12-13 06:39:58 +00002116 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002117 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002118 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002119
Richard Smithc1c5f272011-12-13 06:39:58 +00002120 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002121 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002122 return false;
2123
2124 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002125 }
2126
Richard Smithc49bd112011-10-28 17:51:58 +00002127 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2128 return StmtVisitorTy::Visit(E->getInitializer());
2129 }
Richard Smithf10d9172011-10-11 21:43:33 +00002130 RetTy VisitInitListExpr(const InitListExpr *E) {
2131 if (Info.getLangOpts().CPlusPlus0x) {
2132 if (E->getNumInits() == 0)
Richard Smitheba05b22011-12-25 20:00:17 +00002133 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002134 if (E->getNumInits() == 1)
2135 return StmtVisitorTy::Visit(E->getInit(0));
2136 }
Richard Smithf48fdb02011-12-09 22:58:01 +00002137 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002138 }
2139 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002140 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002141 }
2142 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002143 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002144 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002145 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002146 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002147 }
Richard Smithf10d9172011-10-11 21:43:33 +00002148
Richard Smith180f4792011-11-10 06:34:14 +00002149 /// A member expression where the object is a prvalue is itself a prvalue.
2150 RetTy VisitMemberExpr(const MemberExpr *E) {
2151 assert(!E->isArrow() && "missing call to bound member function?");
2152
2153 CCValue Val;
2154 if (!Evaluate(Val, Info, E->getBase()))
2155 return false;
2156
2157 QualType BaseTy = E->getBase()->getType();
2158
2159 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002160 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002161 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2162 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2163 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2164
2165 SubobjectDesignator Designator;
2166 Designator.addDecl(FD);
2167
Richard Smithf48fdb02011-12-09 22:58:01 +00002168 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002169 DerivedSuccess(Val, E);
2170 }
2171
Richard Smithc49bd112011-10-28 17:51:58 +00002172 RetTy VisitCastExpr(const CastExpr *E) {
2173 switch (E->getCastKind()) {
2174 default:
2175 break;
2176
2177 case CK_NoOp:
2178 return StmtVisitorTy::Visit(E->getSubExpr());
2179
2180 case CK_LValueToRValue: {
2181 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002182 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2183 return false;
2184 CCValue RVal;
2185 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2186 return false;
2187 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002188 }
2189 }
2190
Richard Smithf48fdb02011-12-09 22:58:01 +00002191 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002192 }
2193
Richard Smith8327fad2011-10-24 18:44:57 +00002194 /// Visit a value which is evaluated, but whose value is ignored.
2195 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002196 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002197 if (!Evaluate(Scratch, Info, E))
2198 Info.EvalStatus.HasSideEffects = true;
2199 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002200};
2201
2202}
2203
2204//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002205// Common base class for lvalue and temporary evaluation.
2206//===----------------------------------------------------------------------===//
2207namespace {
2208template<class Derived>
2209class LValueExprEvaluatorBase
2210 : public ExprEvaluatorBase<Derived, bool> {
2211protected:
2212 LValue &Result;
2213 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2214 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2215
2216 bool Success(APValue::LValueBase B) {
2217 Result.set(B);
2218 return true;
2219 }
2220
2221public:
2222 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2223 ExprEvaluatorBaseTy(Info), Result(Result) {}
2224
2225 bool Success(const CCValue &V, const Expr *E) {
2226 Result.setFrom(V);
2227 return true;
2228 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002229
2230 bool CheckValidLValue() {
2231 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2232 // there are no null references, nor once-past-the-end references.
2233 // FIXME: Check for one-past-the-end array indices
2234 return Result.Base && !Result.Designator.Invalid &&
2235 !Result.Designator.OnePastTheEnd;
2236 }
2237
2238 bool VisitMemberExpr(const MemberExpr *E) {
2239 // Handle non-static data members.
2240 QualType BaseTy;
2241 if (E->isArrow()) {
2242 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2243 return false;
2244 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002245 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002246 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002247 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2248 return false;
2249 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002250 } else {
2251 if (!this->Visit(E->getBase()))
2252 return false;
2253 BaseTy = E->getBase()->getType();
2254 }
2255 // FIXME: In C++11, require the result to be a valid lvalue.
2256
2257 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2258 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002259 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002260 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2261 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2262 (void)BaseTy;
2263
2264 HandleLValueMember(this->Info, Result, FD);
2265
2266 if (FD->getType()->isReferenceType()) {
2267 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002268 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002269 RefValue))
2270 return false;
2271 return Success(RefValue, E);
2272 }
2273 return true;
2274 }
2275
2276 bool VisitBinaryOperator(const BinaryOperator *E) {
2277 switch (E->getOpcode()) {
2278 default:
2279 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2280
2281 case BO_PtrMemD:
2282 case BO_PtrMemI:
2283 return HandleMemberPointerAccess(this->Info, E, Result);
2284 }
2285 }
2286
2287 bool VisitCastExpr(const CastExpr *E) {
2288 switch (E->getCastKind()) {
2289 default:
2290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2291
2292 case CK_DerivedToBase:
2293 case CK_UncheckedDerivedToBase: {
2294 if (!this->Visit(E->getSubExpr()))
2295 return false;
2296 if (!CheckValidLValue())
2297 return false;
2298
2299 // Now figure out the necessary offset to add to the base LV to get from
2300 // the derived class to the base class.
2301 QualType Type = E->getSubExpr()->getType();
2302
2303 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2304 PathE = E->path_end(); PathI != PathE; ++PathI) {
2305 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2306 *PathI))
2307 return false;
2308 Type = (*PathI)->getType();
2309 }
2310
2311 return true;
2312 }
2313 }
2314 }
2315};
2316}
2317
2318//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002319// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002320//
2321// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2322// function designators (in C), decl references to void objects (in C), and
2323// temporaries (if building with -Wno-address-of-temporary).
2324//
2325// LValue evaluation produces values comprising a base expression of one of the
2326// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002327// - Declarations
2328// * VarDecl
2329// * FunctionDecl
2330// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002331// * CompoundLiteralExpr in C
2332// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002333// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002334// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002335// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002336// * ObjCEncodeExpr
2337// * AddrLabelExpr
2338// * BlockExpr
2339// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002340// - Locals and temporaries
2341// * Any Expr, with a Frame indicating the function in which the temporary was
2342// evaluated.
2343// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002344//===----------------------------------------------------------------------===//
2345namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002346class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002347 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002348public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002349 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2350 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Richard Smithc49bd112011-10-28 17:51:58 +00002352 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2353
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002354 bool VisitDeclRefExpr(const DeclRefExpr *E);
2355 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002356 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002357 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2358 bool VisitMemberExpr(const MemberExpr *E);
2359 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2360 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002361 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002362 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2363 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002364
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002365 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002366 switch (E->getCastKind()) {
2367 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002368 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002369
Eli Friedmandb924222011-10-11 00:13:24 +00002370 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002371 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002372 if (!Visit(E->getSubExpr()))
2373 return false;
2374 Result.Designator.setInvalid();
2375 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002376
Richard Smithe24f5fc2011-11-17 22:56:20 +00002377 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002378 if (!Visit(E->getSubExpr()))
2379 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002380 if (!CheckValidLValue())
2381 return false;
2382 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002383 }
2384 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002385
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002386 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387
Eli Friedman4efaa272008-11-12 09:44:48 +00002388};
2389} // end anonymous namespace
2390
Richard Smithc49bd112011-10-28 17:51:58 +00002391/// Evaluate an expression as an lvalue. This can be legitimately called on
2392/// expressions which are not glvalues, in a few cases:
2393/// * function designators in C,
2394/// * "extern void" objects,
2395/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002396static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002397 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2398 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2399 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002400 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002401}
2402
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002403bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002404 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2405 return Success(FD);
2406 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002407 return VisitVarDecl(E, VD);
2408 return Error(E);
2409}
Richard Smith436c8892011-10-24 23:14:33 +00002410
Richard Smithc49bd112011-10-28 17:51:58 +00002411bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002412 if (!VD->getType()->isReferenceType()) {
2413 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002414 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002415 return true;
2416 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002417 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002418 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002419
Richard Smith47a1eed2011-10-29 20:57:55 +00002420 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002421 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2422 return false;
2423 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002424}
2425
Richard Smithbd552ef2011-10-31 05:52:43 +00002426bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2427 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002428 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002429 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002430 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2431
2432 Result.set(E, Info.CurrentCall);
2433 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2434 Result, E->GetTemporaryExpr());
2435 }
2436
2437 // Materialization of an lvalue temporary occurs when we need to force a copy
2438 // (for instance, if it's a bitfield).
2439 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2440 if (!Visit(E->GetTemporaryExpr()))
2441 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002442 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002443 Info.CurrentCall->Temporaries[E]))
2444 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002445 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002446 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002447}
2448
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449bool
2450LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002451 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2452 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2453 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002454 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002455}
2456
Richard Smith47d21452011-12-27 12:18:28 +00002457bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2458 if (E->isTypeOperand())
2459 return Success(E);
2460 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2461 if (RD && RD->isPolymorphic()) {
2462 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2463 << E->getExprOperand()->getType()
2464 << E->getExprOperand()->getSourceRange();
2465 return false;
2466 }
2467 return Success(E);
2468}
2469
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002470bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002471 // Handle static data members.
2472 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2473 VisitIgnoredValue(E->getBase());
2474 return VisitVarDecl(E, VD);
2475 }
2476
Richard Smithd0dccea2011-10-28 22:34:42 +00002477 // Handle static member functions.
2478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2479 if (MD->isStatic()) {
2480 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002481 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002482 }
2483 }
2484
Richard Smith180f4792011-11-10 06:34:14 +00002485 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002487}
2488
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002489bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002490 // FIXME: Deal with vectors as array subscript bases.
2491 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002492 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002493
Anders Carlsson3068d112008-11-16 19:01:22 +00002494 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002495 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Anders Carlsson3068d112008-11-16 19:01:22 +00002497 APSInt Index;
2498 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002499 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002500 int64_t IndexValue
2501 = Index.isSigned() ? Index.getSExtValue()
2502 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002503
Richard Smithe24f5fc2011-11-17 22:56:20 +00002504 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002505 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002506}
Eli Friedman4efaa272008-11-12 09:44:48 +00002507
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002509 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002510 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002511}
2512
Eli Friedman4efaa272008-11-12 09:44:48 +00002513//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002514// Pointer Evaluation
2515//===----------------------------------------------------------------------===//
2516
Anders Carlssonc754aa62008-07-08 05:13:58 +00002517namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002518class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002519 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002520 LValue &Result;
2521
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002522 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002523 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002524 return true;
2525 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002526public:
Mike Stump1eb44332009-09-09 15:08:12 +00002527
John McCallefdb83e2010-05-07 21:00:08 +00002528 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002529 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002530
Richard Smith47a1eed2011-10-29 20:57:55 +00002531 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002532 Result.setFrom(V);
2533 return true;
2534 }
Richard Smitheba05b22011-12-25 20:00:17 +00002535 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002536 return Success((Expr*)0);
2537 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002538
John McCallefdb83e2010-05-07 21:00:08 +00002539 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002540 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002541 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002542 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002543 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002544 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002545 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002546 bool VisitCallExpr(const CallExpr *E);
2547 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002548 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002549 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002551 }
Richard Smith180f4792011-11-10 06:34:14 +00002552 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2553 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002554 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002555 Result = *Info.CurrentCall->This;
2556 return true;
2557 }
John McCall56ca35d2011-02-17 10:25:35 +00002558
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002559 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002560};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002561} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002562
John McCallefdb83e2010-05-07 21:00:08 +00002563static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002564 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002565 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002566}
2567
John McCallefdb83e2010-05-07 21:00:08 +00002568bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002569 if (E->getOpcode() != BO_Add &&
2570 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002572
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002573 const Expr *PExp = E->getLHS();
2574 const Expr *IExp = E->getRHS();
2575 if (IExp->getType()->isPointerType())
2576 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002577
John McCallefdb83e2010-05-07 21:00:08 +00002578 if (!EvaluatePointer(PExp, Result, Info))
2579 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002580
John McCallefdb83e2010-05-07 21:00:08 +00002581 llvm::APSInt Offset;
2582 if (!EvaluateInteger(IExp, Offset, Info))
2583 return false;
2584 int64_t AdditionalOffset
2585 = Offset.isSigned() ? Offset.getSExtValue()
2586 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002587 if (E->getOpcode() == BO_Sub)
2588 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002589
Richard Smith180f4792011-11-10 06:34:14 +00002590 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002591 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002592 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002593}
Eli Friedman4efaa272008-11-12 09:44:48 +00002594
John McCallefdb83e2010-05-07 21:00:08 +00002595bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2596 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002597}
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002599bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2600 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002601
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002602 switch (E->getCastKind()) {
2603 default:
2604 break;
2605
John McCall2de56d12010-08-25 11:45:40 +00002606 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002607 case CK_CPointerToObjCPointerCast:
2608 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002609 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002610 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2611 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2612 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002613 if (!E->getType()->isVoidPointerType()) {
2614 if (SubExpr->getType()->isVoidPointerType())
2615 CCEDiag(E, diag::note_constexpr_invalid_cast)
2616 << 3 << SubExpr->getType();
2617 else
2618 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2619 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002620 if (!Visit(SubExpr))
2621 return false;
2622 Result.Designator.setInvalid();
2623 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002624
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002625 case CK_DerivedToBase:
2626 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002627 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002628 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002629 if (!Result.Base && Result.Offset.isZero())
2630 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002631
Richard Smith180f4792011-11-10 06:34:14 +00002632 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002633 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002634 QualType Type =
2635 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002636
Richard Smith180f4792011-11-10 06:34:14 +00002637 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002638 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002639 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002640 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002641 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002642 }
2643
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002644 return true;
2645 }
2646
Richard Smithe24f5fc2011-11-17 22:56:20 +00002647 case CK_BaseToDerived:
2648 if (!Visit(E->getSubExpr()))
2649 return false;
2650 if (!Result.Base && Result.Offset.isZero())
2651 return true;
2652 return HandleBaseToDerivedCast(Info, E, Result);
2653
Richard Smith47a1eed2011-10-29 20:57:55 +00002654 case CK_NullToPointer:
Richard Smitheba05b22011-12-25 20:00:17 +00002655 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002656
John McCall2de56d12010-08-25 11:45:40 +00002657 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002658 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2659
Richard Smith47a1eed2011-10-29 20:57:55 +00002660 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002661 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002662 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002663
John McCallefdb83e2010-05-07 21:00:08 +00002664 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002665 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2666 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002667 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002668 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002669 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002670 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002671 return true;
2672 } else {
2673 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002674 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002675 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002676 }
2677 }
John McCall2de56d12010-08-25 11:45:40 +00002678 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002679 if (SubExpr->isGLValue()) {
2680 if (!EvaluateLValue(SubExpr, Result, Info))
2681 return false;
2682 } else {
2683 Result.set(SubExpr, Info.CurrentCall);
2684 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2685 Info, Result, SubExpr))
2686 return false;
2687 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002688 // The result is a pointer to the first element of the array.
2689 Result.Designator.addIndex(0);
2690 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002691
John McCall2de56d12010-08-25 11:45:40 +00002692 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002693 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002694 }
2695
Richard Smithc49bd112011-10-28 17:51:58 +00002696 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002697}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002698
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002699bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002700 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002701 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002702
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002703 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002704}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002705
2706//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002707// Member Pointer Evaluation
2708//===----------------------------------------------------------------------===//
2709
2710namespace {
2711class MemberPointerExprEvaluator
2712 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2713 MemberPtr &Result;
2714
2715 bool Success(const ValueDecl *D) {
2716 Result = MemberPtr(D);
2717 return true;
2718 }
2719public:
2720
2721 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2722 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2723
2724 bool Success(const CCValue &V, const Expr *E) {
2725 Result.setFrom(V);
2726 return true;
2727 }
Richard Smitheba05b22011-12-25 20:00:17 +00002728 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002729 return Success((const ValueDecl*)0);
2730 }
2731
2732 bool VisitCastExpr(const CastExpr *E);
2733 bool VisitUnaryAddrOf(const UnaryOperator *E);
2734};
2735} // end anonymous namespace
2736
2737static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2738 EvalInfo &Info) {
2739 assert(E->isRValue() && E->getType()->isMemberPointerType());
2740 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2741}
2742
2743bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2744 switch (E->getCastKind()) {
2745 default:
2746 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2747
2748 case CK_NullToMemberPointer:
Richard Smitheba05b22011-12-25 20:00:17 +00002749 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002750
2751 case CK_BaseToDerivedMemberPointer: {
2752 if (!Visit(E->getSubExpr()))
2753 return false;
2754 if (E->path_empty())
2755 return true;
2756 // Base-to-derived member pointer casts store the path in derived-to-base
2757 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2758 // the wrong end of the derived->base arc, so stagger the path by one class.
2759 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2760 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2761 PathI != PathE; ++PathI) {
2762 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2763 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2764 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002765 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002766 }
2767 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2768 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002769 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002770 return true;
2771 }
2772
2773 case CK_DerivedToBaseMemberPointer:
2774 if (!Visit(E->getSubExpr()))
2775 return false;
2776 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2777 PathE = E->path_end(); PathI != PathE; ++PathI) {
2778 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2779 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2780 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002781 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002782 }
2783 return true;
2784 }
2785}
2786
2787bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2788 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2789 // member can be formed.
2790 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2791}
2792
2793//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002794// Record Evaluation
2795//===----------------------------------------------------------------------===//
2796
2797namespace {
2798 class RecordExprEvaluator
2799 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2800 const LValue &This;
2801 APValue &Result;
2802 public:
2803
2804 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2805 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2806
2807 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002808 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002809 }
Richard Smitheba05b22011-12-25 20:00:17 +00002810 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002811
Richard Smith59efe262011-11-11 04:05:33 +00002812 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002813 bool VisitInitListExpr(const InitListExpr *E);
2814 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2815 };
2816}
2817
Richard Smitheba05b22011-12-25 20:00:17 +00002818/// Perform zero-initialization on an object of non-union class type.
2819/// C++11 [dcl.init]p5:
2820/// To zero-initialize an object or reference of type T means:
2821/// [...]
2822/// -- if T is a (possibly cv-qualified) non-union class type,
2823/// each non-static data member and each base-class subobject is
2824/// zero-initialized
2825static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2826 const LValue &This, APValue &Result) {
2827 assert(!RD->isUnion() && "Expected non-union class type");
2828 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2829 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2830 std::distance(RD->field_begin(), RD->field_end()));
2831
2832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2833
2834 if (CD) {
2835 unsigned Index = 0;
2836 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2837 E = CD->bases_end(); I != E; ++I, ++Index) {
2838 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2839 LValue Subobject = This;
2840 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2841 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2842 Result.getStructBase(Index)))
2843 return false;
2844 }
2845 }
2846
2847 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2848 I != E; ++I) {
2849 // -- if T is a reference type, no initialization is performed.
2850 if ((*I)->getType()->isReferenceType())
2851 continue;
2852
2853 LValue Subobject = This;
2854 HandleLValueMember(Info, Subobject, *I, &Layout);
2855
2856 ImplicitValueInitExpr VIE((*I)->getType());
2857 if (!EvaluateConstantExpression(
2858 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2859 return false;
2860 }
2861
2862 return true;
2863}
2864
2865bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2866 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2867 if (RD->isUnion()) {
2868 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2869 // object's first non-static named data member is zero-initialized
2870 RecordDecl::field_iterator I = RD->field_begin();
2871 if (I == RD->field_end()) {
2872 Result = APValue((const FieldDecl*)0);
2873 return true;
2874 }
2875
2876 LValue Subobject = This;
2877 HandleLValueMember(Info, Subobject, *I);
2878 Result = APValue(*I);
2879 ImplicitValueInitExpr VIE((*I)->getType());
2880 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2881 Subobject, &VIE);
2882 }
2883
2884 return HandleClassZeroInitialization(Info, RD, This, Result);
2885}
2886
Richard Smith59efe262011-11-11 04:05:33 +00002887bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2888 switch (E->getCastKind()) {
2889 default:
2890 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2891
2892 case CK_ConstructorConversion:
2893 return Visit(E->getSubExpr());
2894
2895 case CK_DerivedToBase:
2896 case CK_UncheckedDerivedToBase: {
2897 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002898 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002899 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002900 if (!DerivedObject.isStruct())
2901 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002902
2903 // Derived-to-base rvalue conversion: just slice off the derived part.
2904 APValue *Value = &DerivedObject;
2905 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2906 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2907 PathE = E->path_end(); PathI != PathE; ++PathI) {
2908 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2909 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2910 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2911 RD = Base;
2912 }
2913 Result = *Value;
2914 return true;
2915 }
2916 }
2917}
2918
Richard Smith180f4792011-11-10 06:34:14 +00002919bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2920 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2921 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2922
2923 if (RD->isUnion()) {
2924 Result = APValue(E->getInitializedFieldInUnion());
2925 if (!E->getNumInits())
2926 return true;
2927 LValue Subobject = This;
2928 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2929 &Layout);
2930 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2931 Subobject, E->getInit(0));
2932 }
2933
2934 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2935 "initializer list for class with base classes");
2936 Result = APValue(APValue::UninitStruct(), 0,
2937 std::distance(RD->field_begin(), RD->field_end()));
2938 unsigned ElementNo = 0;
2939 for (RecordDecl::field_iterator Field = RD->field_begin(),
2940 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2941 // Anonymous bit-fields are not considered members of the class for
2942 // purposes of aggregate initialization.
2943 if (Field->isUnnamedBitfield())
2944 continue;
2945
2946 LValue Subobject = This;
2947 HandleLValueMember(Info, Subobject, *Field, &Layout);
2948
2949 if (ElementNo < E->getNumInits()) {
2950 if (!EvaluateConstantExpression(
2951 Result.getStructField((*Field)->getFieldIndex()),
2952 Info, Subobject, E->getInit(ElementNo++)))
2953 return false;
2954 } else {
2955 // Perform an implicit value-initialization for members beyond the end of
2956 // the initializer list.
2957 ImplicitValueInitExpr VIE(Field->getType());
2958 if (!EvaluateConstantExpression(
2959 Result.getStructField((*Field)->getFieldIndex()),
2960 Info, Subobject, &VIE))
2961 return false;
2962 }
2963 }
2964
2965 return true;
2966}
2967
2968bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2969 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smitheba05b22011-12-25 20:00:17 +00002970 bool ZeroInit = E->requiresZeroInitialization();
2971 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2972 if (ZeroInit)
2973 return ZeroInitialization(E);
2974
Richard Smith61802452011-12-22 02:22:31 +00002975 const CXXRecordDecl *RD = FD->getParent();
2976 if (RD->isUnion())
2977 Result = APValue((FieldDecl*)0);
2978 else
2979 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2980 std::distance(RD->field_begin(), RD->field_end()));
2981 return true;
2982 }
2983
Richard Smith180f4792011-11-10 06:34:14 +00002984 const FunctionDecl *Definition = 0;
2985 FD->getBody(Definition);
2986
Richard Smithc1c5f272011-12-13 06:39:58 +00002987 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2988 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002989
2990 // FIXME: Elide the copy/move construction wherever we can.
Richard Smitheba05b22011-12-25 20:00:17 +00002991 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00002992 if (const MaterializeTemporaryExpr *ME
2993 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2994 return Visit(ME->GetTemporaryExpr());
2995
Richard Smitheba05b22011-12-25 20:00:17 +00002996 if (ZeroInit && !ZeroInitialization(E))
2997 return false;
2998
Richard Smith180f4792011-11-10 06:34:14 +00002999 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return HandleConstructorCall(E, This, Args,
3001 cast<CXXConstructorDecl>(Definition), Info,
3002 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003003}
3004
3005static bool EvaluateRecord(const Expr *E, const LValue &This,
3006 APValue &Result, EvalInfo &Info) {
3007 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003008 "can't evaluate expression as a record rvalue");
3009 return RecordExprEvaluator(Info, This, Result).Visit(E);
3010}
3011
3012//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003013// Temporary Evaluation
3014//
3015// Temporaries are represented in the AST as rvalues, but generally behave like
3016// lvalues. The full-object of which the temporary is a subobject is implicitly
3017// materialized so that a reference can bind to it.
3018//===----------------------------------------------------------------------===//
3019namespace {
3020class TemporaryExprEvaluator
3021 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3022public:
3023 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3024 LValueExprEvaluatorBaseTy(Info, Result) {}
3025
3026 /// Visit an expression which constructs the value of this temporary.
3027 bool VisitConstructExpr(const Expr *E) {
3028 Result.set(E, Info.CurrentCall);
3029 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3030 Result, E);
3031 }
3032
3033 bool VisitCastExpr(const CastExpr *E) {
3034 switch (E->getCastKind()) {
3035 default:
3036 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3037
3038 case CK_ConstructorConversion:
3039 return VisitConstructExpr(E->getSubExpr());
3040 }
3041 }
3042 bool VisitInitListExpr(const InitListExpr *E) {
3043 return VisitConstructExpr(E);
3044 }
3045 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3046 return VisitConstructExpr(E);
3047 }
3048 bool VisitCallExpr(const CallExpr *E) {
3049 return VisitConstructExpr(E);
3050 }
3051};
3052} // end anonymous namespace
3053
3054/// Evaluate an expression of record type as a temporary.
3055static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003056 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003057 return TemporaryExprEvaluator(Info, Result).Visit(E);
3058}
3059
3060//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003061// Vector Evaluation
3062//===----------------------------------------------------------------------===//
3063
3064namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003065 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003066 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3067 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003068 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Richard Smith07fc6572011-10-22 21:10:00 +00003070 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3071 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Richard Smith07fc6572011-10-22 21:10:00 +00003073 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3074 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3075 // FIXME: remove this APValue copy.
3076 Result = APValue(V.data(), V.size());
3077 return true;
3078 }
Richard Smith69c2c502011-11-04 05:33:44 +00003079 bool Success(const CCValue &V, const Expr *E) {
3080 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003081 Result = V;
3082 return true;
3083 }
Richard Smitheba05b22011-12-25 20:00:17 +00003084 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Richard Smith07fc6572011-10-22 21:10:00 +00003086 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003087 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003088 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003089 bool VisitInitListExpr(const InitListExpr *E);
3090 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003091 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003092 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003093 // shufflevector, ExtVectorElementExpr
3094 // (Note that these require implementing conversions
3095 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00003096 };
3097} // end anonymous namespace
3098
3099static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003100 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003101 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003102}
3103
Richard Smith07fc6572011-10-22 21:10:00 +00003104bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3105 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003106 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Richard Smithd62ca372011-12-06 22:44:34 +00003108 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003109 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003110
Eli Friedman46a52322011-03-25 00:43:55 +00003111 switch (E->getCastKind()) {
3112 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003113 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003114 if (SETy->isIntegerType()) {
3115 APSInt IntResult;
3116 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003117 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003118 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003119 } else if (SETy->isRealFloatingType()) {
3120 APFloat F(0.0);
3121 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003122 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003123 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003124 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003125 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003126 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003127
3128 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003129 SmallVector<APValue, 4> Elts(NElts, Val);
3130 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003131 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003132 case CK_BitCast: {
3133 // Evaluate the operand into an APInt we can extract from.
3134 llvm::APInt SValInt;
3135 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3136 return false;
3137 // Extract the elements
3138 QualType EltTy = VTy->getElementType();
3139 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3140 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3141 SmallVector<APValue, 4> Elts;
3142 if (EltTy->isRealFloatingType()) {
3143 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3144 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3145 unsigned FloatEltSize = EltSize;
3146 if (&Sem == &APFloat::x87DoubleExtended)
3147 FloatEltSize = 80;
3148 for (unsigned i = 0; i < NElts; i++) {
3149 llvm::APInt Elt;
3150 if (BigEndian)
3151 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3152 else
3153 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3154 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3155 }
3156 } else if (EltTy->isIntegerType()) {
3157 for (unsigned i = 0; i < NElts; i++) {
3158 llvm::APInt Elt;
3159 if (BigEndian)
3160 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3161 else
3162 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3163 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3164 }
3165 } else {
3166 return Error(E);
3167 }
3168 return Success(Elts, E);
3169 }
Eli Friedman46a52322011-03-25 00:43:55 +00003170 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003171 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003172 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003173}
3174
Richard Smith07fc6572011-10-22 21:10:00 +00003175bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003176VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003177 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003178 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003179 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Nate Begeman59b5da62009-01-18 03:20:47 +00003181 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003182 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003183
John McCalla7d6c222010-06-11 17:54:15 +00003184 // If a vector is initialized with a single element, that value
3185 // becomes every element of the vector, not just the first.
3186 // This is the behavior described in the IBM AltiVec documentation.
3187 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00003188
3189 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00003190 // vector (OpenCL 6.1.6).
3191 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00003192 return Visit(E->getInit(0));
3193
John McCalla7d6c222010-06-11 17:54:15 +00003194 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00003195 if (EltTy->isIntegerType()) {
3196 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00003197 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003198 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003199 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00003200 } else {
3201 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00003202 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003203 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003204 InitValue = APValue(f);
3205 }
3206 for (unsigned i = 0; i < NumElements; i++) {
3207 Elements.push_back(InitValue);
3208 }
3209 } else {
3210 for (unsigned i = 0; i < NumElements; i++) {
3211 if (EltTy->isIntegerType()) {
3212 llvm::APSInt sInt(32);
3213 if (i < NumInits) {
3214 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003215 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003216 } else {
3217 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3218 }
3219 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00003220 } else {
John McCalla7d6c222010-06-11 17:54:15 +00003221 llvm::APFloat f(0.0);
3222 if (i < NumInits) {
3223 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003224 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003225 } else {
3226 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3227 }
3228 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00003229 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003230 }
3231 }
Richard Smith07fc6572011-10-22 21:10:00 +00003232 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003233}
3234
Richard Smith07fc6572011-10-22 21:10:00 +00003235bool
Richard Smitheba05b22011-12-25 20:00:17 +00003236VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003237 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003238 QualType EltTy = VT->getElementType();
3239 APValue ZeroElement;
3240 if (EltTy->isIntegerType())
3241 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3242 else
3243 ZeroElement =
3244 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3245
Chris Lattner5f9e2722011-07-23 10:55:15 +00003246 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003247 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003248}
3249
Richard Smith07fc6572011-10-22 21:10:00 +00003250bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003251 VisitIgnoredValue(E->getSubExpr());
Richard Smitheba05b22011-12-25 20:00:17 +00003252 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003253}
3254
Nate Begeman59b5da62009-01-18 03:20:47 +00003255//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003256// Array Evaluation
3257//===----------------------------------------------------------------------===//
3258
3259namespace {
3260 class ArrayExprEvaluator
3261 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003262 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003263 APValue &Result;
3264 public:
3265
Richard Smith180f4792011-11-10 06:34:14 +00003266 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3267 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003268
3269 bool Success(const APValue &V, const Expr *E) {
3270 assert(V.isArray() && "Expected array type");
3271 Result = V;
3272 return true;
3273 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003274
Richard Smitheba05b22011-12-25 20:00:17 +00003275 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003276 const ConstantArrayType *CAT =
3277 Info.Ctx.getAsConstantArrayType(E->getType());
3278 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003279 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003280
3281 Result = APValue(APValue::UninitArray(), 0,
3282 CAT->getSize().getZExtValue());
3283 if (!Result.hasArrayFiller()) return true;
3284
Richard Smitheba05b22011-12-25 20:00:17 +00003285 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003286 LValue Subobject = This;
3287 Subobject.Designator.addIndex(0);
3288 ImplicitValueInitExpr VIE(CAT->getElementType());
3289 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3290 Subobject, &VIE);
3291 }
3292
Richard Smithcc5d4f62011-11-07 09:22:26 +00003293 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003294 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003295 };
3296} // end anonymous namespace
3297
Richard Smith180f4792011-11-10 06:34:14 +00003298static bool EvaluateArray(const Expr *E, const LValue &This,
3299 APValue &Result, EvalInfo &Info) {
Richard Smitheba05b22011-12-25 20:00:17 +00003300 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003301 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003302}
3303
3304bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3305 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3306 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003307 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003308
Richard Smith974c5f92011-12-22 01:07:19 +00003309 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3310 // an appropriately-typed string literal enclosed in braces.
3311 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3312 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3313 LValue LV;
3314 if (!EvaluateLValue(E->getInit(0), LV, Info))
3315 return false;
3316 uint64_t NumElements = CAT->getSize().getZExtValue();
3317 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3318
3319 // Copy the string literal into the array. FIXME: Do this better.
3320 LV.Designator.addIndex(0);
3321 for (uint64_t I = 0; I < NumElements; ++I) {
3322 CCValue Char;
3323 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3324 CAT->getElementType(), LV, Char))
3325 return false;
3326 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3327 Result.getArrayInitializedElt(I)))
3328 return false;
3329 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3330 return false;
3331 }
3332 return true;
3333 }
3334
Richard Smithcc5d4f62011-11-07 09:22:26 +00003335 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3336 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003337 LValue Subobject = This;
3338 Subobject.Designator.addIndex(0);
3339 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003340 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003341 I != End; ++I, ++Index) {
3342 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3343 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003344 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003345 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3346 return false;
3347 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003348
3349 if (!Result.hasArrayFiller()) return true;
3350 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003351 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3352 // but sometimes does:
3353 // struct S { constexpr S() : p(&p) {} void *p; };
3354 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003355 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003356 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003357}
3358
Richard Smithe24f5fc2011-11-17 22:56:20 +00003359bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3360 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3361 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003362 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003363
3364 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3365 if (!Result.hasArrayFiller())
3366 return true;
3367
3368 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003369
Richard Smitheba05b22011-12-25 20:00:17 +00003370 bool ZeroInit = E->requiresZeroInitialization();
3371 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3372 if (ZeroInit) {
3373 LValue Subobject = This;
3374 Subobject.Designator.addIndex(0);
3375 ImplicitValueInitExpr VIE(CAT->getElementType());
3376 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3377 Subobject, &VIE);
3378 }
3379
Richard Smith61802452011-12-22 02:22:31 +00003380 const CXXRecordDecl *RD = FD->getParent();
3381 if (RD->isUnion())
3382 Result.getArrayFiller() = APValue((FieldDecl*)0);
3383 else
3384 Result.getArrayFiller() =
3385 APValue(APValue::UninitStruct(), RD->getNumBases(),
3386 std::distance(RD->field_begin(), RD->field_end()));
3387 return true;
3388 }
3389
Richard Smithe24f5fc2011-11-17 22:56:20 +00003390 const FunctionDecl *Definition = 0;
3391 FD->getBody(Definition);
3392
Richard Smithc1c5f272011-12-13 06:39:58 +00003393 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3394 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003395
3396 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3397 // but sometimes does:
3398 // struct S { constexpr S() : p(&p) {} void *p; };
3399 // S s[10];
3400 LValue Subobject = This;
3401 Subobject.Designator.addIndex(0);
Richard Smitheba05b22011-12-25 20:00:17 +00003402
3403 if (ZeroInit) {
3404 ImplicitValueInitExpr VIE(CAT->getElementType());
3405 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3406 &VIE))
3407 return false;
3408 }
3409
Richard Smithe24f5fc2011-11-17 22:56:20 +00003410 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003411 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003412 cast<CXXConstructorDecl>(Definition),
3413 Info, Result.getArrayFiller());
3414}
3415
Richard Smithcc5d4f62011-11-07 09:22:26 +00003416//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003417// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003418//
3419// As a GNU extension, we support casting pointers to sufficiently-wide integer
3420// types and back in constant folding. Integer values are thus represented
3421// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003422//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003423
3424namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003425class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003426 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003427 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003428public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003429 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003430 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003431
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003432 bool Success(const llvm::APSInt &SI, const Expr *E) {
3433 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003434 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003435 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003436 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003437 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003438 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003439 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003440 return true;
3441 }
3442
Daniel Dunbar131eb432009-02-19 09:06:44 +00003443 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003444 assert(E->getType()->isIntegralOrEnumerationType() &&
3445 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003446 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003447 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003448 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003449 Result.getInt().setIsUnsigned(
3450 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003451 return true;
3452 }
3453
3454 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003455 assert(E->getType()->isIntegralOrEnumerationType() &&
3456 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003457 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003458 return true;
3459 }
3460
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003461 bool Success(CharUnits Size, const Expr *E) {
3462 return Success(Size.getQuantity(), E);
3463 }
3464
Richard Smith47a1eed2011-10-29 20:57:55 +00003465 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003466 if (V.isLValue()) {
3467 Result = V;
3468 return true;
3469 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003470 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Richard Smitheba05b22011-12-25 20:00:17 +00003473 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003474
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003475 //===--------------------------------------------------------------------===//
3476 // Visitor Methods
3477 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003478
Chris Lattner4c4867e2008-07-12 00:38:25 +00003479 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003480 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003481 }
3482 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003483 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003484 }
Eli Friedman04309752009-11-24 05:28:59 +00003485
3486 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3487 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003488 if (CheckReferencedDecl(E, E->getDecl()))
3489 return true;
3490
3491 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003492 }
3493 bool VisitMemberExpr(const MemberExpr *E) {
3494 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003495 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003496 return true;
3497 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003498
3499 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003500 }
3501
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003502 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003503 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003504 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003505 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003506
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003507 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003508 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003509
Anders Carlsson3068d112008-11-16 19:01:22 +00003510 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003511 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003512 }
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Richard Smithf10d9172011-10-11 21:43:33 +00003514 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003515 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00003516 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003517 }
3518
Sebastian Redl64b45f72009-01-05 20:52:13 +00003519 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003520 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003521 }
3522
Francois Pichet6ad6f282010-12-07 00:08:36 +00003523 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3524 return Success(E->getValue(), E);
3525 }
3526
John Wiegley21ff2e52011-04-28 00:16:57 +00003527 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3528 return Success(E->getValue(), E);
3529 }
3530
John Wiegley55262202011-04-25 06:54:41 +00003531 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3532 return Success(E->getValue(), E);
3533 }
3534
Eli Friedman722c7172009-02-28 03:59:05 +00003535 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003536 bool VisitUnaryImag(const UnaryOperator *E);
3537
Sebastian Redl295995c2010-09-10 20:55:47 +00003538 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003539 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003540
Chris Lattnerfcee0012008-07-11 21:24:13 +00003541private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003542 CharUnits GetAlignOfExpr(const Expr *E);
3543 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003544 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003545 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003546 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003547};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003548} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003549
Richard Smithc49bd112011-10-28 17:51:58 +00003550/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3551/// produce either the integer value or a pointer.
3552///
3553/// GCC has a heinous extension which folds casts between pointer types and
3554/// pointer-sized integral types. We support this by allowing the evaluation of
3555/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3556/// Some simple arithmetic on such values is supported (they are treated much
3557/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003558static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003559 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003560 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003561 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003562}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003563
Richard Smithf48fdb02011-12-09 22:58:01 +00003564static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003565 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003566 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003567 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003568 if (!Val.isInt()) {
3569 // FIXME: It would be better to produce the diagnostic for casting
3570 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003571 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003572 return false;
3573 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003574 Result = Val.getInt();
3575 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003576}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003577
Richard Smithf48fdb02011-12-09 22:58:01 +00003578/// Check whether the given declaration can be directly converted to an integral
3579/// rvalue. If not, no diagnostic is produced; there are other things we can
3580/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003581bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003582 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003583 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003584 // Check for signedness/width mismatches between E type and ECD value.
3585 bool SameSign = (ECD->getInitVal().isSigned()
3586 == E->getType()->isSignedIntegerOrEnumerationType());
3587 bool SameWidth = (ECD->getInitVal().getBitWidth()
3588 == Info.Ctx.getIntWidth(E->getType()));
3589 if (SameSign && SameWidth)
3590 return Success(ECD->getInitVal(), E);
3591 else {
3592 // Get rid of mismatch (otherwise Success assertions will fail)
3593 // by computing a new value matching the type of E.
3594 llvm::APSInt Val = ECD->getInitVal();
3595 if (!SameSign)
3596 Val.setIsSigned(!ECD->getInitVal().isSigned());
3597 if (!SameWidth)
3598 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3599 return Success(Val, E);
3600 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003601 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003602 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003603}
3604
Chris Lattnera4d55d82008-10-06 06:40:35 +00003605/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3606/// as GCC.
3607static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3608 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003609 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003610 enum gcc_type_class {
3611 no_type_class = -1,
3612 void_type_class, integer_type_class, char_type_class,
3613 enumeral_type_class, boolean_type_class,
3614 pointer_type_class, reference_type_class, offset_type_class,
3615 real_type_class, complex_type_class,
3616 function_type_class, method_type_class,
3617 record_type_class, union_type_class,
3618 array_type_class, string_type_class,
3619 lang_type_class
3620 };
Mike Stump1eb44332009-09-09 15:08:12 +00003621
3622 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003623 // ideal, however it is what gcc does.
3624 if (E->getNumArgs() == 0)
3625 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Chris Lattnera4d55d82008-10-06 06:40:35 +00003627 QualType ArgTy = E->getArg(0)->getType();
3628 if (ArgTy->isVoidType())
3629 return void_type_class;
3630 else if (ArgTy->isEnumeralType())
3631 return enumeral_type_class;
3632 else if (ArgTy->isBooleanType())
3633 return boolean_type_class;
3634 else if (ArgTy->isCharType())
3635 return string_type_class; // gcc doesn't appear to use char_type_class
3636 else if (ArgTy->isIntegerType())
3637 return integer_type_class;
3638 else if (ArgTy->isPointerType())
3639 return pointer_type_class;
3640 else if (ArgTy->isReferenceType())
3641 return reference_type_class;
3642 else if (ArgTy->isRealType())
3643 return real_type_class;
3644 else if (ArgTy->isComplexType())
3645 return complex_type_class;
3646 else if (ArgTy->isFunctionType())
3647 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003648 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003649 return record_type_class;
3650 else if (ArgTy->isUnionType())
3651 return union_type_class;
3652 else if (ArgTy->isArrayType())
3653 return array_type_class;
3654 else if (ArgTy->isUnionType())
3655 return union_type_class;
3656 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003657 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003658 return -1;
3659}
3660
Richard Smith80d4b552011-12-28 19:48:30 +00003661/// EvaluateBuiltinConstantPForLValue - Determine the result of
3662/// __builtin_constant_p when applied to the given lvalue.
3663///
3664/// An lvalue is only "constant" if it is a pointer or reference to the first
3665/// character of a string literal.
3666template<typename LValue>
3667static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3668 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3669 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3670}
3671
3672/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3673/// GCC as we can manage.
3674static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3675 QualType ArgType = Arg->getType();
3676
3677 // __builtin_constant_p always has one operand. The rules which gcc follows
3678 // are not precisely documented, but are as follows:
3679 //
3680 // - If the operand is of integral, floating, complex or enumeration type,
3681 // and can be folded to a known value of that type, it returns 1.
3682 // - If the operand and can be folded to a pointer to the first character
3683 // of a string literal (or such a pointer cast to an integral type), it
3684 // returns 1.
3685 //
3686 // Otherwise, it returns 0.
3687 //
3688 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3689 // its support for this does not currently work.
3690 if (ArgType->isIntegralOrEnumerationType()) {
3691 Expr::EvalResult Result;
3692 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3693 return false;
3694
3695 APValue &V = Result.Val;
3696 if (V.getKind() == APValue::Int)
3697 return true;
3698
3699 return EvaluateBuiltinConstantPForLValue(V);
3700 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3701 return Arg->isEvaluatable(Ctx);
3702 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3703 LValue LV;
3704 Expr::EvalStatus Status;
3705 EvalInfo Info(Ctx, Status);
3706 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3707 : EvaluatePointer(Arg, LV, Info)) &&
3708 !Status.HasSideEffects)
3709 return EvaluateBuiltinConstantPForLValue(LV);
3710 }
3711
3712 // Anything else isn't considered to be sufficiently constant.
3713 return false;
3714}
3715
John McCall42c8f872010-05-10 23:27:23 +00003716/// Retrieves the "underlying object type" of the given expression,
3717/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003718QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3719 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3720 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003721 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003722 } else if (const Expr *E = B.get<const Expr*>()) {
3723 if (isa<CompoundLiteralExpr>(E))
3724 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003725 }
3726
3727 return QualType();
3728}
3729
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003730bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003731 // TODO: Perhaps we should let LLVM lower this?
3732 LValue Base;
3733 if (!EvaluatePointer(E->getArg(0), Base, Info))
3734 return false;
3735
3736 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003737 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003738
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003739 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003740 if (T.isNull() ||
3741 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003742 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003743 T->isVariablyModifiedType() ||
3744 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003745 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003746
3747 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3748 CharUnits Offset = Base.getLValueOffset();
3749
3750 if (!Offset.isNegative() && Offset <= Size)
3751 Size -= Offset;
3752 else
3753 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003754 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003755}
3756
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003757bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003758 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003759 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003760 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003761
3762 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003763 if (TryEvaluateBuiltinObjectSize(E))
3764 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003765
Eric Christopherb2aaf512010-01-19 22:58:35 +00003766 // If evaluating the argument has side-effects we can't determine
3767 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003768 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003769 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003770 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003771 return Success(0, E);
3772 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003773
Richard Smithf48fdb02011-12-09 22:58:01 +00003774 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003775 }
3776
Chris Lattner019f4e82008-10-06 05:28:25 +00003777 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003778 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003779
Richard Smith80d4b552011-12-28 19:48:30 +00003780 case Builtin::BI__builtin_constant_p:
3781 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00003782
Chris Lattner21fb98e2009-09-23 06:06:36 +00003783 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003784 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003785 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003786 return Success(Operand, E);
3787 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003788
3789 case Builtin::BI__builtin_expect:
3790 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003791
3792 case Builtin::BIstrlen:
3793 case Builtin::BI__builtin_strlen:
3794 // As an extension, we support strlen() and __builtin_strlen() as constant
3795 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003796 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003797 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3798 // The string literal may have embedded null characters. Find the first
3799 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003800 StringRef Str = S->getString();
3801 StringRef::size_type Pos = Str.find(0);
3802 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003803 Str = Str.substr(0, Pos);
3804
3805 return Success(Str.size(), E);
3806 }
3807
Richard Smithf48fdb02011-12-09 22:58:01 +00003808 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003809
3810 case Builtin::BI__atomic_is_lock_free: {
3811 APSInt SizeVal;
3812 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3813 return false;
3814
3815 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3816 // of two less than the maximum inline atomic width, we know it is
3817 // lock-free. If the size isn't a power of two, or greater than the
3818 // maximum alignment where we promote atomics, we know it is not lock-free
3819 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3820 // the answer can only be determined at runtime; for example, 16-byte
3821 // atomics have lock-free implementations on some, but not all,
3822 // x86-64 processors.
3823
3824 // Check power-of-two.
3825 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3826 if (!Size.isPowerOfTwo())
3827#if 0
3828 // FIXME: Suppress this folding until the ABI for the promotion width
3829 // settles.
3830 return Success(0, E);
3831#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003832 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003833#endif
3834
3835#if 0
3836 // Check against promotion width.
3837 // FIXME: Suppress this folding until the ABI for the promotion width
3838 // settles.
3839 unsigned PromoteWidthBits =
3840 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3841 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3842 return Success(0, E);
3843#endif
3844
3845 // Check against inlining width.
3846 unsigned InlineWidthBits =
3847 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3848 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3849 return Success(1, E);
3850
Richard Smithf48fdb02011-12-09 22:58:01 +00003851 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003852 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003853 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003854}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003855
Richard Smith625b8072011-10-31 01:37:14 +00003856static bool HasSameBase(const LValue &A, const LValue &B) {
3857 if (!A.getLValueBase())
3858 return !B.getLValueBase();
3859 if (!B.getLValueBase())
3860 return false;
3861
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003862 if (A.getLValueBase().getOpaqueValue() !=
3863 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003864 const Decl *ADecl = GetLValueBaseDecl(A);
3865 if (!ADecl)
3866 return false;
3867 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003868 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003869 return false;
3870 }
3871
3872 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003873 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003874}
3875
Chris Lattnerb542afe2008-07-11 19:10:17 +00003876bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003877 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003878 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003879
John McCall2de56d12010-08-25 11:45:40 +00003880 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003881 VisitIgnoredValue(E->getLHS());
3882 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003883 }
3884
3885 if (E->isLogicalOp()) {
3886 // These need to be handled specially because the operands aren't
3887 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003888 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Richard Smithc49bd112011-10-28 17:51:58 +00003890 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003891 // We were able to evaluate the LHS, see if we can get away with not
3892 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003893 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003894 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003895
Richard Smithc49bd112011-10-28 17:51:58 +00003896 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003897 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003898 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003899 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003900 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003901 }
3902 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003903 // FIXME: If both evaluations fail, we should produce the diagnostic from
3904 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3905 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003906 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003907 // We can't evaluate the LHS; however, sometimes the result
3908 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003909 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003910 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003911 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003912 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003913
3914 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003915 }
3916 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003917 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003918
Eli Friedmana6afa762008-11-13 06:09:17 +00003919 return false;
3920 }
3921
Anders Carlsson286f85e2008-11-16 07:17:21 +00003922 QualType LHSTy = E->getLHS()->getType();
3923 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003924
3925 if (LHSTy->isAnyComplexType()) {
3926 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003927 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003928
3929 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3930 return false;
3931
3932 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3933 return false;
3934
3935 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003936 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003937 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003938 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003939 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3940
John McCall2de56d12010-08-25 11:45:40 +00003941 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003942 return Success((CR_r == APFloat::cmpEqual &&
3943 CR_i == APFloat::cmpEqual), E);
3944 else {
John McCall2de56d12010-08-25 11:45:40 +00003945 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003946 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003947 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003948 CR_r == APFloat::cmpLessThan ||
3949 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003950 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003951 CR_i == APFloat::cmpLessThan ||
3952 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003953 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003954 } else {
John McCall2de56d12010-08-25 11:45:40 +00003955 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003956 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3957 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3958 else {
John McCall2de56d12010-08-25 11:45:40 +00003959 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003960 "Invalid compex comparison.");
3961 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3962 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3963 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003964 }
3965 }
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Anders Carlsson286f85e2008-11-16 07:17:21 +00003967 if (LHSTy->isRealFloatingType() &&
3968 RHSTy->isRealFloatingType()) {
3969 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Anders Carlsson286f85e2008-11-16 07:17:21 +00003971 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3972 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Anders Carlsson286f85e2008-11-16 07:17:21 +00003974 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3975 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Anders Carlsson286f85e2008-11-16 07:17:21 +00003977 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003978
Anders Carlsson286f85e2008-11-16 07:17:21 +00003979 switch (E->getOpcode()) {
3980 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003981 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003982 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003983 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003984 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003985 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003986 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003987 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003988 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003989 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003990 E);
John McCall2de56d12010-08-25 11:45:40 +00003991 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003992 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003993 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003994 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003995 || CR == APFloat::cmpLessThan
3996 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003997 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004000 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004001 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00004002 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004003 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4004 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004005
John McCallefdb83e2010-05-07 21:00:08 +00004006 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004007 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4008 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004009
Richard Smith625b8072011-10-31 01:37:14 +00004010 // Reject differing bases from the normal codepath; we special-case
4011 // comparisons to null.
4012 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00004013 // Inequalities and subtractions between unrelated pointers have
4014 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004015 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004016 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004017 // A constant address may compare equal to the address of a symbol.
4018 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004019 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004020 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4021 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004022 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004023 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004024 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004025 // distinct. However, we do know that the address of a literal will be
4026 // non-null.
4027 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4028 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004029 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004030 // We can't tell whether weak symbols will end up pointing to the same
4031 // object.
4032 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004033 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004034 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004035 // (Note that clang defaults to -fmerge-all-constants, which can
4036 // lead to inconsistent results for comparisons involving the address
4037 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004038 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004039 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004040
Richard Smithcc5d4f62011-11-07 09:22:26 +00004041 // FIXME: Implement the C++11 restrictions:
4042 // - Pointer subtractions must be on elements of the same array.
4043 // - Pointer comparisons must be between members with the same access.
4044
John McCall2de56d12010-08-25 11:45:40 +00004045 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004046 QualType Type = E->getLHS()->getType();
4047 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004048
Richard Smith180f4792011-11-10 06:34:14 +00004049 CharUnits ElementSize;
4050 if (!HandleSizeof(Info, ElementType, ElementSize))
4051 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004052
Richard Smith180f4792011-11-10 06:34:14 +00004053 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004054 RHSValue.getLValueOffset();
4055 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004056 }
Richard Smith625b8072011-10-31 01:37:14 +00004057
4058 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4059 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4060 switch (E->getOpcode()) {
4061 default: llvm_unreachable("missing comparison operator");
4062 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4063 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4064 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4065 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4066 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4067 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004068 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004069 }
4070 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004071 if (!LHSTy->isIntegralOrEnumerationType() ||
4072 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004073 // We can't continue from here for non-integral types.
4074 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004075 }
4076
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004077 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004078 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00004079 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00004080 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004081
Richard Smithc49bd112011-10-28 17:51:58 +00004082 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004083 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004084 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004085
4086 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004087 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004088 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4089 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004090 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004091 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004092 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004093 LHSVal.getLValueOffset() -= AdditionalOffset;
4094 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004095 return true;
4096 }
4097
4098 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004099 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004100 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004101 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4102 LHSVal.getInt().getZExtValue());
4103 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004104 return true;
4105 }
4106
4107 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004108 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004109 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004110
Richard Smithc49bd112011-10-28 17:51:58 +00004111 APSInt &LHS = LHSVal.getInt();
4112 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004113
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004114 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004115 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004116 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004117 case BO_Mul: return Success(LHS * RHS, E);
4118 case BO_Add: return Success(LHS + RHS, E);
4119 case BO_Sub: return Success(LHS - RHS, E);
4120 case BO_And: return Success(LHS & RHS, E);
4121 case BO_Xor: return Success(LHS ^ RHS, E);
4122 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004123 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004124 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004125 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004126 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004127 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004128 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004129 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004130 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004131 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004132 // During constant-folding, a negative shift is an opposite shift.
4133 if (RHS.isSigned() && RHS.isNegative()) {
4134 RHS = -RHS;
4135 goto shift_right;
4136 }
4137
4138 shift_left:
4139 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004140 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4141 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004142 }
John McCall2de56d12010-08-25 11:45:40 +00004143 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004144 // During constant-folding, a negative shift is an opposite shift.
4145 if (RHS.isSigned() && RHS.isNegative()) {
4146 RHS = -RHS;
4147 goto shift_left;
4148 }
4149
4150 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004151 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004152 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4153 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004154 }
Mike Stump1eb44332009-09-09 15:08:12 +00004155
Richard Smithc49bd112011-10-28 17:51:58 +00004156 case BO_LT: return Success(LHS < RHS, E);
4157 case BO_GT: return Success(LHS > RHS, E);
4158 case BO_LE: return Success(LHS <= RHS, E);
4159 case BO_GE: return Success(LHS >= RHS, E);
4160 case BO_EQ: return Success(LHS == RHS, E);
4161 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004162 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004163}
4164
Ken Dyck8b752f12010-01-27 17:10:57 +00004165CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004166 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4167 // the result is the size of the referenced type."
4168 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4169 // result shall be the alignment of the referenced type."
4170 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4171 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004172
4173 // __alignof is defined to return the preferred alignment.
4174 return Info.Ctx.toCharUnitsFromBits(
4175 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004176}
4177
Ken Dyck8b752f12010-01-27 17:10:57 +00004178CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004179 E = E->IgnoreParens();
4180
4181 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004182 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004183 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004184 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4185 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004186
Chris Lattneraf707ab2009-01-24 21:53:27 +00004187 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004188 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4189 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004190
Chris Lattnere9feb472009-01-24 21:09:06 +00004191 return GetAlignOfType(E->getType());
4192}
4193
4194
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004195/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4196/// a result as the expression's type.
4197bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4198 const UnaryExprOrTypeTraitExpr *E) {
4199 switch(E->getKind()) {
4200 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004201 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004202 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004203 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004204 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004205 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004206
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004207 case UETT_VecStep: {
4208 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004209
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004210 if (Ty->isVectorType()) {
4211 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004212
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004213 // The vec_step built-in functions that take a 3-component
4214 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4215 if (n == 3)
4216 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004217
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004218 return Success(n, E);
4219 } else
4220 return Success(1, E);
4221 }
4222
4223 case UETT_SizeOf: {
4224 QualType SrcTy = E->getTypeOfArgument();
4225 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4226 // the result is the size of the referenced type."
4227 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4228 // result shall be the alignment of the referenced type."
4229 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4230 SrcTy = Ref->getPointeeType();
4231
Richard Smith180f4792011-11-10 06:34:14 +00004232 CharUnits Sizeof;
4233 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004234 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004235 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004236 }
4237 }
4238
4239 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00004240 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00004241}
4242
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004243bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004244 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004245 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004246 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004247 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004248 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004249 for (unsigned i = 0; i != n; ++i) {
4250 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4251 switch (ON.getKind()) {
4252 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004253 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004254 APSInt IdxResult;
4255 if (!EvaluateInteger(Idx, IdxResult, Info))
4256 return false;
4257 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4258 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004259 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004260 CurrentType = AT->getElementType();
4261 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4262 Result += IdxResult.getSExtValue() * ElementSize;
4263 break;
4264 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004265
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004266 case OffsetOfExpr::OffsetOfNode::Field: {
4267 FieldDecl *MemberDecl = ON.getField();
4268 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004269 if (!RT)
4270 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004271 RecordDecl *RD = RT->getDecl();
4272 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004273 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004274 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004275 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004276 CurrentType = MemberDecl->getType().getNonReferenceType();
4277 break;
4278 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004279
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004280 case OffsetOfExpr::OffsetOfNode::Identifier:
4281 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004282 return Error(OOE);
4283
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004284 case OffsetOfExpr::OffsetOfNode::Base: {
4285 CXXBaseSpecifier *BaseSpec = ON.getBase();
4286 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004287 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004288
4289 // Find the layout of the class whose base we are looking into.
4290 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004291 if (!RT)
4292 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004293 RecordDecl *RD = RT->getDecl();
4294 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4295
4296 // Find the base class itself.
4297 CurrentType = BaseSpec->getType();
4298 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4299 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004300 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004301
4302 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004303 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004304 break;
4305 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004306 }
4307 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004308 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004309}
4310
Chris Lattnerb542afe2008-07-11 19:10:17 +00004311bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004312 switch (E->getOpcode()) {
4313 default:
4314 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4315 // See C99 6.6p3.
4316 return Error(E);
4317 case UO_Extension:
4318 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4319 // If so, we could clear the diagnostic ID.
4320 return Visit(E->getSubExpr());
4321 case UO_Plus:
4322 // The result is just the value.
4323 return Visit(E->getSubExpr());
4324 case UO_Minus: {
4325 if (!Visit(E->getSubExpr()))
4326 return false;
4327 if (!Result.isInt()) return Error(E);
4328 return Success(-Result.getInt(), E);
4329 }
4330 case UO_Not: {
4331 if (!Visit(E->getSubExpr()))
4332 return false;
4333 if (!Result.isInt()) return Error(E);
4334 return Success(~Result.getInt(), E);
4335 }
4336 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004337 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004338 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004339 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004340 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004341 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004342 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004343}
Mike Stump1eb44332009-09-09 15:08:12 +00004344
Chris Lattner732b2232008-07-12 01:15:53 +00004345/// HandleCast - This is used to evaluate implicit or explicit casts where the
4346/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004347bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4348 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004349 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004350 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004351
Eli Friedman46a52322011-03-25 00:43:55 +00004352 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004353 case CK_BaseToDerived:
4354 case CK_DerivedToBase:
4355 case CK_UncheckedDerivedToBase:
4356 case CK_Dynamic:
4357 case CK_ToUnion:
4358 case CK_ArrayToPointerDecay:
4359 case CK_FunctionToPointerDecay:
4360 case CK_NullToPointer:
4361 case CK_NullToMemberPointer:
4362 case CK_BaseToDerivedMemberPointer:
4363 case CK_DerivedToBaseMemberPointer:
4364 case CK_ConstructorConversion:
4365 case CK_IntegralToPointer:
4366 case CK_ToVoid:
4367 case CK_VectorSplat:
4368 case CK_IntegralToFloating:
4369 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004370 case CK_CPointerToObjCPointerCast:
4371 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004372 case CK_AnyPointerToBlockPointerCast:
4373 case CK_ObjCObjectLValueCast:
4374 case CK_FloatingRealToComplex:
4375 case CK_FloatingComplexToReal:
4376 case CK_FloatingComplexCast:
4377 case CK_FloatingComplexToIntegralComplex:
4378 case CK_IntegralRealToComplex:
4379 case CK_IntegralComplexCast:
4380 case CK_IntegralComplexToFloatingComplex:
4381 llvm_unreachable("invalid cast kind for integral value");
4382
Eli Friedmane50c2972011-03-25 19:07:11 +00004383 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004384 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004385 case CK_LValueBitCast:
4386 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004387 case CK_ARCProduceObject:
4388 case CK_ARCConsumeObject:
4389 case CK_ARCReclaimReturnedObject:
4390 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004391 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004392
4393 case CK_LValueToRValue:
4394 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004395 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004396
4397 case CK_MemberPointerToBoolean:
4398 case CK_PointerToBoolean:
4399 case CK_IntegralToBoolean:
4400 case CK_FloatingToBoolean:
4401 case CK_FloatingComplexToBoolean:
4402 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004403 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004404 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004405 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004406 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004407 }
4408
Eli Friedman46a52322011-03-25 00:43:55 +00004409 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004410 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004411 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004412
Eli Friedmanbe265702009-02-20 01:15:07 +00004413 if (!Result.isInt()) {
4414 // Only allow casts of lvalues if they are lossless.
4415 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4416 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004417
Daniel Dunbardd211642009-02-19 22:24:01 +00004418 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004419 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004420 }
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Eli Friedman46a52322011-03-25 00:43:55 +00004422 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004423 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4424
John McCallefdb83e2010-05-07 21:00:08 +00004425 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004426 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004427 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004428
Daniel Dunbardd211642009-02-19 22:24:01 +00004429 if (LV.getLValueBase()) {
4430 // Only allow based lvalue casts if they are lossless.
4431 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004432 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004433
Richard Smithb755a9d2011-11-16 07:18:12 +00004434 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004435 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004436 return true;
4437 }
4438
Ken Dycka7305832010-01-15 12:37:54 +00004439 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4440 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004441 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004442 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004443
Eli Friedman46a52322011-03-25 00:43:55 +00004444 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004445 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004446 if (!EvaluateComplex(SubExpr, C, Info))
4447 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004448 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004449 }
Eli Friedman2217c872009-02-22 11:46:18 +00004450
Eli Friedman46a52322011-03-25 00:43:55 +00004451 case CK_FloatingToIntegral: {
4452 APFloat F(0.0);
4453 if (!EvaluateFloat(SubExpr, F, Info))
4454 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004455
Richard Smithc1c5f272011-12-13 06:39:58 +00004456 APSInt Value;
4457 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4458 return false;
4459 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004460 }
4461 }
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Eli Friedman46a52322011-03-25 00:43:55 +00004463 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004464 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004465}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004466
Eli Friedman722c7172009-02-28 03:59:05 +00004467bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4468 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004469 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004470 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4471 return false;
4472 if (!LV.isComplexInt())
4473 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004474 return Success(LV.getComplexIntReal(), E);
4475 }
4476
4477 return Visit(E->getSubExpr());
4478}
4479
Eli Friedman664a1042009-02-27 04:45:43 +00004480bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004481 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004482 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004483 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4484 return false;
4485 if (!LV.isComplexInt())
4486 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004487 return Success(LV.getComplexIntImag(), E);
4488 }
4489
Richard Smith8327fad2011-10-24 18:44:57 +00004490 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004491 return Success(0, E);
4492}
4493
Douglas Gregoree8aff02011-01-04 17:33:58 +00004494bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4495 return Success(E->getPackLength(), E);
4496}
4497
Sebastian Redl295995c2010-09-10 20:55:47 +00004498bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4499 return Success(E->getValue(), E);
4500}
4501
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004502//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004503// Float Evaluation
4504//===----------------------------------------------------------------------===//
4505
4506namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004507class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004508 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004509 APFloat &Result;
4510public:
4511 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004512 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004513
Richard Smith47a1eed2011-10-29 20:57:55 +00004514 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004515 Result = V.getFloat();
4516 return true;
4517 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004518
Richard Smitheba05b22011-12-25 20:00:17 +00004519 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004520 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4521 return true;
4522 }
4523
Chris Lattner019f4e82008-10-06 05:28:25 +00004524 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004525
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004526 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004527 bool VisitBinaryOperator(const BinaryOperator *E);
4528 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004529 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004530
John McCallabd3a852010-05-07 22:08:54 +00004531 bool VisitUnaryReal(const UnaryOperator *E);
4532 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004533
Richard Smitheba05b22011-12-25 20:00:17 +00004534 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004535};
4536} // end anonymous namespace
4537
4538static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004539 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004540 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004541}
4542
Jay Foad4ba2a172011-01-12 09:06:06 +00004543static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004544 QualType ResultTy,
4545 const Expr *Arg,
4546 bool SNaN,
4547 llvm::APFloat &Result) {
4548 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4549 if (!S) return false;
4550
4551 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4552
4553 llvm::APInt fill;
4554
4555 // Treat empty strings as if they were zero.
4556 if (S->getString().empty())
4557 fill = llvm::APInt(32, 0);
4558 else if (S->getString().getAsInteger(0, fill))
4559 return false;
4560
4561 if (SNaN)
4562 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4563 else
4564 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4565 return true;
4566}
4567
Chris Lattner019f4e82008-10-06 05:28:25 +00004568bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004569 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004570 default:
4571 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4572
Chris Lattner019f4e82008-10-06 05:28:25 +00004573 case Builtin::BI__builtin_huge_val:
4574 case Builtin::BI__builtin_huge_valf:
4575 case Builtin::BI__builtin_huge_vall:
4576 case Builtin::BI__builtin_inf:
4577 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004578 case Builtin::BI__builtin_infl: {
4579 const llvm::fltSemantics &Sem =
4580 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004581 Result = llvm::APFloat::getInf(Sem);
4582 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004583 }
Mike Stump1eb44332009-09-09 15:08:12 +00004584
John McCalldb7b72a2010-02-28 13:00:19 +00004585 case Builtin::BI__builtin_nans:
4586 case Builtin::BI__builtin_nansf:
4587 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004588 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4589 true, Result))
4590 return Error(E);
4591 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004592
Chris Lattner9e621712008-10-06 06:31:58 +00004593 case Builtin::BI__builtin_nan:
4594 case Builtin::BI__builtin_nanf:
4595 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004596 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004597 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004598 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4599 false, Result))
4600 return Error(E);
4601 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004602
4603 case Builtin::BI__builtin_fabs:
4604 case Builtin::BI__builtin_fabsf:
4605 case Builtin::BI__builtin_fabsl:
4606 if (!EvaluateFloat(E->getArg(0), Result, Info))
4607 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004609 if (Result.isNegative())
4610 Result.changeSign();
4611 return true;
4612
Mike Stump1eb44332009-09-09 15:08:12 +00004613 case Builtin::BI__builtin_copysign:
4614 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004615 case Builtin::BI__builtin_copysignl: {
4616 APFloat RHS(0.);
4617 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4618 !EvaluateFloat(E->getArg(1), RHS, Info))
4619 return false;
4620 Result.copySign(RHS);
4621 return true;
4622 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004623 }
4624}
4625
John McCallabd3a852010-05-07 22:08:54 +00004626bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004627 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4628 ComplexValue CV;
4629 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4630 return false;
4631 Result = CV.FloatReal;
4632 return true;
4633 }
4634
4635 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004636}
4637
4638bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004639 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4640 ComplexValue CV;
4641 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4642 return false;
4643 Result = CV.FloatImag;
4644 return true;
4645 }
4646
Richard Smith8327fad2011-10-24 18:44:57 +00004647 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004648 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4649 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004650 return true;
4651}
4652
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004653bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004654 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004655 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004656 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004657 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004658 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004659 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4660 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004661 Result.changeSign();
4662 return true;
4663 }
4664}
Chris Lattner019f4e82008-10-06 05:28:25 +00004665
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004666bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004667 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4668 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004669
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004670 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004671 if (!EvaluateFloat(E->getLHS(), Result, Info))
4672 return false;
4673 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4674 return false;
4675
4676 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004677 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004678 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004679 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4680 return true;
John McCall2de56d12010-08-25 11:45:40 +00004681 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004682 Result.add(RHS, APFloat::rmNearestTiesToEven);
4683 return true;
John McCall2de56d12010-08-25 11:45:40 +00004684 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004685 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4686 return true;
John McCall2de56d12010-08-25 11:45:40 +00004687 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004688 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4689 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004690 }
4691}
4692
4693bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4694 Result = E->getValue();
4695 return true;
4696}
4697
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004698bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4699 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Eli Friedman2a523ee2011-03-25 00:54:52 +00004701 switch (E->getCastKind()) {
4702 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004703 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004704
4705 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004706 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004707 return EvaluateInteger(SubExpr, IntResult, Info) &&
4708 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4709 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004710 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004711
4712 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004713 if (!Visit(SubExpr))
4714 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004715 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4716 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004717 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004718
Eli Friedman2a523ee2011-03-25 00:54:52 +00004719 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004720 ComplexValue V;
4721 if (!EvaluateComplex(SubExpr, V, Info))
4722 return false;
4723 Result = V.getComplexFloatReal();
4724 return true;
4725 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004726 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004727
Richard Smithf48fdb02011-12-09 22:58:01 +00004728 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004729}
4730
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004731//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004732// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004733//===----------------------------------------------------------------------===//
4734
4735namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004736class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004737 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004738 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004740public:
John McCallf4cf1a12010-05-07 17:22:02 +00004741 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004742 : ExprEvaluatorBaseTy(info), Result(Result) {}
4743
Richard Smith47a1eed2011-10-29 20:57:55 +00004744 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004745 Result.setFrom(V);
4746 return true;
4747 }
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004749 //===--------------------------------------------------------------------===//
4750 // Visitor Methods
4751 //===--------------------------------------------------------------------===//
4752
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004753 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004755 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004756
John McCallf4cf1a12010-05-07 17:22:02 +00004757 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004758 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004759 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004760};
4761} // end anonymous namespace
4762
John McCallf4cf1a12010-05-07 17:22:02 +00004763static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4764 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004765 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004766 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004767}
4768
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004769bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4770 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004771
4772 if (SubExpr->getType()->isRealFloatingType()) {
4773 Result.makeComplexFloat();
4774 APFloat &Imag = Result.FloatImag;
4775 if (!EvaluateFloat(SubExpr, Imag, Info))
4776 return false;
4777
4778 Result.FloatReal = APFloat(Imag.getSemantics());
4779 return true;
4780 } else {
4781 assert(SubExpr->getType()->isIntegerType() &&
4782 "Unexpected imaginary literal.");
4783
4784 Result.makeComplexInt();
4785 APSInt &Imag = Result.IntImag;
4786 if (!EvaluateInteger(SubExpr, Imag, Info))
4787 return false;
4788
4789 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4790 return true;
4791 }
4792}
4793
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004794bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004795
John McCall8786da72010-12-14 17:51:41 +00004796 switch (E->getCastKind()) {
4797 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004798 case CK_BaseToDerived:
4799 case CK_DerivedToBase:
4800 case CK_UncheckedDerivedToBase:
4801 case CK_Dynamic:
4802 case CK_ToUnion:
4803 case CK_ArrayToPointerDecay:
4804 case CK_FunctionToPointerDecay:
4805 case CK_NullToPointer:
4806 case CK_NullToMemberPointer:
4807 case CK_BaseToDerivedMemberPointer:
4808 case CK_DerivedToBaseMemberPointer:
4809 case CK_MemberPointerToBoolean:
4810 case CK_ConstructorConversion:
4811 case CK_IntegralToPointer:
4812 case CK_PointerToIntegral:
4813 case CK_PointerToBoolean:
4814 case CK_ToVoid:
4815 case CK_VectorSplat:
4816 case CK_IntegralCast:
4817 case CK_IntegralToBoolean:
4818 case CK_IntegralToFloating:
4819 case CK_FloatingToIntegral:
4820 case CK_FloatingToBoolean:
4821 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004822 case CK_CPointerToObjCPointerCast:
4823 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004824 case CK_AnyPointerToBlockPointerCast:
4825 case CK_ObjCObjectLValueCast:
4826 case CK_FloatingComplexToReal:
4827 case CK_FloatingComplexToBoolean:
4828 case CK_IntegralComplexToReal:
4829 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004830 case CK_ARCProduceObject:
4831 case CK_ARCConsumeObject:
4832 case CK_ARCReclaimReturnedObject:
4833 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004834 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004835
John McCall8786da72010-12-14 17:51:41 +00004836 case CK_LValueToRValue:
4837 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004838 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004839
4840 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004841 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004842 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004843 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004844
4845 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004846 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004847 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004848 return false;
4849
John McCall8786da72010-12-14 17:51:41 +00004850 Result.makeComplexFloat();
4851 Result.FloatImag = APFloat(Real.getSemantics());
4852 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004853 }
4854
John McCall8786da72010-12-14 17:51:41 +00004855 case CK_FloatingComplexCast: {
4856 if (!Visit(E->getSubExpr()))
4857 return false;
4858
4859 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4860 QualType From
4861 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4862
Richard Smithc1c5f272011-12-13 06:39:58 +00004863 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4864 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004865 }
4866
4867 case CK_FloatingComplexToIntegralComplex: {
4868 if (!Visit(E->getSubExpr()))
4869 return false;
4870
4871 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4872 QualType From
4873 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4874 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004875 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4876 To, Result.IntReal) &&
4877 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4878 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004879 }
4880
4881 case CK_IntegralRealToComplex: {
4882 APSInt &Real = Result.IntReal;
4883 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4884 return false;
4885
4886 Result.makeComplexInt();
4887 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4888 return true;
4889 }
4890
4891 case CK_IntegralComplexCast: {
4892 if (!Visit(E->getSubExpr()))
4893 return false;
4894
4895 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4896 QualType From
4897 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4898
4899 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4900 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4901 return true;
4902 }
4903
4904 case CK_IntegralComplexToFloatingComplex: {
4905 if (!Visit(E->getSubExpr()))
4906 return false;
4907
4908 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4909 QualType From
4910 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4911 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004912 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4913 To, Result.FloatReal) &&
4914 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4915 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004916 }
4917 }
4918
4919 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004920 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004921}
4922
John McCallf4cf1a12010-05-07 17:22:02 +00004923bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004924 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004925 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4926
John McCallf4cf1a12010-05-07 17:22:02 +00004927 if (!Visit(E->getLHS()))
4928 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
John McCallf4cf1a12010-05-07 17:22:02 +00004930 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004931 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004932 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004933
Daniel Dunbar3f279872009-01-29 01:32:56 +00004934 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4935 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004936 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004937 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004938 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004939 if (Result.isComplexFloat()) {
4940 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4941 APFloat::rmNearestTiesToEven);
4942 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4943 APFloat::rmNearestTiesToEven);
4944 } else {
4945 Result.getComplexIntReal() += RHS.getComplexIntReal();
4946 Result.getComplexIntImag() += RHS.getComplexIntImag();
4947 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004948 break;
John McCall2de56d12010-08-25 11:45:40 +00004949 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004950 if (Result.isComplexFloat()) {
4951 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4952 APFloat::rmNearestTiesToEven);
4953 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4954 APFloat::rmNearestTiesToEven);
4955 } else {
4956 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4957 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4958 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004959 break;
John McCall2de56d12010-08-25 11:45:40 +00004960 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004961 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004962 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004963 APFloat &LHS_r = LHS.getComplexFloatReal();
4964 APFloat &LHS_i = LHS.getComplexFloatImag();
4965 APFloat &RHS_r = RHS.getComplexFloatReal();
4966 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004967
Daniel Dunbar3f279872009-01-29 01:32:56 +00004968 APFloat Tmp = LHS_r;
4969 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4970 Result.getComplexFloatReal() = Tmp;
4971 Tmp = LHS_i;
4972 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4973 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4974
4975 Tmp = LHS_r;
4976 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4977 Result.getComplexFloatImag() = Tmp;
4978 Tmp = LHS_i;
4979 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4980 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4981 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004982 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004983 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004984 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4985 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004986 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004987 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4988 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4989 }
4990 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004991 case BO_Div:
4992 if (Result.isComplexFloat()) {
4993 ComplexValue LHS = Result;
4994 APFloat &LHS_r = LHS.getComplexFloatReal();
4995 APFloat &LHS_i = LHS.getComplexFloatImag();
4996 APFloat &RHS_r = RHS.getComplexFloatReal();
4997 APFloat &RHS_i = RHS.getComplexFloatImag();
4998 APFloat &Res_r = Result.getComplexFloatReal();
4999 APFloat &Res_i = Result.getComplexFloatImag();
5000
5001 APFloat Den = RHS_r;
5002 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5003 APFloat Tmp = RHS_i;
5004 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5005 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5006
5007 Res_r = LHS_r;
5008 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5009 Tmp = LHS_i;
5010 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5011 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5012 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5013
5014 Res_i = LHS_i;
5015 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5016 Tmp = LHS_r;
5017 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5018 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5019 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5020 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005021 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5022 return Error(E, diag::note_expr_divide_by_zero);
5023
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005024 ComplexValue LHS = Result;
5025 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5026 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5027 Result.getComplexIntReal() =
5028 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5029 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5030 Result.getComplexIntImag() =
5031 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5032 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5033 }
5034 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005035 }
5036
John McCallf4cf1a12010-05-07 17:22:02 +00005037 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005038}
5039
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005040bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5041 // Get the operand value into 'Result'.
5042 if (!Visit(E->getSubExpr()))
5043 return false;
5044
5045 switch (E->getOpcode()) {
5046 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005047 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005048 case UO_Extension:
5049 return true;
5050 case UO_Plus:
5051 // The result is always just the subexpr.
5052 return true;
5053 case UO_Minus:
5054 if (Result.isComplexFloat()) {
5055 Result.getComplexFloatReal().changeSign();
5056 Result.getComplexFloatImag().changeSign();
5057 }
5058 else {
5059 Result.getComplexIntReal() = -Result.getComplexIntReal();
5060 Result.getComplexIntImag() = -Result.getComplexIntImag();
5061 }
5062 return true;
5063 case UO_Not:
5064 if (Result.isComplexFloat())
5065 Result.getComplexFloatImag().changeSign();
5066 else
5067 Result.getComplexIntImag() = -Result.getComplexIntImag();
5068 return true;
5069 }
5070}
5071
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005072//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005073// Void expression evaluation, primarily for a cast to void on the LHS of a
5074// comma operator
5075//===----------------------------------------------------------------------===//
5076
5077namespace {
5078class VoidExprEvaluator
5079 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5080public:
5081 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5082
5083 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005084
5085 bool VisitCastExpr(const CastExpr *E) {
5086 switch (E->getCastKind()) {
5087 default:
5088 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5089 case CK_ToVoid:
5090 VisitIgnoredValue(E->getSubExpr());
5091 return true;
5092 }
5093 }
5094};
5095} // end anonymous namespace
5096
5097static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5098 assert(E->isRValue() && E->getType()->isVoidType());
5099 return VoidExprEvaluator(Info).Visit(E);
5100}
5101
5102//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005103// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005104//===----------------------------------------------------------------------===//
5105
Richard Smith47a1eed2011-10-29 20:57:55 +00005106static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005107 // In C, function designators are not lvalues, but we evaluate them as if they
5108 // are.
5109 if (E->isGLValue() || E->getType()->isFunctionType()) {
5110 LValue LV;
5111 if (!EvaluateLValue(E, LV, Info))
5112 return false;
5113 LV.moveInto(Result);
5114 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005115 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005116 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005117 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005118 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005119 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005120 } else if (E->getType()->hasPointerRepresentation()) {
5121 LValue LV;
5122 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005123 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005124 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005125 } else if (E->getType()->isRealFloatingType()) {
5126 llvm::APFloat F(0.0);
5127 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005128 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005129 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005130 } else if (E->getType()->isAnyComplexType()) {
5131 ComplexValue C;
5132 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005133 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005134 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005135 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005136 MemberPtr P;
5137 if (!EvaluateMemberPointer(E, P, Info))
5138 return false;
5139 P.moveInto(Result);
5140 return true;
Richard Smitheba05b22011-12-25 20:00:17 +00005141 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005142 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005143 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005144 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005145 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005146 Result = Info.CurrentCall->Temporaries[E];
Richard Smitheba05b22011-12-25 20:00:17 +00005147 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005148 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005149 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005150 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5151 return false;
5152 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005153 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005154 if (Info.getLangOpts().CPlusPlus0x)
5155 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5156 << E->getType();
5157 else
5158 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005159 if (!EvaluateVoid(E, Info))
5160 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005161 } else if (Info.getLangOpts().CPlusPlus0x) {
5162 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5163 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005164 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005165 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005166 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005167 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005168
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005169 return true;
5170}
5171
Richard Smith69c2c502011-11-04 05:33:44 +00005172/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5173/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5174/// since later initializers for an object can indirectly refer to subobjects
5175/// which were initialized earlier.
5176static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005177 const LValue &This, const Expr *E,
5178 CheckConstantExpressionKind CCEK) {
Richard Smitheba05b22011-12-25 20:00:17 +00005179 if (!CheckLiteralType(Info, E))
5180 return false;
5181
5182 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005183 // Evaluate arrays and record types in-place, so that later initializers can
5184 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005185 if (E->getType()->isArrayType())
5186 return EvaluateArray(E, This, Result, Info);
5187 else if (E->getType()->isRecordType())
5188 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005189 }
5190
5191 // For any other type, in-place evaluation is unimportant.
5192 CCValue CoreConstResult;
5193 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005194 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005195}
5196
Richard Smithf48fdb02011-12-09 22:58:01 +00005197/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5198/// lvalue-to-rvalue cast if it is an lvalue.
5199static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smitheba05b22011-12-25 20:00:17 +00005200 if (!CheckLiteralType(Info, E))
5201 return false;
5202
Richard Smithf48fdb02011-12-09 22:58:01 +00005203 CCValue Value;
5204 if (!::Evaluate(Value, Info, E))
5205 return false;
5206
5207 if (E->isGLValue()) {
5208 LValue LV;
5209 LV.setFrom(Value);
5210 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5211 return false;
5212 }
5213
5214 // Check this core constant expression is a constant expression, and if so,
5215 // convert it to one.
5216 return CheckConstantExpression(Info, E, Value, Result);
5217}
Richard Smithc49bd112011-10-28 17:51:58 +00005218
Richard Smith51f47082011-10-29 00:50:52 +00005219/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005220/// any crazy technique (that has nothing to do with language standards) that
5221/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005222/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5223/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005224bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005225 // Fast-path evaluations of integer literals, since we sometimes see files
5226 // containing vast quantities of these.
5227 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5228 Result.Val = APValue(APSInt(L->getValue(),
5229 L->getType()->isUnsignedIntegerType()));
5230 return true;
5231 }
5232
Richard Smith1445bba2011-11-10 03:30:42 +00005233 // FIXME: Evaluating initializers for large arrays can cause performance
5234 // problems, and we don't use such values yet. Once we have a more efficient
5235 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005236 // The same problem affects large records.
5237 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5238 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005239 return false;
5240
Richard Smith180f4792011-11-10 06:34:14 +00005241 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00005242 EvalInfo Info(Ctx, Result);
5243 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005244}
5245
Jay Foad4ba2a172011-01-12 09:06:06 +00005246bool Expr::EvaluateAsBooleanCondition(bool &Result,
5247 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005248 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005249 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00005250 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005251 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005252}
5253
Richard Smith80d4b552011-12-28 19:48:30 +00005254bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5255 SideEffectsKind AllowSideEffects) const {
5256 if (!getType()->isIntegralOrEnumerationType())
5257 return false;
5258
Richard Smithc49bd112011-10-28 17:51:58 +00005259 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005260 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5261 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005262 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005263
Richard Smithc49bd112011-10-28 17:51:58 +00005264 Result = ExprResult.Val.getInt();
5265 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005266}
5267
Jay Foad4ba2a172011-01-12 09:06:06 +00005268bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005269 EvalInfo Info(Ctx, Result);
5270
John McCallefdb83e2010-05-07 21:00:08 +00005271 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005272 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005273 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5274 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005275}
5276
Richard Smith099e7f62011-12-19 06:19:21 +00005277bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5278 const VarDecl *VD,
5279 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5280 Expr::EvalStatus EStatus;
5281 EStatus.Diag = &Notes;
5282
5283 EvalInfo InitInfo(Ctx, EStatus);
5284 InitInfo.setEvaluatingDecl(VD, Value);
5285
Richard Smitheba05b22011-12-25 20:00:17 +00005286 if (!CheckLiteralType(InitInfo, this))
5287 return false;
5288
Richard Smith099e7f62011-12-19 06:19:21 +00005289 LValue LVal;
5290 LVal.set(VD);
5291
Richard Smitheba05b22011-12-25 20:00:17 +00005292 // C++11 [basic.start.init]p2:
5293 // Variables with static storage duration or thread storage duration shall be
5294 // zero-initialized before any other initialization takes place.
5295 // This behavior is not present in C.
5296 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5297 !VD->getType()->isReferenceType()) {
5298 ImplicitValueInitExpr VIE(VD->getType());
5299 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5300 return false;
5301 }
5302
Richard Smith099e7f62011-12-19 06:19:21 +00005303 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5304 !EStatus.HasSideEffects;
5305}
5306
Richard Smith51f47082011-10-29 00:50:52 +00005307/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5308/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005309bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005310 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005311 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005312}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005313
Jay Foad4ba2a172011-01-12 09:06:06 +00005314bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005315 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005316}
5317
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005318APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005319 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005320 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005321 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005322 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005323 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005324
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005325 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005326}
John McCalld905f5a2010-05-07 05:32:02 +00005327
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005328 bool Expr::EvalResult::isGlobalLValue() const {
5329 assert(Val.isLValue());
5330 return IsGlobalLValue(Val.getLValueBase());
5331 }
5332
5333
John McCalld905f5a2010-05-07 05:32:02 +00005334/// isIntegerConstantExpr - this recursive routine will test if an expression is
5335/// an integer constant expression.
5336
5337/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5338/// comma, etc
5339///
5340/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5341/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5342/// cast+dereference.
5343
5344// CheckICE - This function does the fundamental ICE checking: the returned
5345// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5346// Note that to reduce code duplication, this helper does no evaluation
5347// itself; the caller checks whether the expression is evaluatable, and
5348// in the rare cases where CheckICE actually cares about the evaluated
5349// value, it calls into Evalute.
5350//
5351// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005352// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005353// 1: This expression is not an ICE, but if it isn't evaluated, it's
5354// a legal subexpression for an ICE. This return value is used to handle
5355// the comma operator in C99 mode.
5356// 2: This expression is not an ICE, and is not a legal subexpression for one.
5357
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005358namespace {
5359
John McCalld905f5a2010-05-07 05:32:02 +00005360struct ICEDiag {
5361 unsigned Val;
5362 SourceLocation Loc;
5363
5364 public:
5365 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5366 ICEDiag() : Val(0) {}
5367};
5368
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005369}
5370
5371static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005372
5373static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5374 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005375 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005376 !EVResult.Val.isInt()) {
5377 return ICEDiag(2, E->getLocStart());
5378 }
5379 return NoDiag();
5380}
5381
5382static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5383 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005384 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005385 return ICEDiag(2, E->getLocStart());
5386 }
5387
5388 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005389#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005390#define STMT(Node, Base) case Expr::Node##Class:
5391#define EXPR(Node, Base)
5392#include "clang/AST/StmtNodes.inc"
5393 case Expr::PredefinedExprClass:
5394 case Expr::FloatingLiteralClass:
5395 case Expr::ImaginaryLiteralClass:
5396 case Expr::StringLiteralClass:
5397 case Expr::ArraySubscriptExprClass:
5398 case Expr::MemberExprClass:
5399 case Expr::CompoundAssignOperatorClass:
5400 case Expr::CompoundLiteralExprClass:
5401 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005402 case Expr::DesignatedInitExprClass:
5403 case Expr::ImplicitValueInitExprClass:
5404 case Expr::ParenListExprClass:
5405 case Expr::VAArgExprClass:
5406 case Expr::AddrLabelExprClass:
5407 case Expr::StmtExprClass:
5408 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005409 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005410 case Expr::CXXDynamicCastExprClass:
5411 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005412 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005413 case Expr::CXXNullPtrLiteralExprClass:
5414 case Expr::CXXThisExprClass:
5415 case Expr::CXXThrowExprClass:
5416 case Expr::CXXNewExprClass:
5417 case Expr::CXXDeleteExprClass:
5418 case Expr::CXXPseudoDestructorExprClass:
5419 case Expr::UnresolvedLookupExprClass:
5420 case Expr::DependentScopeDeclRefExprClass:
5421 case Expr::CXXConstructExprClass:
5422 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005423 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005424 case Expr::CXXTemporaryObjectExprClass:
5425 case Expr::CXXUnresolvedConstructExprClass:
5426 case Expr::CXXDependentScopeMemberExprClass:
5427 case Expr::UnresolvedMemberExprClass:
5428 case Expr::ObjCStringLiteralClass:
5429 case Expr::ObjCEncodeExprClass:
5430 case Expr::ObjCMessageExprClass:
5431 case Expr::ObjCSelectorExprClass:
5432 case Expr::ObjCProtocolExprClass:
5433 case Expr::ObjCIvarRefExprClass:
5434 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005435 case Expr::ObjCIsaExprClass:
5436 case Expr::ShuffleVectorExprClass:
5437 case Expr::BlockExprClass:
5438 case Expr::BlockDeclRefExprClass:
5439 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005440 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005441 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005442 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005443 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005444 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005445 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005446 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005447 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005448 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005449 return ICEDiag(2, E->getLocStart());
5450
Douglas Gregoree8aff02011-01-04 17:33:58 +00005451 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005452 case Expr::GNUNullExprClass:
5453 // GCC considers the GNU __null value to be an integral constant expression.
5454 return NoDiag();
5455
John McCall91a57552011-07-15 05:09:51 +00005456 case Expr::SubstNonTypeTemplateParmExprClass:
5457 return
5458 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5459
John McCalld905f5a2010-05-07 05:32:02 +00005460 case Expr::ParenExprClass:
5461 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005462 case Expr::GenericSelectionExprClass:
5463 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005464 case Expr::IntegerLiteralClass:
5465 case Expr::CharacterLiteralClass:
5466 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005467 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005468 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005469 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005470 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005471 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005472 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005473 return NoDiag();
5474 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005475 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005476 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5477 // constant expressions, but they can never be ICEs because an ICE cannot
5478 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005479 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005480 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005481 return CheckEvalInICE(E, Ctx);
5482 return ICEDiag(2, E->getLocStart());
5483 }
5484 case Expr::DeclRefExprClass:
5485 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5486 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005487 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005488 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5489
5490 // Parameter variables are never constants. Without this check,
5491 // getAnyInitializer() can find a default argument, which leads
5492 // to chaos.
5493 if (isa<ParmVarDecl>(D))
5494 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5495
5496 // C++ 7.1.5.1p2
5497 // A variable of non-volatile const-qualified integral or enumeration
5498 // type initialized by an ICE can be used in ICEs.
5499 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005500 if (!Dcl->getType()->isIntegralOrEnumerationType())
5501 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5502
Richard Smith099e7f62011-12-19 06:19:21 +00005503 const VarDecl *VD;
5504 // Look for a declaration of this variable that has an initializer, and
5505 // check whether it is an ICE.
5506 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5507 return NoDiag();
5508 else
5509 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005510 }
5511 }
5512 return ICEDiag(2, E->getLocStart());
5513 case Expr::UnaryOperatorClass: {
5514 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5515 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005516 case UO_PostInc:
5517 case UO_PostDec:
5518 case UO_PreInc:
5519 case UO_PreDec:
5520 case UO_AddrOf:
5521 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005522 // C99 6.6/3 allows increment and decrement within unevaluated
5523 // subexpressions of constant expressions, but they can never be ICEs
5524 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005525 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005526 case UO_Extension:
5527 case UO_LNot:
5528 case UO_Plus:
5529 case UO_Minus:
5530 case UO_Not:
5531 case UO_Real:
5532 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005533 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005534 }
5535
5536 // OffsetOf falls through here.
5537 }
5538 case Expr::OffsetOfExprClass: {
5539 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005540 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005541 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005542 // compliance: we should warn earlier for offsetof expressions with
5543 // array subscripts that aren't ICEs, and if the array subscripts
5544 // are ICEs, the value of the offsetof must be an integer constant.
5545 return CheckEvalInICE(E, Ctx);
5546 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005547 case Expr::UnaryExprOrTypeTraitExprClass: {
5548 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5549 if ((Exp->getKind() == UETT_SizeOf) &&
5550 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005551 return ICEDiag(2, E->getLocStart());
5552 return NoDiag();
5553 }
5554 case Expr::BinaryOperatorClass: {
5555 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5556 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005557 case BO_PtrMemD:
5558 case BO_PtrMemI:
5559 case BO_Assign:
5560 case BO_MulAssign:
5561 case BO_DivAssign:
5562 case BO_RemAssign:
5563 case BO_AddAssign:
5564 case BO_SubAssign:
5565 case BO_ShlAssign:
5566 case BO_ShrAssign:
5567 case BO_AndAssign:
5568 case BO_XorAssign:
5569 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005570 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5571 // constant expressions, but they can never be ICEs because an ICE cannot
5572 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005573 return ICEDiag(2, E->getLocStart());
5574
John McCall2de56d12010-08-25 11:45:40 +00005575 case BO_Mul:
5576 case BO_Div:
5577 case BO_Rem:
5578 case BO_Add:
5579 case BO_Sub:
5580 case BO_Shl:
5581 case BO_Shr:
5582 case BO_LT:
5583 case BO_GT:
5584 case BO_LE:
5585 case BO_GE:
5586 case BO_EQ:
5587 case BO_NE:
5588 case BO_And:
5589 case BO_Xor:
5590 case BO_Or:
5591 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005592 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5593 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005594 if (Exp->getOpcode() == BO_Div ||
5595 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005596 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005597 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005598 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005599 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005600 if (REval == 0)
5601 return ICEDiag(1, E->getLocStart());
5602 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005603 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005604 if (LEval.isMinSignedValue())
5605 return ICEDiag(1, E->getLocStart());
5606 }
5607 }
5608 }
John McCall2de56d12010-08-25 11:45:40 +00005609 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005610 if (Ctx.getLangOptions().C99) {
5611 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5612 // if it isn't evaluated.
5613 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5614 return ICEDiag(1, E->getLocStart());
5615 } else {
5616 // In both C89 and C++, commas in ICEs are illegal.
5617 return ICEDiag(2, E->getLocStart());
5618 }
5619 }
5620 if (LHSResult.Val >= RHSResult.Val)
5621 return LHSResult;
5622 return RHSResult;
5623 }
John McCall2de56d12010-08-25 11:45:40 +00005624 case BO_LAnd:
5625 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005626 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5627 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5628 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5629 // Rare case where the RHS has a comma "side-effect"; we need
5630 // to actually check the condition to see whether the side
5631 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005632 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005633 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005634 return RHSResult;
5635 return NoDiag();
5636 }
5637
5638 if (LHSResult.Val >= RHSResult.Val)
5639 return LHSResult;
5640 return RHSResult;
5641 }
5642 }
5643 }
5644 case Expr::ImplicitCastExprClass:
5645 case Expr::CStyleCastExprClass:
5646 case Expr::CXXFunctionalCastExprClass:
5647 case Expr::CXXStaticCastExprClass:
5648 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005649 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005650 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005651 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005652 if (isa<ExplicitCastExpr>(E)) {
5653 if (const FloatingLiteral *FL
5654 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5655 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5656 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5657 APSInt IgnoredVal(DestWidth, !DestSigned);
5658 bool Ignored;
5659 // If the value does not fit in the destination type, the behavior is
5660 // undefined, so we are not required to treat it as a constant
5661 // expression.
5662 if (FL->getValue().convertToInteger(IgnoredVal,
5663 llvm::APFloat::rmTowardZero,
5664 &Ignored) & APFloat::opInvalidOp)
5665 return ICEDiag(2, E->getLocStart());
5666 return NoDiag();
5667 }
5668 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005669 switch (cast<CastExpr>(E)->getCastKind()) {
5670 case CK_LValueToRValue:
5671 case CK_NoOp:
5672 case CK_IntegralToBoolean:
5673 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005674 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005675 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005676 return ICEDiag(2, E->getLocStart());
5677 }
John McCalld905f5a2010-05-07 05:32:02 +00005678 }
John McCall56ca35d2011-02-17 10:25:35 +00005679 case Expr::BinaryConditionalOperatorClass: {
5680 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5681 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5682 if (CommonResult.Val == 2) return CommonResult;
5683 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5684 if (FalseResult.Val == 2) return FalseResult;
5685 if (CommonResult.Val == 1) return CommonResult;
5686 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005687 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005688 return FalseResult;
5689 }
John McCalld905f5a2010-05-07 05:32:02 +00005690 case Expr::ConditionalOperatorClass: {
5691 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5692 // If the condition (ignoring parens) is a __builtin_constant_p call,
5693 // then only the true side is actually considered in an integer constant
5694 // expression, and it is fully evaluated. This is an important GNU
5695 // extension. See GCC PR38377 for discussion.
5696 if (const CallExpr *CallCE
5697 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00005698 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5699 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005700 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005701 if (CondResult.Val == 2)
5702 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005703
Richard Smithf48fdb02011-12-09 22:58:01 +00005704 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5705 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005706
John McCalld905f5a2010-05-07 05:32:02 +00005707 if (TrueResult.Val == 2)
5708 return TrueResult;
5709 if (FalseResult.Val == 2)
5710 return FalseResult;
5711 if (CondResult.Val == 1)
5712 return CondResult;
5713 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5714 return NoDiag();
5715 // Rare case where the diagnostics depend on which side is evaluated
5716 // Note that if we get here, CondResult is 0, and at least one of
5717 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005718 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005719 return FalseResult;
5720 }
5721 return TrueResult;
5722 }
5723 case Expr::CXXDefaultArgExprClass:
5724 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5725 case Expr::ChooseExprClass: {
5726 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5727 }
5728 }
5729
5730 // Silence a GCC warning
5731 return ICEDiag(2, E->getLocStart());
5732}
5733
Richard Smithf48fdb02011-12-09 22:58:01 +00005734/// Evaluate an expression as a C++11 integral constant expression.
5735static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5736 const Expr *E,
5737 llvm::APSInt *Value,
5738 SourceLocation *Loc) {
5739 if (!E->getType()->isIntegralOrEnumerationType()) {
5740 if (Loc) *Loc = E->getExprLoc();
5741 return false;
5742 }
5743
5744 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005745 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5746 Result.Diag = &Diags;
5747 EvalInfo Info(Ctx, Result);
5748
5749 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5750 if (!Diags.empty()) {
5751 IsICE = false;
5752 if (Loc) *Loc = Diags[0].first;
5753 } else if (!IsICE && Loc) {
5754 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005755 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005756
5757 if (!IsICE)
5758 return false;
5759
5760 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5761 if (Value) *Value = Result.Val.getInt();
5762 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005763}
5764
Richard Smithdd1f29b2011-12-12 09:28:41 +00005765bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005766 if (Ctx.getLangOptions().CPlusPlus0x)
5767 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5768
John McCalld905f5a2010-05-07 05:32:02 +00005769 ICEDiag d = CheckICE(this, Ctx);
5770 if (d.Val != 0) {
5771 if (Loc) *Loc = d.Loc;
5772 return false;
5773 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005774 return true;
5775}
5776
5777bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5778 SourceLocation *Loc, bool isEvaluated) const {
5779 if (Ctx.getLangOptions().CPlusPlus0x)
5780 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5781
5782 if (!isIntegerConstantExpr(Ctx, Loc))
5783 return false;
5784 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005785 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005786 return true;
5787}