blob: 8e6682bcdee3c5cd40b4fb36c8125a5b765e2826 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-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 McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-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 Smithd62306a2011-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 Smith80815602011-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 Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-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 Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-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 Smith80815602011-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 Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-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 Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-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 Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-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 Smith0b0a0b62011-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 Smith027bf112011-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 Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-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 Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-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 Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithf6f003a2011-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 Smithd62306a2011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smith254a73d2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000246
Richard Smith4e4c78ff2011-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 Smithf6f003a2011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000256 };
257
Richard Smith92b1ce02011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smith4e4c78ff2011-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 Smith4e4c78ff2011-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 Smithd62306a2011-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 Smith357362d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312
Richard Smith4e4c78ff2011-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 Smithd62306a2011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smith9a568822011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smith357362d2011-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 Smith9a568822011-11-21 19:36:32 +0000332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000333
Richard Smith357362d2011-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 Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000345 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-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 Smith92b1ce02011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-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 Smith92b1ce02011-12-12 09:28:41 +0000365 }
Richard Smith357362d2011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-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 Smithf2b681b2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smith357362d2011-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 Smithf57d8cb2011-12-09 22:58:01 +0000386 }
Richard Smithd0b4dd62011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000395 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000396}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000397
Richard Smithf6f003a2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000441 }
442
Richard Smithf6f003a2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000453 }
454
Richard Smithf6f003a2011-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 McCall93d91dc2010-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 Smith0b0a0b62011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000502 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCallc07a0c72011-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 McCall93d91dc2010-05-07 17:22:02 +0000515 };
John McCall45d55e42010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000522
Richard Smithce40ad62011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000529
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000532 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smithce40ad62011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000546 }
John McCall45d55e42010-05-07 21:00:08 +0000547 };
Richard Smith027bf112011-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 Smith357362d2011-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 McCall93d91dc2010-05-07 17:22:02 +0000644}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000645
Richard Smith0b0a0b62011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCall45d55e42010-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 Smith027bf112011-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 Lattnercdf34e72008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smithd62306a2011-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 Smithce40ad62011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-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 Smithce40ad62011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000680
Richard Smithce40ad62011-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 Smithd62306a2011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smithd62306a2011-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:
700 return true;
701 case Expr::CallExprClass:
702 return IsStringLiteralCall(cast<CallExpr>(E));
703 // For GCC compatibility, &&label has static storage duration.
704 case Expr::AddrLabelExprClass:
705 return true;
706 // A Block literal expression may be used as the initialization value for
707 // Block variables at global or local static scope.
708 case Expr::BlockExprClass:
709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
710 }
John McCall95007602010-05-10 23:27:23 +0000711}
712
Richard Smith80815602011-11-07 05:07:52 +0000713/// Check that this reference or pointer core constant expression is a valid
714/// value for a constant expression. Type T should be either LValue or CCValue.
715template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000716static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000717 const T &LVal, APValue &Value,
718 CheckConstantExpressionKind CCEK) {
719 APValue::LValueBase Base = LVal.getLValueBase();
720 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
721
722 if (!IsGlobalLValue(Base)) {
723 if (Info.getLangOpts().CPlusPlus0x) {
724 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
725 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
726 << E->isGLValue() << !Designator.Entries.empty()
727 << !!VD << CCEK << VD;
728 if (VD)
729 Info.Note(VD->getLocation(), diag::note_declared_at);
730 else
731 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
732 diag::note_constexpr_temporary_here);
733 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000734 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000735 }
Richard Smith80815602011-11-07 05:07:52 +0000736 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000737 }
Richard Smith80815602011-11-07 05:07:52 +0000738
Richard Smith80815602011-11-07 05:07:52 +0000739 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000740 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000741 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000742 // FIXME: This is not a core constant expression. We should have already
743 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000744 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
745 APValue::NoLValuePath());
746 return true;
747 }
748
Richard Smith357362d2011-12-13 06:39:58 +0000749 // Does this refer one past the end of some object?
750 // This is technically not an address constant expression nor a reference
751 // constant expression, but we allow it for address constant expressions.
752 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
753 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
754 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
755 << !Designator.Entries.empty() << !!VD << VD;
756 if (VD)
757 Info.Note(VD->getLocation(), diag::note_declared_at);
758 else
759 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
760 diag::note_constexpr_temporary_here);
761 return false;
762 }
763
Richard Smith80815602011-11-07 05:07:52 +0000764 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000765 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000766 return true;
767}
768
Richard Smith0b0a0b62011-10-29 20:57:55 +0000769/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000770/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000771/// If not, report an appropriate diagnostic.
772static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000773 const CCValue &CCValue, APValue &Value,
774 CheckConstantExpressionKind CCEK
775 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000776 if (!CCValue.isLValue()) {
777 Value = CCValue;
778 return true;
779 }
Richard Smith357362d2011-12-13 06:39:58 +0000780 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000781}
782
Richard Smith83c68212011-10-31 05:11:32 +0000783const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000784 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000785}
786
787static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000788 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000789}
790
Richard Smithcecf1842011-11-01 21:06:14 +0000791static bool IsWeakLValue(const LValue &Value) {
792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000793 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000794}
795
Richard Smith027bf112011-11-17 22:56:20 +0000796static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000797 // A null base expression indicates a null pointer. These are always
798 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000799 if (!Value.getLValueBase()) {
800 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000801 return true;
802 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000803
John McCall95007602010-05-10 23:27:23 +0000804 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000805 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000806 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000807
Richard Smith027bf112011-11-17 22:56:20 +0000808 // We have a non-null base. These are generally known to be true, but if it's
809 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000810 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000811 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000812 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000813}
814
Richard Smith0b0a0b62011-10-29 20:57:55 +0000815static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000816 switch (Val.getKind()) {
817 case APValue::Uninitialized:
818 return false;
819 case APValue::Int:
820 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000821 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000822 case APValue::Float:
823 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000824 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000825 case APValue::ComplexInt:
826 Result = Val.getComplexIntReal().getBoolValue() ||
827 Val.getComplexIntImag().getBoolValue();
828 return true;
829 case APValue::ComplexFloat:
830 Result = !Val.getComplexFloatReal().isZero() ||
831 !Val.getComplexFloatImag().isZero();
832 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000833 case APValue::LValue:
834 return EvalPointerValueAsBool(Val, Result);
835 case APValue::MemberPointer:
836 Result = Val.getMemberPointerDecl();
837 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000838 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000839 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000840 case APValue::Struct:
841 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000842 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000843 }
844
Richard Smith11562c52011-10-28 17:51:58 +0000845 llvm_unreachable("unknown APValue kind");
846}
847
848static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
849 EvalInfo &Info) {
850 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000851 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000852 if (!Evaluate(Val, Info, E))
853 return false;
854 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000855}
856
Richard Smith357362d2011-12-13 06:39:58 +0000857template<typename T>
858static bool HandleOverflow(EvalInfo &Info, const Expr *E,
859 const T &SrcValue, QualType DestType) {
860 llvm::SmallVector<char, 32> Buffer;
861 SrcValue.toString(Buffer);
862 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
863 << StringRef(Buffer.data(), Buffer.size()) << DestType;
864 return false;
865}
866
867static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
868 QualType SrcType, const APFloat &Value,
869 QualType DestType, APSInt &Result) {
870 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000871 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000872 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000873
Richard Smith357362d2011-12-13 06:39:58 +0000874 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000875 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000876 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
877 & APFloat::opInvalidOp)
878 return HandleOverflow(Info, E, Value, DestType);
879 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000880}
881
Richard Smith357362d2011-12-13 06:39:58 +0000882static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
883 QualType SrcType, QualType DestType,
884 APFloat &Result) {
885 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000886 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000887 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
888 APFloat::rmNearestTiesToEven, &ignored)
889 & APFloat::opOverflow)
890 return HandleOverflow(Info, E, Value, DestType);
891 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000892}
893
Mike Stump11289f42009-09-09 15:08:12 +0000894static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000895 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000896 unsigned DestWidth = Ctx.getIntWidth(DestType);
897 APSInt Result = Value;
898 // Figure out if this is a truncate, extend or noop cast.
899 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000900 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000901 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000902 return Result;
903}
904
Richard Smith357362d2011-12-13 06:39:58 +0000905static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
906 QualType SrcType, const APSInt &Value,
907 QualType DestType, APFloat &Result) {
908 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
909 if (Result.convertFromAPInt(Value, Value.isSigned(),
910 APFloat::rmNearestTiesToEven)
911 & APFloat::opOverflow)
912 return HandleOverflow(Info, E, Value, DestType);
913 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000914}
915
Richard Smith027bf112011-11-17 22:56:20 +0000916static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
917 const CXXRecordDecl *&MostDerivedType,
918 unsigned &MostDerivedPathLength,
919 bool &MostDerivedIsArrayElement) {
920 const SubobjectDesignator &D = LVal.Designator;
921 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000922 return false;
923
Richard Smith027bf112011-11-17 22:56:20 +0000924 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000925
926 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000927 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000928 MostDerivedPathLength = 0;
929 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000930
931 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
932 bool IsArray = T && T->isArrayType();
933 if (IsArray)
934 T = T->getBaseElementTypeUnsafe();
935 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
936 T = FD->getType().getTypePtr();
937 else
938 T = 0;
939
940 if (T) {
941 MostDerivedType = T->getAsCXXRecordDecl();
942 MostDerivedPathLength = I + 1;
943 MostDerivedIsArrayElement = IsArray;
944 }
945 }
946
Richard Smithd62306a2011-11-10 06:34:14 +0000947 // (B*)&d + 1 has no most-derived object.
948 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
949 return false;
950
Richard Smith027bf112011-11-17 22:56:20 +0000951 return MostDerivedType != 0;
952}
953
954static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
955 const RecordDecl *TruncatedType,
956 unsigned TruncatedElements,
957 bool IsArrayElement) {
958 SubobjectDesignator &D = Result.Designator;
959 const RecordDecl *RD = TruncatedType;
960 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000961 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
962 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000963 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000965 else
Richard Smithd62306a2011-11-10 06:34:14 +0000966 Result.Offset -= Layout.getBaseClassOffset(Base);
967 RD = Base;
968 }
Richard Smith027bf112011-11-17 22:56:20 +0000969 D.Entries.resize(TruncatedElements);
970 D.ArrayElement = IsArrayElement;
971}
972
973/// If the given LValue refers to a base subobject of some object, find the most
974/// derived object and the corresponding complete record type. This is necessary
975/// in order to find the offset of a virtual base class.
976static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
977 const CXXRecordDecl *&MostDerivedType) {
978 unsigned MostDerivedPathLength;
979 bool MostDerivedIsArrayElement;
980 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
981 MostDerivedPathLength, MostDerivedIsArrayElement))
982 return false;
983
984 // Remove the trailing base class path entries and their offsets.
985 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
986 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000987 return true;
988}
989
990static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
991 const CXXRecordDecl *Derived,
992 const CXXRecordDecl *Base,
993 const ASTRecordLayout *RL = 0) {
994 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
995 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
996 Obj.Designator.addDecl(Base, /*Virtual*/ false);
997}
998
999static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1000 const CXXRecordDecl *DerivedDecl,
1001 const CXXBaseSpecifier *Base) {
1002 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1003
1004 if (!Base->isVirtual()) {
1005 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1006 return true;
1007 }
1008
1009 // Extract most-derived object and corresponding type.
1010 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1011 return false;
1012
1013 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1014 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1015 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1016 return true;
1017}
1018
1019/// Update LVal to refer to the given field, which must be a member of the type
1020/// currently described by LVal.
1021static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1022 const FieldDecl *FD,
1023 const ASTRecordLayout *RL = 0) {
1024 if (!RL)
1025 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1026
1027 unsigned I = FD->getFieldIndex();
1028 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1029 LVal.Designator.addDecl(FD);
1030}
1031
1032/// Get the size of the given type in char units.
1033static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1034 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1035 // extension.
1036 if (Type->isVoidType() || Type->isFunctionType()) {
1037 Size = CharUnits::One();
1038 return true;
1039 }
1040
1041 if (!Type->isConstantSizeType()) {
1042 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1043 return false;
1044 }
1045
1046 Size = Info.Ctx.getTypeSizeInChars(Type);
1047 return true;
1048}
1049
1050/// Update a pointer value to model pointer arithmetic.
1051/// \param Info - Information about the ongoing evaluation.
1052/// \param LVal - The pointer value to be updated.
1053/// \param EltTy - The pointee type represented by LVal.
1054/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1055static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1056 QualType EltTy, int64_t Adjustment) {
1057 CharUnits SizeOfPointee;
1058 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1059 return false;
1060
1061 // Compute the new offset in the appropriate width.
1062 LVal.Offset += Adjustment * SizeOfPointee;
1063 LVal.Designator.adjustIndex(Adjustment);
1064 return true;
1065}
1066
Richard Smith27908702011-10-24 17:54:18 +00001067/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001068static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1069 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001070 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001071 // If this is a parameter to an active constexpr function call, perform
1072 // argument substitution.
1073 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001074 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001075 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001076 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001077 }
Richard Smithfec09922011-11-01 16:57:24 +00001078 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1079 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001080 }
Richard Smith27908702011-10-24 17:54:18 +00001081
Richard Smithd0b4dd62011-12-19 06:19:21 +00001082 // Dig out the initializer, and use the declaration which it's attached to.
1083 const Expr *Init = VD->getAnyInitializer(VD);
1084 if (!Init || Init->isValueDependent()) {
1085 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1086 return false;
1087 }
1088
Richard Smithd62306a2011-11-10 06:34:14 +00001089 // If we're currently evaluating the initializer of this declaration, use that
1090 // in-flight value.
1091 if (Info.EvaluatingDecl == VD) {
1092 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1093 return !Result.isUninit();
1094 }
1095
Richard Smithcecf1842011-11-01 21:06:14 +00001096 // Never evaluate the initializer of a weak variable. We can't be sure that
1097 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001098 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001099 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001100 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001101 }
Richard Smithcecf1842011-11-01 21:06:14 +00001102
Richard Smithd0b4dd62011-12-19 06:19:21 +00001103 // Check that we can fold the initializer. In C++, we will have already done
1104 // this in the cases where it matters for conformance.
1105 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1106 if (!VD->evaluateValue(Notes)) {
1107 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1108 Notes.size() + 1) << VD;
1109 Info.Note(VD->getLocation(), diag::note_declared_at);
1110 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001111 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001112 } else if (!VD->checkInitIsICE()) {
1113 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1114 Notes.size() + 1) << VD;
1115 Info.Note(VD->getLocation(), diag::note_declared_at);
1116 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001117 }
Richard Smith27908702011-10-24 17:54:18 +00001118
Richard Smithd0b4dd62011-12-19 06:19:21 +00001119 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001120 return true;
Richard Smith27908702011-10-24 17:54:18 +00001121}
1122
Richard Smith11562c52011-10-28 17:51:58 +00001123static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001124 Qualifiers Quals = T.getQualifiers();
1125 return Quals.hasConst() && !Quals.hasVolatile();
1126}
1127
Richard Smithe97cbd72011-11-11 04:05:33 +00001128/// Get the base index of the given base class within an APValue representing
1129/// the given derived class.
1130static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1131 const CXXRecordDecl *Base) {
1132 Base = Base->getCanonicalDecl();
1133 unsigned Index = 0;
1134 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1135 E = Derived->bases_end(); I != E; ++I, ++Index) {
1136 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1137 return Index;
1138 }
1139
1140 llvm_unreachable("base class missing from derived class's bases list");
1141}
1142
Richard Smithf3e9e432011-11-07 09:22:26 +00001143/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001144static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1145 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001146 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001147 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001148 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001150 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001151 if (Sub.OnePastTheEnd) {
1152 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001153 (unsigned)diag::note_constexpr_read_past_end :
1154 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001155 return false;
1156 }
Richard Smith6804be52011-11-11 08:28:03 +00001157 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001158 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001159
1160 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1161 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001162 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001163 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001164 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001165 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001166 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001167 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001168 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001169 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001170 // Note, it should not be possible to form a pointer with a valid
1171 // designator which points more than one past the end of the array.
1172 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001173 (unsigned)diag::note_constexpr_read_past_end :
1174 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001176 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001177 if (O->getArrayInitializedElts() > Index)
1178 O = &O->getArrayInitializedElt(Index);
1179 else
1180 O = &O->getArrayFiller();
1181 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001182 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1183 // Next subobject is a class, struct or union field.
1184 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1185 if (RD->isUnion()) {
1186 const FieldDecl *UnionField = O->getUnionField();
1187 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001188 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001189 Info.Diag(E->getExprLoc(),
1190 diag::note_constexpr_read_inactive_union_member)
1191 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001192 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001193 }
Richard Smithd62306a2011-11-10 06:34:14 +00001194 O = &O->getUnionValue();
1195 } else
1196 O = &O->getStructField(Field->getFieldIndex());
1197 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001198
1199 if (ObjType.isVolatileQualified()) {
1200 if (Info.getLangOpts().CPlusPlus) {
1201 // FIXME: Include a description of the path to the volatile subobject.
1202 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1203 << 2 << Field;
1204 Info.Note(Field->getLocation(), diag::note_declared_at);
1205 } else {
1206 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1207 }
1208 return false;
1209 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001210 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001211 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001212 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1213 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1214 O = &O->getStructBase(getBaseIndex(Derived, Base));
1215 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001216 }
Richard Smithd62306a2011-11-10 06:34:14 +00001217
Richard Smithf57d8cb2011-12-09 22:58:01 +00001218 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001219 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001220 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001221 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001222 }
1223
Richard Smithf3e9e432011-11-07 09:22:26 +00001224 Obj = CCValue(*O, CCValue::GlobalValue());
1225 return true;
1226}
1227
Richard Smithd62306a2011-11-10 06:34:14 +00001228/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1229/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1230/// for looking up the glvalue referred to by an entity of reference type.
1231///
1232/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001233/// \param Conv - The expression for which we are performing the conversion.
1234/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001235/// \param Type - The type we expect this conversion to produce.
1236/// \param LVal - The glvalue on which we are attempting to perform this action.
1237/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001238static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1239 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001240 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001241 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1242 if (!Info.getLangOpts().CPlusPlus)
1243 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1244
Richard Smithce40ad62011-11-12 22:28:03 +00001245 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001246 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001247 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001248
Richard Smithf57d8cb2011-12-09 22:58:01 +00001249 if (!LVal.Base) {
1250 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001251 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1252 return false;
1253 }
1254
1255 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1256 // is not a constant expression (even if the object is non-volatile). We also
1257 // apply this rule to C++98, in order to conform to the expected 'volatile'
1258 // semantics.
1259 if (Type.isVolatileQualified()) {
1260 if (Info.getLangOpts().CPlusPlus)
1261 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1262 else
1263 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001264 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001265 }
Richard Smith11562c52011-10-28 17:51:58 +00001266
Richard Smithce40ad62011-11-12 22:28:03 +00001267 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001268 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1269 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001270 // expressions are constant expressions too. Inside constexpr functions,
1271 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001272 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001273 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001274 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001275 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001276 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001277 }
1278
Richard Smithf2b681b2011-12-21 05:04:46 +00001279 // DR1313: If the object is volatile-qualified but the glvalue was not,
1280 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001281 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001282 if (VT.isVolatileQualified()) {
1283 if (Info.getLangOpts().CPlusPlus) {
1284 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1285 Info.Note(VD->getLocation(), diag::note_declared_at);
1286 } else {
1287 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001288 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001289 return false;
1290 }
1291
1292 if (!isa<ParmVarDecl>(VD)) {
1293 if (VD->isConstexpr()) {
1294 // OK, we can read this variable.
1295 } else if (VT->isIntegralOrEnumerationType()) {
1296 if (!VT.isConstQualified()) {
1297 if (Info.getLangOpts().CPlusPlus) {
1298 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1299 Info.Note(VD->getLocation(), diag::note_declared_at);
1300 } else {
1301 Info.Diag(Loc);
1302 }
1303 return false;
1304 }
1305 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1306 // We support folding of const floating-point types, in order to make
1307 // static const data members of such types (supported as an extension)
1308 // more useful.
1309 if (Info.getLangOpts().CPlusPlus0x) {
1310 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1311 Info.Note(VD->getLocation(), diag::note_declared_at);
1312 } else {
1313 Info.CCEDiag(Loc);
1314 }
1315 } else {
1316 // FIXME: Allow folding of values of any literal type in all languages.
1317 if (Info.getLangOpts().CPlusPlus0x) {
1318 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1319 Info.Note(VD->getLocation(), diag::note_declared_at);
1320 } else {
1321 Info.Diag(Loc);
1322 }
Richard Smith96e0c102011-11-04 02:25:55 +00001323 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001324 }
Richard Smith96e0c102011-11-04 02:25:55 +00001325 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001326
Richard Smithf57d8cb2011-12-09 22:58:01 +00001327 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001328 return false;
1329
Richard Smith0b0a0b62011-10-29 20:57:55 +00001330 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001331 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001332
1333 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1334 // conversion. This happens when the declaration and the lvalue should be
1335 // considered synonymous, for instance when initializing an array of char
1336 // from a string literal. Continue as if the initializer lvalue was the
1337 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001338 assert(RVal.getLValueOffset().isZero() &&
1339 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001340 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001341 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001342 }
1343
Richard Smithf2b681b2011-12-21 05:04:46 +00001344 // Volatile temporary objects cannot be read in constant expressions.
1345 if (Base->getType().isVolatileQualified()) {
1346 if (Info.getLangOpts().CPlusPlus) {
1347 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1348 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1349 } else {
1350 Info.Diag(Loc);
1351 }
1352 return false;
1353 }
1354
Richard Smith96e0c102011-11-04 02:25:55 +00001355 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1356 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1357 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001358 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001359 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001360 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001361 }
Richard Smith96e0c102011-11-04 02:25:55 +00001362
1363 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001364 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001365 const ConstantArrayType *CAT =
1366 Info.Ctx.getAsConstantArrayType(S->getType());
1367 if (Index >= CAT->getSize().getZExtValue()) {
1368 // Note, it should not be possible to form a pointer which points more
1369 // than one past the end of the array without producing a prior const expr
1370 // diagnostic.
1371 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001372 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001373 }
Richard Smith96e0c102011-11-04 02:25:55 +00001374 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1375 Type->isUnsignedIntegerType());
1376 if (Index < S->getLength())
1377 Value = S->getCodeUnit(Index);
1378 RVal = CCValue(Value);
1379 return true;
1380 }
1381
Richard Smithf3e9e432011-11-07 09:22:26 +00001382 if (Frame) {
1383 // If this is a temporary expression with a nontrivial initializer, grab the
1384 // value from the relevant stack frame.
1385 RVal = Frame->Temporaries[Base];
1386 } else if (const CompoundLiteralExpr *CLE
1387 = dyn_cast<CompoundLiteralExpr>(Base)) {
1388 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1389 // initializer until now for such expressions. Such an expression can't be
1390 // an ICE in C, so this only matters for fold.
1391 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1392 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1393 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001394 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001395 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001396 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001397 }
Richard Smith96e0c102011-11-04 02:25:55 +00001398
Richard Smithf57d8cb2011-12-09 22:58:01 +00001399 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1400 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001401}
1402
Richard Smithe97cbd72011-11-11 04:05:33 +00001403/// Build an lvalue for the object argument of a member function call.
1404static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1405 LValue &This) {
1406 if (Object->getType()->isPointerType())
1407 return EvaluatePointer(Object, This, Info);
1408
1409 if (Object->isGLValue())
1410 return EvaluateLValue(Object, This, Info);
1411
Richard Smith027bf112011-11-17 22:56:20 +00001412 if (Object->getType()->isLiteralType())
1413 return EvaluateTemporary(Object, This, Info);
1414
1415 return false;
1416}
1417
1418/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1419/// lvalue referring to the result.
1420///
1421/// \param Info - Information about the ongoing evaluation.
1422/// \param BO - The member pointer access operation.
1423/// \param LV - Filled in with a reference to the resulting object.
1424/// \param IncludeMember - Specifies whether the member itself is included in
1425/// the resulting LValue subobject designator. This is not possible when
1426/// creating a bound member function.
1427/// \return The field or method declaration to which the member pointer refers,
1428/// or 0 if evaluation fails.
1429static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1430 const BinaryOperator *BO,
1431 LValue &LV,
1432 bool IncludeMember = true) {
1433 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1434
1435 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1436 return 0;
1437
1438 MemberPtr MemPtr;
1439 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1440 return 0;
1441
1442 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1443 // member value, the behavior is undefined.
1444 if (!MemPtr.getDecl())
1445 return 0;
1446
1447 if (MemPtr.isDerivedMember()) {
1448 // This is a member of some derived class. Truncate LV appropriately.
1449 const CXXRecordDecl *MostDerivedType;
1450 unsigned MostDerivedPathLength;
1451 bool MostDerivedIsArrayElement;
1452 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1453 MostDerivedIsArrayElement))
1454 return 0;
1455
1456 // The end of the derived-to-base path for the base object must match the
1457 // derived-to-base path for the member pointer.
1458 if (MostDerivedPathLength + MemPtr.Path.size() >
1459 LV.Designator.Entries.size())
1460 return 0;
1461 unsigned PathLengthToMember =
1462 LV.Designator.Entries.size() - MemPtr.Path.size();
1463 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1464 const CXXRecordDecl *LVDecl = getAsBaseClass(
1465 LV.Designator.Entries[PathLengthToMember + I]);
1466 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1467 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1468 return 0;
1469 }
1470
1471 // Truncate the lvalue to the appropriate derived class.
1472 bool ResultIsArray = false;
1473 if (PathLengthToMember == MostDerivedPathLength)
1474 ResultIsArray = MostDerivedIsArrayElement;
1475 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1476 PathLengthToMember, ResultIsArray);
1477 } else if (!MemPtr.Path.empty()) {
1478 // Extend the LValue path with the member pointer's path.
1479 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1480 MemPtr.Path.size() + IncludeMember);
1481
1482 // Walk down to the appropriate base class.
1483 QualType LVType = BO->getLHS()->getType();
1484 if (const PointerType *PT = LVType->getAs<PointerType>())
1485 LVType = PT->getPointeeType();
1486 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1487 assert(RD && "member pointer access on non-class-type expression");
1488 // The first class in the path is that of the lvalue.
1489 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1490 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1491 HandleLValueDirectBase(Info, LV, RD, Base);
1492 RD = Base;
1493 }
1494 // Finally cast to the class containing the member.
1495 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1496 }
1497
1498 // Add the member. Note that we cannot build bound member functions here.
1499 if (IncludeMember) {
1500 // FIXME: Deal with IndirectFieldDecls.
1501 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1502 if (!FD) return 0;
1503 HandleLValueMember(Info, LV, FD);
1504 }
1505
1506 return MemPtr.getDecl();
1507}
1508
1509/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1510/// the provided lvalue, which currently refers to the base object.
1511static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1512 LValue &Result) {
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516
1517 // Check this cast doesn't take us outside the object.
1518 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1519 MostDerivedPathLength,
1520 MostDerivedIsArrayElement))
1521 return false;
1522 SubobjectDesignator &D = Result.Designator;
1523 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1524 return false;
1525
1526 // Check the type of the final cast. We don't need to check the path,
1527 // since a cast can only be formed if the path is unique.
1528 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1529 bool ResultIsArray = false;
1530 QualType TargetQT = E->getType();
1531 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1532 TargetQT = PT->getPointeeType();
1533 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1534 const CXXRecordDecl *FinalType;
1535 if (NewEntriesSize == MostDerivedPathLength) {
1536 ResultIsArray = MostDerivedIsArrayElement;
1537 FinalType = MostDerivedType;
1538 } else
1539 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1540 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1541 return false;
1542
1543 // Truncate the lvalue to the appropriate derived class.
1544 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1545 ResultIsArray);
1546 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001547}
1548
Mike Stump876387b2009-10-27 22:09:17 +00001549namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001550enum EvalStmtResult {
1551 /// Evaluation failed.
1552 ESR_Failed,
1553 /// Hit a 'return' statement.
1554 ESR_Returned,
1555 /// Evaluation succeeded.
1556 ESR_Succeeded
1557};
1558}
1559
1560// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001561static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001562 const Stmt *S) {
1563 switch (S->getStmtClass()) {
1564 default:
1565 return ESR_Failed;
1566
1567 case Stmt::NullStmtClass:
1568 case Stmt::DeclStmtClass:
1569 return ESR_Succeeded;
1570
Richard Smith357362d2011-12-13 06:39:58 +00001571 case Stmt::ReturnStmtClass: {
1572 CCValue CCResult;
1573 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1574 if (!Evaluate(CCResult, Info, RetExpr) ||
1575 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1576 CCEK_ReturnValue))
1577 return ESR_Failed;
1578 return ESR_Returned;
1579 }
Richard Smith254a73d2011-10-28 22:34:42 +00001580
1581 case Stmt::CompoundStmtClass: {
1582 const CompoundStmt *CS = cast<CompoundStmt>(S);
1583 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1584 BE = CS->body_end(); BI != BE; ++BI) {
1585 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1586 if (ESR != ESR_Succeeded)
1587 return ESR;
1588 }
1589 return ESR_Succeeded;
1590 }
1591 }
1592}
1593
Richard Smith357362d2011-12-13 06:39:58 +00001594/// CheckConstexprFunction - Check that a function can be called in a constant
1595/// expression.
1596static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1597 const FunctionDecl *Declaration,
1598 const FunctionDecl *Definition) {
1599 // Can we evaluate this function call?
1600 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1601 return true;
1602
1603 if (Info.getLangOpts().CPlusPlus0x) {
1604 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001605 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1606 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001607 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1608 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1609 << DiagDecl;
1610 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1611 } else {
1612 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1613 }
1614 return false;
1615}
1616
Richard Smithd62306a2011-11-10 06:34:14 +00001617namespace {
Richard Smith60494462011-11-11 05:48:57 +00001618typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001619}
1620
1621/// EvaluateArgs - Evaluate the arguments to a function call.
1622static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1623 EvalInfo &Info) {
1624 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1625 I != E; ++I)
1626 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1627 return false;
1628 return true;
1629}
1630
Richard Smith254a73d2011-10-28 22:34:42 +00001631/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001632static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1633 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001634 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001635 EvalInfo &Info, APValue &Result) {
1636 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001637 return false;
1638
Richard Smithd62306a2011-11-10 06:34:14 +00001639 ArgVector ArgValues(Args.size());
1640 if (!EvaluateArgs(Args, ArgValues, Info))
1641 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001642
Richard Smithf6f003a2011-12-16 19:06:07 +00001643 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1644 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001645 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1646}
1647
Richard Smithd62306a2011-11-10 06:34:14 +00001648/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001649static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001650 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001651 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001652 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001653 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001654 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001655 return false;
1656
1657 ArgVector ArgValues(Args.size());
1658 if (!EvaluateArgs(Args, ArgValues, Info))
1659 return false;
1660
Richard Smithf6f003a2011-12-16 19:06:07 +00001661 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1662 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001663
1664 // If it's a delegating constructor, just delegate.
1665 if (Definition->isDelegatingConstructor()) {
1666 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1667 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1668 }
1669
1670 // Reserve space for the struct members.
1671 const CXXRecordDecl *RD = Definition->getParent();
1672 if (!RD->isUnion())
1673 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1674 std::distance(RD->field_begin(), RD->field_end()));
1675
1676 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1677
1678 unsigned BasesSeen = 0;
1679#ifndef NDEBUG
1680 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1681#endif
1682 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1683 E = Definition->init_end(); I != E; ++I) {
1684 if ((*I)->isBaseInitializer()) {
1685 QualType BaseType((*I)->getBaseClass(), 0);
1686#ifndef NDEBUG
1687 // Non-virtual base classes are initialized in the order in the class
1688 // definition. We cannot have a virtual base class for a literal type.
1689 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1690 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1691 "base class initializers not in expected order");
1692 ++BaseIt;
1693#endif
1694 LValue Subobject = This;
1695 HandleLValueDirectBase(Info, Subobject, RD,
1696 BaseType->getAsCXXRecordDecl(), &Layout);
1697 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1698 Subobject, (*I)->getInit()))
1699 return false;
1700 } else if (FieldDecl *FD = (*I)->getMember()) {
1701 LValue Subobject = This;
1702 HandleLValueMember(Info, Subobject, FD, &Layout);
1703 if (RD->isUnion()) {
1704 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001705 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1706 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001707 return false;
1708 } else if (!EvaluateConstantExpression(
1709 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001710 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001711 return false;
1712 } else {
1713 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001714 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001715 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001716 return false;
1717 }
1718 }
1719
1720 return true;
1721}
1722
Richard Smith254a73d2011-10-28 22:34:42 +00001723namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001724class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001725 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001726 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001727public:
1728
Richard Smith725810a2011-10-16 21:26:27 +00001729 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001730
1731 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001732 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001733 return true;
1734 }
1735
Peter Collingbournee9200682011-05-13 03:29:01 +00001736 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1737 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001738 return Visit(E->getResultExpr());
1739 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001740 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001741 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001742 return true;
1743 return false;
1744 }
John McCall31168b02011-06-15 23:02:42 +00001745 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001746 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001747 return true;
1748 return false;
1749 }
1750 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001751 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001752 return true;
1753 return false;
1754 }
1755
Mike Stump876387b2009-10-27 22:09:17 +00001756 // We don't want to evaluate BlockExprs multiple times, as they generate
1757 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001758 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1759 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1760 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001761 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001762 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1763 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1764 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1765 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1766 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1767 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001768 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001769 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001770 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001771 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001772 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001773 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1774 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1775 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1776 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001777 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001778 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1779 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1780 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1781 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1782 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001783 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001784 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001785 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001786 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001787 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001788
1789 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001790 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001791 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1792 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001793 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001794 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001795 return false;
1796 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001797
Peter Collingbournee9200682011-05-13 03:29:01 +00001798 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001799};
1800
John McCallc07a0c72011-02-17 10:25:35 +00001801class OpaqueValueEvaluation {
1802 EvalInfo &info;
1803 OpaqueValueExpr *opaqueValue;
1804
1805public:
1806 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1807 Expr *value)
1808 : info(info), opaqueValue(opaqueValue) {
1809
1810 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001811 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001812 this->opaqueValue = 0;
1813 return;
1814 }
John McCallc07a0c72011-02-17 10:25:35 +00001815 }
1816
1817 bool hasError() const { return opaqueValue == 0; }
1818
1819 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001820 // FIXME: This will not work for recursive constexpr functions using opaque
1821 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001822 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1823 }
1824};
1825
Mike Stump876387b2009-10-27 22:09:17 +00001826} // end anonymous namespace
1827
Eli Friedman9a156e52008-11-12 09:44:48 +00001828//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001829// Generic Evaluation
1830//===----------------------------------------------------------------------===//
1831namespace {
1832
Richard Smithf57d8cb2011-12-09 22:58:01 +00001833// FIXME: RetTy is always bool. Remove it.
1834template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001835class ExprEvaluatorBase
1836 : public ConstStmtVisitor<Derived, RetTy> {
1837private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001838 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001839 return static_cast<Derived*>(this)->Success(V, E);
1840 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001841 RetTy DerivedValueInitialization(const Expr *E) {
1842 return static_cast<Derived*>(this)->ValueInitialization(E);
1843 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001844
1845protected:
1846 EvalInfo &Info;
1847 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1848 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1849
Richard Smith92b1ce02011-12-12 09:28:41 +00001850 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001851 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001852 }
1853
1854 /// Report an evaluation error. This should only be called when an error is
1855 /// first discovered. When propagating an error, just return false.
1856 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001857 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001858 return false;
1859 }
1860 bool Error(const Expr *E) {
1861 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1862 }
1863
1864 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001865
Peter Collingbournee9200682011-05-13 03:29:01 +00001866public:
1867 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1868
1869 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001870 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001871 }
1872 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001873 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001874 }
1875
1876 RetTy VisitParenExpr(const ParenExpr *E)
1877 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1878 RetTy VisitUnaryExtension(const UnaryOperator *E)
1879 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1880 RetTy VisitUnaryPlus(const UnaryOperator *E)
1881 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1882 RetTy VisitChooseExpr(const ChooseExpr *E)
1883 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1884 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1885 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001886 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1887 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001888 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1889 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001890 // We cannot create any objects for which cleanups are required, so there is
1891 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1892 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1893 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001894
Richard Smith6d6ecc32011-12-12 12:46:16 +00001895 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1896 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1897 return static_cast<Derived*>(this)->VisitCastExpr(E);
1898 }
1899 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1900 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1901 return static_cast<Derived*>(this)->VisitCastExpr(E);
1902 }
1903
Richard Smith027bf112011-11-17 22:56:20 +00001904 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1905 switch (E->getOpcode()) {
1906 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001907 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001908
1909 case BO_Comma:
1910 VisitIgnoredValue(E->getLHS());
1911 return StmtVisitorTy::Visit(E->getRHS());
1912
1913 case BO_PtrMemD:
1914 case BO_PtrMemI: {
1915 LValue Obj;
1916 if (!HandleMemberPointerAccess(Info, E, Obj))
1917 return false;
1918 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001919 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001920 return false;
1921 return DerivedSuccess(Result, E);
1922 }
1923 }
1924 }
1925
Peter Collingbournee9200682011-05-13 03:29:01 +00001926 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1927 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1928 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001929 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001930
1931 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001932 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001933 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001934
1935 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1936 }
1937
1938 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1939 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001940 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001941 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001942
Richard Smith11562c52011-10-28 17:51:58 +00001943 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001944 return StmtVisitorTy::Visit(EvalExpr);
1945 }
1946
1947 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001948 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001949 if (!Value) {
1950 const Expr *Source = E->getSourceExpr();
1951 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001952 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001953 if (Source == E) { // sanity checking.
1954 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001955 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001956 }
1957 return StmtVisitorTy::Visit(Source);
1958 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001959 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001960 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001961
Richard Smith254a73d2011-10-28 22:34:42 +00001962 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001963 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001964 QualType CalleeType = Callee->getType();
1965
Richard Smith254a73d2011-10-28 22:34:42 +00001966 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001967 LValue *This = 0, ThisVal;
1968 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001969
Richard Smithe97cbd72011-11-11 04:05:33 +00001970 // Extract function decl and 'this' pointer from the callee.
1971 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001972 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001973 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1974 // Explicit bound member calls, such as x.f() or p->g();
1975 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 return false;
1977 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001978 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001979 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1980 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001981 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1982 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001983 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001984 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001985 return Error(Callee);
1986
1987 FD = dyn_cast<FunctionDecl>(Member);
1988 if (!FD)
1989 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001990 } else if (CalleeType->isFunctionPointerType()) {
1991 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001992 if (!Evaluate(Call, Info, Callee))
1993 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001994
Richard Smithf57d8cb2011-12-09 22:58:01 +00001995 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1996 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001997 FD = dyn_cast_or_null<FunctionDecl>(
1998 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001999 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002000 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002001
2002 // Overloaded operator calls to member functions are represented as normal
2003 // calls with '*this' as the first argument.
2004 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2005 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002006 // FIXME: When selecting an implicit conversion for an overloaded
2007 // operator delete, we sometimes try to evaluate calls to conversion
2008 // operators without a 'this' parameter!
2009 if (Args.empty())
2010 return Error(E);
2011
Richard Smithe97cbd72011-11-11 04:05:33 +00002012 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2013 return false;
2014 This = &ThisVal;
2015 Args = Args.slice(1);
2016 }
2017
2018 // Don't call function pointers which have been cast to some other type.
2019 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002020 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002021 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002022 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002023
Richard Smith357362d2011-12-13 06:39:58 +00002024 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002025 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002026 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002027
Richard Smith357362d2011-12-13 06:39:58 +00002028 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002029 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002030 return false;
2031
2032 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002033 }
2034
Richard Smith11562c52011-10-28 17:51:58 +00002035 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2036 return StmtVisitorTy::Visit(E->getInitializer());
2037 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002038 RetTy VisitInitListExpr(const InitListExpr *E) {
2039 if (Info.getLangOpts().CPlusPlus0x) {
2040 if (E->getNumInits() == 0)
2041 return DerivedValueInitialization(E);
2042 if (E->getNumInits() == 1)
2043 return StmtVisitorTy::Visit(E->getInit(0));
2044 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00002045 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002046 }
2047 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2048 return DerivedValueInitialization(E);
2049 }
2050 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2051 return DerivedValueInitialization(E);
2052 }
Richard Smith027bf112011-11-17 22:56:20 +00002053 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2054 return DerivedValueInitialization(E);
2055 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002056
Richard Smithd62306a2011-11-10 06:34:14 +00002057 /// A member expression where the object is a prvalue is itself a prvalue.
2058 RetTy VisitMemberExpr(const MemberExpr *E) {
2059 assert(!E->isArrow() && "missing call to bound member function?");
2060
2061 CCValue Val;
2062 if (!Evaluate(Val, Info, E->getBase()))
2063 return false;
2064
2065 QualType BaseTy = E->getBase()->getType();
2066
2067 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002068 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002069 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2070 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2071 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2072
2073 SubobjectDesignator Designator;
2074 Designator.addDecl(FD);
2075
Richard Smithf57d8cb2011-12-09 22:58:01 +00002076 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002077 DerivedSuccess(Val, E);
2078 }
2079
Richard Smith11562c52011-10-28 17:51:58 +00002080 RetTy VisitCastExpr(const CastExpr *E) {
2081 switch (E->getCastKind()) {
2082 default:
2083 break;
2084
2085 case CK_NoOp:
2086 return StmtVisitorTy::Visit(E->getSubExpr());
2087
2088 case CK_LValueToRValue: {
2089 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2091 return false;
2092 CCValue RVal;
2093 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2094 return false;
2095 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002096 }
2097 }
2098
Richard Smithf57d8cb2011-12-09 22:58:01 +00002099 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002100 }
2101
Richard Smith4a678122011-10-24 18:44:57 +00002102 /// Visit a value which is evaluated, but whose value is ignored.
2103 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002104 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002105 if (!Evaluate(Scratch, Info, E))
2106 Info.EvalStatus.HasSideEffects = true;
2107 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002108};
2109
2110}
2111
2112//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002113// Common base class for lvalue and temporary evaluation.
2114//===----------------------------------------------------------------------===//
2115namespace {
2116template<class Derived>
2117class LValueExprEvaluatorBase
2118 : public ExprEvaluatorBase<Derived, bool> {
2119protected:
2120 LValue &Result;
2121 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2122 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2123
2124 bool Success(APValue::LValueBase B) {
2125 Result.set(B);
2126 return true;
2127 }
2128
2129public:
2130 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2131 ExprEvaluatorBaseTy(Info), Result(Result) {}
2132
2133 bool Success(const CCValue &V, const Expr *E) {
2134 Result.setFrom(V);
2135 return true;
2136 }
Richard Smith027bf112011-11-17 22:56:20 +00002137
2138 bool CheckValidLValue() {
2139 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2140 // there are no null references, nor once-past-the-end references.
2141 // FIXME: Check for one-past-the-end array indices
2142 return Result.Base && !Result.Designator.Invalid &&
2143 !Result.Designator.OnePastTheEnd;
2144 }
2145
2146 bool VisitMemberExpr(const MemberExpr *E) {
2147 // Handle non-static data members.
2148 QualType BaseTy;
2149 if (E->isArrow()) {
2150 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2151 return false;
2152 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002153 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002154 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002155 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2156 return false;
2157 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002158 } else {
2159 if (!this->Visit(E->getBase()))
2160 return false;
2161 BaseTy = E->getBase()->getType();
2162 }
2163 // FIXME: In C++11, require the result to be a valid lvalue.
2164
2165 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2166 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002167 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002168 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2169 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2170 (void)BaseTy;
2171
2172 HandleLValueMember(this->Info, Result, FD);
2173
2174 if (FD->getType()->isReferenceType()) {
2175 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002176 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002177 RefValue))
2178 return false;
2179 return Success(RefValue, E);
2180 }
2181 return true;
2182 }
2183
2184 bool VisitBinaryOperator(const BinaryOperator *E) {
2185 switch (E->getOpcode()) {
2186 default:
2187 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2188
2189 case BO_PtrMemD:
2190 case BO_PtrMemI:
2191 return HandleMemberPointerAccess(this->Info, E, Result);
2192 }
2193 }
2194
2195 bool VisitCastExpr(const CastExpr *E) {
2196 switch (E->getCastKind()) {
2197 default:
2198 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2199
2200 case CK_DerivedToBase:
2201 case CK_UncheckedDerivedToBase: {
2202 if (!this->Visit(E->getSubExpr()))
2203 return false;
2204 if (!CheckValidLValue())
2205 return false;
2206
2207 // Now figure out the necessary offset to add to the base LV to get from
2208 // the derived class to the base class.
2209 QualType Type = E->getSubExpr()->getType();
2210
2211 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2212 PathE = E->path_end(); PathI != PathE; ++PathI) {
2213 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2214 *PathI))
2215 return false;
2216 Type = (*PathI)->getType();
2217 }
2218
2219 return true;
2220 }
2221 }
2222 }
2223};
2224}
2225
2226//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002227// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002228//
2229// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2230// function designators (in C), decl references to void objects (in C), and
2231// temporaries (if building with -Wno-address-of-temporary).
2232//
2233// LValue evaluation produces values comprising a base expression of one of the
2234// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002235// - Declarations
2236// * VarDecl
2237// * FunctionDecl
2238// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002239// * CompoundLiteralExpr in C
2240// * StringLiteral
2241// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002242// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002243// * ObjCEncodeExpr
2244// * AddrLabelExpr
2245// * BlockExpr
2246// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002247// - Locals and temporaries
2248// * Any Expr, with a Frame indicating the function in which the temporary was
2249// evaluated.
2250// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002251//===----------------------------------------------------------------------===//
2252namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002253class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002254 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002255public:
Richard Smith027bf112011-11-17 22:56:20 +00002256 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2257 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002258
Richard Smith11562c52011-10-28 17:51:58 +00002259 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2260
Peter Collingbournee9200682011-05-13 03:29:01 +00002261 bool VisitDeclRefExpr(const DeclRefExpr *E);
2262 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002263 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002264 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2265 bool VisitMemberExpr(const MemberExpr *E);
2266 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2267 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2268 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2269 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002270
Peter Collingbournee9200682011-05-13 03:29:01 +00002271 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002272 switch (E->getCastKind()) {
2273 default:
Richard Smith027bf112011-11-17 22:56:20 +00002274 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002275
Eli Friedmance3e02a2011-10-11 00:13:24 +00002276 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002277 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002278 if (!Visit(E->getSubExpr()))
2279 return false;
2280 Result.Designator.setInvalid();
2281 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002282
Richard Smith027bf112011-11-17 22:56:20 +00002283 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002284 if (!Visit(E->getSubExpr()))
2285 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002286 if (!CheckValidLValue())
2287 return false;
2288 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002289 }
2290 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002291
Eli Friedman449fe542009-03-23 04:56:01 +00002292 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002293
Eli Friedman9a156e52008-11-12 09:44:48 +00002294};
2295} // end anonymous namespace
2296
Richard Smith11562c52011-10-28 17:51:58 +00002297/// Evaluate an expression as an lvalue. This can be legitimately called on
2298/// expressions which are not glvalues, in a few cases:
2299/// * function designators in C,
2300/// * "extern void" objects,
2301/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002302static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002303 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2304 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2305 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002306 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002307}
2308
Peter Collingbournee9200682011-05-13 03:29:01 +00002309bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002310 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2311 return Success(FD);
2312 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002313 return VisitVarDecl(E, VD);
2314 return Error(E);
2315}
Richard Smith733237d2011-10-24 23:14:33 +00002316
Richard Smith11562c52011-10-28 17:51:58 +00002317bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002318 if (!VD->getType()->isReferenceType()) {
2319 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002320 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002321 return true;
2322 }
Richard Smithce40ad62011-11-12 22:28:03 +00002323 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002324 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002325
Richard Smith0b0a0b62011-10-29 20:57:55 +00002326 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002327 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2328 return false;
2329 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002330}
2331
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002332bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2333 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002334 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002335 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002336 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2337
2338 Result.set(E, Info.CurrentCall);
2339 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2340 Result, E->GetTemporaryExpr());
2341 }
2342
2343 // Materialization of an lvalue temporary occurs when we need to force a copy
2344 // (for instance, if it's a bitfield).
2345 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2346 if (!Visit(E->GetTemporaryExpr()))
2347 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002348 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002349 Info.CurrentCall->Temporaries[E]))
2350 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002351 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002352 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002353}
2354
Peter Collingbournee9200682011-05-13 03:29:01 +00002355bool
2356LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002357 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2358 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2359 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002360 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002361}
2362
Peter Collingbournee9200682011-05-13 03:29:01 +00002363bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002364 // Handle static data members.
2365 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2366 VisitIgnoredValue(E->getBase());
2367 return VisitVarDecl(E, VD);
2368 }
2369
Richard Smith254a73d2011-10-28 22:34:42 +00002370 // Handle static member functions.
2371 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2372 if (MD->isStatic()) {
2373 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002374 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002375 }
2376 }
2377
Richard Smithd62306a2011-11-10 06:34:14 +00002378 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002379 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002380}
2381
Peter Collingbournee9200682011-05-13 03:29:01 +00002382bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002383 // FIXME: Deal with vectors as array subscript bases.
2384 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002385 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002386
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002387 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002388 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002389
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002390 APSInt Index;
2391 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002392 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002393 int64_t IndexValue
2394 = Index.isSigned() ? Index.getSExtValue()
2395 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002396
Richard Smith027bf112011-11-17 22:56:20 +00002397 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002398 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002399}
Eli Friedman9a156e52008-11-12 09:44:48 +00002400
Peter Collingbournee9200682011-05-13 03:29:01 +00002401bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002402 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002403 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002404}
2405
Eli Friedman9a156e52008-11-12 09:44:48 +00002406//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002407// Pointer Evaluation
2408//===----------------------------------------------------------------------===//
2409
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002410namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002411class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002412 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002413 LValue &Result;
2414
Peter Collingbournee9200682011-05-13 03:29:01 +00002415 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002416 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002417 return true;
2418 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002419public:
Mike Stump11289f42009-09-09 15:08:12 +00002420
John McCall45d55e42010-05-07 21:00:08 +00002421 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002422 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002423
Richard Smith0b0a0b62011-10-29 20:57:55 +00002424 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002425 Result.setFrom(V);
2426 return true;
2427 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002428 bool ValueInitialization(const Expr *E) {
2429 return Success((Expr*)0);
2430 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002431
John McCall45d55e42010-05-07 21:00:08 +00002432 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002433 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002434 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002435 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002436 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002437 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002438 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002439 bool VisitCallExpr(const CallExpr *E);
2440 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002441 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002442 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002443 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002444 }
Richard Smithd62306a2011-11-10 06:34:14 +00002445 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2446 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002447 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002448 Result = *Info.CurrentCall->This;
2449 return true;
2450 }
John McCallc07a0c72011-02-17 10:25:35 +00002451
Eli Friedman449fe542009-03-23 04:56:01 +00002452 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002453};
Chris Lattner05706e882008-07-11 18:11:29 +00002454} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002455
John McCall45d55e42010-05-07 21:00:08 +00002456static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002457 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002458 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002459}
2460
John McCall45d55e42010-05-07 21:00:08 +00002461bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002462 if (E->getOpcode() != BO_Add &&
2463 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002464 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002465
Chris Lattner05706e882008-07-11 18:11:29 +00002466 const Expr *PExp = E->getLHS();
2467 const Expr *IExp = E->getRHS();
2468 if (IExp->getType()->isPointerType())
2469 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002470
John McCall45d55e42010-05-07 21:00:08 +00002471 if (!EvaluatePointer(PExp, Result, Info))
2472 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002473
John McCall45d55e42010-05-07 21:00:08 +00002474 llvm::APSInt Offset;
2475 if (!EvaluateInteger(IExp, Offset, Info))
2476 return false;
2477 int64_t AdditionalOffset
2478 = Offset.isSigned() ? Offset.getSExtValue()
2479 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002480 if (E->getOpcode() == BO_Sub)
2481 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002482
Richard Smithd62306a2011-11-10 06:34:14 +00002483 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002484 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002485 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002486}
Eli Friedman9a156e52008-11-12 09:44:48 +00002487
John McCall45d55e42010-05-07 21:00:08 +00002488bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2489 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002490}
Mike Stump11289f42009-09-09 15:08:12 +00002491
Peter Collingbournee9200682011-05-13 03:29:01 +00002492bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2493 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002494
Eli Friedman847a2bc2009-12-27 05:43:15 +00002495 switch (E->getCastKind()) {
2496 default:
2497 break;
2498
John McCalle3027922010-08-25 11:45:40 +00002499 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002500 case CK_CPointerToObjCPointerCast:
2501 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002502 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002503 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2504 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2505 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002506 if (!E->getType()->isVoidPointerType()) {
2507 if (SubExpr->getType()->isVoidPointerType())
2508 CCEDiag(E, diag::note_constexpr_invalid_cast)
2509 << 3 << SubExpr->getType();
2510 else
2511 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2512 }
Richard Smith96e0c102011-11-04 02:25:55 +00002513 if (!Visit(SubExpr))
2514 return false;
2515 Result.Designator.setInvalid();
2516 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002517
Anders Carlsson18275092010-10-31 20:41:46 +00002518 case CK_DerivedToBase:
2519 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002520 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002521 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002522 if (!Result.Base && Result.Offset.isZero())
2523 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002524
Richard Smithd62306a2011-11-10 06:34:14 +00002525 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002526 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002527 QualType Type =
2528 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002529
Richard Smithd62306a2011-11-10 06:34:14 +00002530 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002531 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002532 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002533 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002534 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002535 }
2536
Anders Carlsson18275092010-10-31 20:41:46 +00002537 return true;
2538 }
2539
Richard Smith027bf112011-11-17 22:56:20 +00002540 case CK_BaseToDerived:
2541 if (!Visit(E->getSubExpr()))
2542 return false;
2543 if (!Result.Base && Result.Offset.isZero())
2544 return true;
2545 return HandleBaseToDerivedCast(Info, E, Result);
2546
Richard Smith0b0a0b62011-10-29 20:57:55 +00002547 case CK_NullToPointer:
2548 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002549
John McCalle3027922010-08-25 11:45:40 +00002550 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002551 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2552
Richard Smith0b0a0b62011-10-29 20:57:55 +00002553 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002554 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002555 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002556
John McCall45d55e42010-05-07 21:00:08 +00002557 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002558 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2559 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002560 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002561 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002562 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002563 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002564 return true;
2565 } else {
2566 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002567 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002568 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002569 }
2570 }
John McCalle3027922010-08-25 11:45:40 +00002571 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002572 if (SubExpr->isGLValue()) {
2573 if (!EvaluateLValue(SubExpr, Result, Info))
2574 return false;
2575 } else {
2576 Result.set(SubExpr, Info.CurrentCall);
2577 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2578 Info, Result, SubExpr))
2579 return false;
2580 }
Richard Smith96e0c102011-11-04 02:25:55 +00002581 // The result is a pointer to the first element of the array.
2582 Result.Designator.addIndex(0);
2583 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002584
John McCalle3027922010-08-25 11:45:40 +00002585 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002586 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002587 }
2588
Richard Smith11562c52011-10-28 17:51:58 +00002589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002590}
Chris Lattner05706e882008-07-11 18:11:29 +00002591
Peter Collingbournee9200682011-05-13 03:29:01 +00002592bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002593 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002594 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002595
Peter Collingbournee9200682011-05-13 03:29:01 +00002596 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002597}
Chris Lattner05706e882008-07-11 18:11:29 +00002598
2599//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002600// Member Pointer Evaluation
2601//===----------------------------------------------------------------------===//
2602
2603namespace {
2604class MemberPointerExprEvaluator
2605 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2606 MemberPtr &Result;
2607
2608 bool Success(const ValueDecl *D) {
2609 Result = MemberPtr(D);
2610 return true;
2611 }
2612public:
2613
2614 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2615 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2616
2617 bool Success(const CCValue &V, const Expr *E) {
2618 Result.setFrom(V);
2619 return true;
2620 }
Richard Smith027bf112011-11-17 22:56:20 +00002621 bool ValueInitialization(const Expr *E) {
2622 return Success((const ValueDecl*)0);
2623 }
2624
2625 bool VisitCastExpr(const CastExpr *E);
2626 bool VisitUnaryAddrOf(const UnaryOperator *E);
2627};
2628} // end anonymous namespace
2629
2630static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2631 EvalInfo &Info) {
2632 assert(E->isRValue() && E->getType()->isMemberPointerType());
2633 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2634}
2635
2636bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2637 switch (E->getCastKind()) {
2638 default:
2639 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2640
2641 case CK_NullToMemberPointer:
2642 return ValueInitialization(E);
2643
2644 case CK_BaseToDerivedMemberPointer: {
2645 if (!Visit(E->getSubExpr()))
2646 return false;
2647 if (E->path_empty())
2648 return true;
2649 // Base-to-derived member pointer casts store the path in derived-to-base
2650 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2651 // the wrong end of the derived->base arc, so stagger the path by one class.
2652 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2653 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2654 PathI != PathE; ++PathI) {
2655 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2656 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2657 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002659 }
2660 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2661 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002662 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002663 return true;
2664 }
2665
2666 case CK_DerivedToBaseMemberPointer:
2667 if (!Visit(E->getSubExpr()))
2668 return false;
2669 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2670 PathE = E->path_end(); PathI != PathE; ++PathI) {
2671 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2672 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2673 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002674 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002675 }
2676 return true;
2677 }
2678}
2679
2680bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2681 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2682 // member can be formed.
2683 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2684}
2685
2686//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002687// Record Evaluation
2688//===----------------------------------------------------------------------===//
2689
2690namespace {
2691 class RecordExprEvaluator
2692 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2693 const LValue &This;
2694 APValue &Result;
2695 public:
2696
2697 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2698 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2699
2700 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002701 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002702 }
Richard Smithd62306a2011-11-10 06:34:14 +00002703
Richard Smithe97cbd72011-11-11 04:05:33 +00002704 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002705 bool VisitInitListExpr(const InitListExpr *E);
2706 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2707 };
2708}
2709
Richard Smithe97cbd72011-11-11 04:05:33 +00002710bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2711 switch (E->getCastKind()) {
2712 default:
2713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2714
2715 case CK_ConstructorConversion:
2716 return Visit(E->getSubExpr());
2717
2718 case CK_DerivedToBase:
2719 case CK_UncheckedDerivedToBase: {
2720 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002721 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002722 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002723 if (!DerivedObject.isStruct())
2724 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002725
2726 // Derived-to-base rvalue conversion: just slice off the derived part.
2727 APValue *Value = &DerivedObject;
2728 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2729 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2730 PathE = E->path_end(); PathI != PathE; ++PathI) {
2731 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2732 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2733 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2734 RD = Base;
2735 }
2736 Result = *Value;
2737 return true;
2738 }
2739 }
2740}
2741
Richard Smithd62306a2011-11-10 06:34:14 +00002742bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2743 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2744 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2745
2746 if (RD->isUnion()) {
2747 Result = APValue(E->getInitializedFieldInUnion());
2748 if (!E->getNumInits())
2749 return true;
2750 LValue Subobject = This;
2751 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2752 &Layout);
2753 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2754 Subobject, E->getInit(0));
2755 }
2756
2757 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2758 "initializer list for class with base classes");
2759 Result = APValue(APValue::UninitStruct(), 0,
2760 std::distance(RD->field_begin(), RD->field_end()));
2761 unsigned ElementNo = 0;
2762 for (RecordDecl::field_iterator Field = RD->field_begin(),
2763 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2764 // Anonymous bit-fields are not considered members of the class for
2765 // purposes of aggregate initialization.
2766 if (Field->isUnnamedBitfield())
2767 continue;
2768
2769 LValue Subobject = This;
2770 HandleLValueMember(Info, Subobject, *Field, &Layout);
2771
2772 if (ElementNo < E->getNumInits()) {
2773 if (!EvaluateConstantExpression(
2774 Result.getStructField((*Field)->getFieldIndex()),
2775 Info, Subobject, E->getInit(ElementNo++)))
2776 return false;
2777 } else {
2778 // Perform an implicit value-initialization for members beyond the end of
2779 // the initializer list.
2780 ImplicitValueInitExpr VIE(Field->getType());
2781 if (!EvaluateConstantExpression(
2782 Result.getStructField((*Field)->getFieldIndex()),
2783 Info, Subobject, &VIE))
2784 return false;
2785 }
2786 }
2787
2788 return true;
2789}
2790
2791bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2792 const CXXConstructorDecl *FD = E->getConstructor();
2793 const FunctionDecl *Definition = 0;
2794 FD->getBody(Definition);
2795
Richard Smith357362d2011-12-13 06:39:58 +00002796 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2797 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002798
2799 // FIXME: Elide the copy/move construction wherever we can.
2800 if (E->isElidable())
2801 if (const MaterializeTemporaryExpr *ME
2802 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2803 return Visit(ME->GetTemporaryExpr());
2804
2805 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002806 return HandleConstructorCall(E, This, Args,
2807 cast<CXXConstructorDecl>(Definition), Info,
2808 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002809}
2810
2811static bool EvaluateRecord(const Expr *E, const LValue &This,
2812 APValue &Result, EvalInfo &Info) {
2813 assert(E->isRValue() && E->getType()->isRecordType() &&
2814 E->getType()->isLiteralType() &&
2815 "can't evaluate expression as a record rvalue");
2816 return RecordExprEvaluator(Info, This, Result).Visit(E);
2817}
2818
2819//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002820// Temporary Evaluation
2821//
2822// Temporaries are represented in the AST as rvalues, but generally behave like
2823// lvalues. The full-object of which the temporary is a subobject is implicitly
2824// materialized so that a reference can bind to it.
2825//===----------------------------------------------------------------------===//
2826namespace {
2827class TemporaryExprEvaluator
2828 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2829public:
2830 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2831 LValueExprEvaluatorBaseTy(Info, Result) {}
2832
2833 /// Visit an expression which constructs the value of this temporary.
2834 bool VisitConstructExpr(const Expr *E) {
2835 Result.set(E, Info.CurrentCall);
2836 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2837 Result, E);
2838 }
2839
2840 bool VisitCastExpr(const CastExpr *E) {
2841 switch (E->getCastKind()) {
2842 default:
2843 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2844
2845 case CK_ConstructorConversion:
2846 return VisitConstructExpr(E->getSubExpr());
2847 }
2848 }
2849 bool VisitInitListExpr(const InitListExpr *E) {
2850 return VisitConstructExpr(E);
2851 }
2852 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2853 return VisitConstructExpr(E);
2854 }
2855 bool VisitCallExpr(const CallExpr *E) {
2856 return VisitConstructExpr(E);
2857 }
2858};
2859} // end anonymous namespace
2860
2861/// Evaluate an expression of record type as a temporary.
2862static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002863 assert(E->isRValue() && E->getType()->isRecordType());
2864 if (!E->getType()->isLiteralType()) {
2865 if (Info.getLangOpts().CPlusPlus0x)
2866 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2867 << E->getType();
2868 else
2869 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2870 return false;
2871 }
Richard Smith027bf112011-11-17 22:56:20 +00002872 return TemporaryExprEvaluator(Info, Result).Visit(E);
2873}
2874
2875//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002876// Vector Evaluation
2877//===----------------------------------------------------------------------===//
2878
2879namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002880 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002881 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2882 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002883 public:
Mike Stump11289f42009-09-09 15:08:12 +00002884
Richard Smith2d406342011-10-22 21:10:00 +00002885 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2886 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002887
Richard Smith2d406342011-10-22 21:10:00 +00002888 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2889 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2890 // FIXME: remove this APValue copy.
2891 Result = APValue(V.data(), V.size());
2892 return true;
2893 }
Richard Smithed5165f2011-11-04 05:33:44 +00002894 bool Success(const CCValue &V, const Expr *E) {
2895 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002896 Result = V;
2897 return true;
2898 }
Richard Smith2d406342011-10-22 21:10:00 +00002899 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002900
Richard Smith2d406342011-10-22 21:10:00 +00002901 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002902 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002903 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002904 bool VisitInitListExpr(const InitListExpr *E);
2905 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002906 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002907 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002908 // shufflevector, ExtVectorElementExpr
2909 // (Note that these require implementing conversions
2910 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002911 };
2912} // end anonymous namespace
2913
2914static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002915 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002916 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002917}
2918
Richard Smith2d406342011-10-22 21:10:00 +00002919bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2920 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002921 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002922
Richard Smith161f09a2011-12-06 22:44:34 +00002923 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002924 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002925
Eli Friedmanc757de22011-03-25 00:43:55 +00002926 switch (E->getCastKind()) {
2927 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002928 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002929 if (SETy->isIntegerType()) {
2930 APSInt IntResult;
2931 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002932 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002933 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002934 } else if (SETy->isRealFloatingType()) {
2935 APFloat F(0.0);
2936 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002937 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002938 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002939 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002940 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002941 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002942
2943 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002944 SmallVector<APValue, 4> Elts(NElts, Val);
2945 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002946 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002947 default:
Richard Smith11562c52011-10-28 17:51:58 +00002948 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002949 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002950}
2951
Richard Smith2d406342011-10-22 21:10:00 +00002952bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002953VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002954 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002955 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002956 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002957
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002958 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002959 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002960
John McCall875679e2010-06-11 17:54:15 +00002961 // If a vector is initialized with a single element, that value
2962 // becomes every element of the vector, not just the first.
2963 // This is the behavior described in the IBM AltiVec documentation.
2964 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002965
2966 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002967 // vector (OpenCL 6.1.6).
2968 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002969 return Visit(E->getInit(0));
2970
John McCall875679e2010-06-11 17:54:15 +00002971 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002972 if (EltTy->isIntegerType()) {
2973 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002974 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002975 return false;
John McCall875679e2010-06-11 17:54:15 +00002976 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002977 } else {
2978 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002979 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002980 return false;
John McCall875679e2010-06-11 17:54:15 +00002981 InitValue = APValue(f);
2982 }
2983 for (unsigned i = 0; i < NumElements; i++) {
2984 Elements.push_back(InitValue);
2985 }
2986 } else {
2987 for (unsigned i = 0; i < NumElements; i++) {
2988 if (EltTy->isIntegerType()) {
2989 llvm::APSInt sInt(32);
2990 if (i < NumInits) {
2991 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002992 return false;
John McCall875679e2010-06-11 17:54:15 +00002993 } else {
2994 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2995 }
2996 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002997 } else {
John McCall875679e2010-06-11 17:54:15 +00002998 llvm::APFloat f(0.0);
2999 if (i < NumInits) {
3000 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003001 return false;
John McCall875679e2010-06-11 17:54:15 +00003002 } else {
3003 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3004 }
3005 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00003006 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003007 }
3008 }
Richard Smith2d406342011-10-22 21:10:00 +00003009 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003010}
3011
Richard Smith2d406342011-10-22 21:10:00 +00003012bool
3013VectorExprEvaluator::ValueInitialization(const Expr *E) {
3014 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003015 QualType EltTy = VT->getElementType();
3016 APValue ZeroElement;
3017 if (EltTy->isIntegerType())
3018 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3019 else
3020 ZeroElement =
3021 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3022
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003023 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003024 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003025}
3026
Richard Smith2d406342011-10-22 21:10:00 +00003027bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003028 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00003029 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003030}
3031
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003032//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003033// Array Evaluation
3034//===----------------------------------------------------------------------===//
3035
3036namespace {
3037 class ArrayExprEvaluator
3038 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003039 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003040 APValue &Result;
3041 public:
3042
Richard Smithd62306a2011-11-10 06:34:14 +00003043 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3044 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003045
3046 bool Success(const APValue &V, const Expr *E) {
3047 assert(V.isArray() && "Expected array type");
3048 Result = V;
3049 return true;
3050 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003051
Richard Smithd62306a2011-11-10 06:34:14 +00003052 bool ValueInitialization(const Expr *E) {
3053 const ConstantArrayType *CAT =
3054 Info.Ctx.getAsConstantArrayType(E->getType());
3055 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003056 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003057
3058 Result = APValue(APValue::UninitArray(), 0,
3059 CAT->getSize().getZExtValue());
3060 if (!Result.hasArrayFiller()) return true;
3061
3062 // Value-initialize all elements.
3063 LValue Subobject = This;
3064 Subobject.Designator.addIndex(0);
3065 ImplicitValueInitExpr VIE(CAT->getElementType());
3066 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3067 Subobject, &VIE);
3068 }
3069
Richard Smithf3e9e432011-11-07 09:22:26 +00003070 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003071 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003072 };
3073} // end anonymous namespace
3074
Richard Smithd62306a2011-11-10 06:34:14 +00003075static bool EvaluateArray(const Expr *E, const LValue &This,
3076 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00003077 assert(E->isRValue() && E->getType()->isArrayType() &&
3078 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003079 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003080}
3081
3082bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3083 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3084 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003085 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003086
Richard Smithca2cfbf2011-12-22 01:07:19 +00003087 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3088 // an appropriately-typed string literal enclosed in braces.
3089 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3090 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3091 LValue LV;
3092 if (!EvaluateLValue(E->getInit(0), LV, Info))
3093 return false;
3094 uint64_t NumElements = CAT->getSize().getZExtValue();
3095 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3096
3097 // Copy the string literal into the array. FIXME: Do this better.
3098 LV.Designator.addIndex(0);
3099 for (uint64_t I = 0; I < NumElements; ++I) {
3100 CCValue Char;
3101 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3102 CAT->getElementType(), LV, Char))
3103 return false;
3104 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3105 Result.getArrayInitializedElt(I)))
3106 return false;
3107 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3108 return false;
3109 }
3110 return true;
3111 }
3112
Richard Smithf3e9e432011-11-07 09:22:26 +00003113 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3114 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003115 LValue Subobject = This;
3116 Subobject.Designator.addIndex(0);
3117 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003118 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003119 I != End; ++I, ++Index) {
3120 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3121 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003122 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003123 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3124 return false;
3125 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003126
3127 if (!Result.hasArrayFiller()) return true;
3128 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003129 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3130 // but sometimes does:
3131 // struct S { constexpr S() : p(&p) {} void *p; };
3132 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003133 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003134 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003135}
3136
Richard Smith027bf112011-11-17 22:56:20 +00003137bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3138 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3139 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003140 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003141
3142 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3143 if (!Result.hasArrayFiller())
3144 return true;
3145
3146 const CXXConstructorDecl *FD = E->getConstructor();
3147 const FunctionDecl *Definition = 0;
3148 FD->getBody(Definition);
3149
Richard Smith357362d2011-12-13 06:39:58 +00003150 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3151 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003152
3153 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3154 // but sometimes does:
3155 // struct S { constexpr S() : p(&p) {} void *p; };
3156 // S s[10];
3157 LValue Subobject = This;
3158 Subobject.Designator.addIndex(0);
3159 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003160 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003161 cast<CXXConstructorDecl>(Definition),
3162 Info, Result.getArrayFiller());
3163}
3164
Richard Smithf3e9e432011-11-07 09:22:26 +00003165//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003166// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003167//
3168// As a GNU extension, we support casting pointers to sufficiently-wide integer
3169// types and back in constant folding. Integer values are thus represented
3170// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003171//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003172
3173namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003174class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003175 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003176 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003177public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003178 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003179 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003180
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003181 bool Success(const llvm::APSInt &SI, const Expr *E) {
3182 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003183 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003184 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003185 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003186 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003187 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003188 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003189 return true;
3190 }
3191
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003192 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003193 assert(E->getType()->isIntegralOrEnumerationType() &&
3194 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003195 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003196 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003197 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003198 Result.getInt().setIsUnsigned(
3199 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003200 return true;
3201 }
3202
3203 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003204 assert(E->getType()->isIntegralOrEnumerationType() &&
3205 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003206 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003207 return true;
3208 }
3209
Ken Dyckdbc01912011-03-11 02:13:43 +00003210 bool Success(CharUnits Size, const Expr *E) {
3211 return Success(Size.getQuantity(), E);
3212 }
3213
Richard Smith0b0a0b62011-10-29 20:57:55 +00003214 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003215 if (V.isLValue()) {
3216 Result = V;
3217 return true;
3218 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003219 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003220 }
Mike Stump11289f42009-09-09 15:08:12 +00003221
Richard Smith4ce706a2011-10-11 21:43:33 +00003222 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3223
Peter Collingbournee9200682011-05-13 03:29:01 +00003224 //===--------------------------------------------------------------------===//
3225 // Visitor Methods
3226 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003227
Chris Lattner7174bf32008-07-12 00:38:25 +00003228 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003229 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003230 }
3231 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003232 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003233 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003234
3235 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3236 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003237 if (CheckReferencedDecl(E, E->getDecl()))
3238 return true;
3239
3240 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003241 }
3242 bool VisitMemberExpr(const MemberExpr *E) {
3243 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003244 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003245 return true;
3246 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003247
3248 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003249 }
3250
Peter Collingbournee9200682011-05-13 03:29:01 +00003251 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003252 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003253 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003254 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003255
Peter Collingbournee9200682011-05-13 03:29:01 +00003256 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003257 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003258
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003259 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003260 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003261 }
Mike Stump11289f42009-09-09 15:08:12 +00003262
Richard Smith4ce706a2011-10-11 21:43:33 +00003263 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003264 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003265 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003266 }
3267
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003268 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003269 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003270 }
3271
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003272 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3273 return Success(E->getValue(), E);
3274 }
3275
John Wiegley6242b6a2011-04-28 00:16:57 +00003276 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3277 return Success(E->getValue(), E);
3278 }
3279
John Wiegleyf9f65842011-04-25 06:54:41 +00003280 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3281 return Success(E->getValue(), E);
3282 }
3283
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003284 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003285 bool VisitUnaryImag(const UnaryOperator *E);
3286
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003287 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003288 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003289
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003290private:
Ken Dyck160146e2010-01-27 17:10:57 +00003291 CharUnits GetAlignOfExpr(const Expr *E);
3292 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003293 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003294 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003295 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003296};
Chris Lattner05706e882008-07-11 18:11:29 +00003297} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003298
Richard Smith11562c52011-10-28 17:51:58 +00003299/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3300/// produce either the integer value or a pointer.
3301///
3302/// GCC has a heinous extension which folds casts between pointer types and
3303/// pointer-sized integral types. We support this by allowing the evaluation of
3304/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3305/// Some simple arithmetic on such values is supported (they are treated much
3306/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003307static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003308 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003309 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003310 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003311}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003312
Richard Smithf57d8cb2011-12-09 22:58:01 +00003313static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003314 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003315 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003316 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003317 if (!Val.isInt()) {
3318 // FIXME: It would be better to produce the diagnostic for casting
3319 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003320 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003321 return false;
3322 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003323 Result = Val.getInt();
3324 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003325}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003326
Richard Smithf57d8cb2011-12-09 22:58:01 +00003327/// Check whether the given declaration can be directly converted to an integral
3328/// rvalue. If not, no diagnostic is produced; there are other things we can
3329/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003330bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003331 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003332 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003333 // Check for signedness/width mismatches between E type and ECD value.
3334 bool SameSign = (ECD->getInitVal().isSigned()
3335 == E->getType()->isSignedIntegerOrEnumerationType());
3336 bool SameWidth = (ECD->getInitVal().getBitWidth()
3337 == Info.Ctx.getIntWidth(E->getType()));
3338 if (SameSign && SameWidth)
3339 return Success(ECD->getInitVal(), E);
3340 else {
3341 // Get rid of mismatch (otherwise Success assertions will fail)
3342 // by computing a new value matching the type of E.
3343 llvm::APSInt Val = ECD->getInitVal();
3344 if (!SameSign)
3345 Val.setIsSigned(!ECD->getInitVal().isSigned());
3346 if (!SameWidth)
3347 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3348 return Success(Val, E);
3349 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003350 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003351 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003352}
3353
Chris Lattner86ee2862008-10-06 06:40:35 +00003354/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3355/// as GCC.
3356static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3357 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003358 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003359 enum gcc_type_class {
3360 no_type_class = -1,
3361 void_type_class, integer_type_class, char_type_class,
3362 enumeral_type_class, boolean_type_class,
3363 pointer_type_class, reference_type_class, offset_type_class,
3364 real_type_class, complex_type_class,
3365 function_type_class, method_type_class,
3366 record_type_class, union_type_class,
3367 array_type_class, string_type_class,
3368 lang_type_class
3369 };
Mike Stump11289f42009-09-09 15:08:12 +00003370
3371 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003372 // ideal, however it is what gcc does.
3373 if (E->getNumArgs() == 0)
3374 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003375
Chris Lattner86ee2862008-10-06 06:40:35 +00003376 QualType ArgTy = E->getArg(0)->getType();
3377 if (ArgTy->isVoidType())
3378 return void_type_class;
3379 else if (ArgTy->isEnumeralType())
3380 return enumeral_type_class;
3381 else if (ArgTy->isBooleanType())
3382 return boolean_type_class;
3383 else if (ArgTy->isCharType())
3384 return string_type_class; // gcc doesn't appear to use char_type_class
3385 else if (ArgTy->isIntegerType())
3386 return integer_type_class;
3387 else if (ArgTy->isPointerType())
3388 return pointer_type_class;
3389 else if (ArgTy->isReferenceType())
3390 return reference_type_class;
3391 else if (ArgTy->isRealType())
3392 return real_type_class;
3393 else if (ArgTy->isComplexType())
3394 return complex_type_class;
3395 else if (ArgTy->isFunctionType())
3396 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003397 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003398 return record_type_class;
3399 else if (ArgTy->isUnionType())
3400 return union_type_class;
3401 else if (ArgTy->isArrayType())
3402 return array_type_class;
3403 else if (ArgTy->isUnionType())
3404 return union_type_class;
3405 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003406 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003407 return -1;
3408}
3409
John McCall95007602010-05-10 23:27:23 +00003410/// Retrieves the "underlying object type" of the given expression,
3411/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003412QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3413 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3414 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003415 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003416 } else if (const Expr *E = B.get<const Expr*>()) {
3417 if (isa<CompoundLiteralExpr>(E))
3418 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003419 }
3420
3421 return QualType();
3422}
3423
Peter Collingbournee9200682011-05-13 03:29:01 +00003424bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003425 // TODO: Perhaps we should let LLVM lower this?
3426 LValue Base;
3427 if (!EvaluatePointer(E->getArg(0), Base, Info))
3428 return false;
3429
3430 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003431 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003432
Richard Smithce40ad62011-11-12 22:28:03 +00003433 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003434 if (T.isNull() ||
3435 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003436 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003437 T->isVariablyModifiedType() ||
3438 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003439 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003440
3441 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3442 CharUnits Offset = Base.getLValueOffset();
3443
3444 if (!Offset.isNegative() && Offset <= Size)
3445 Size -= Offset;
3446 else
3447 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003448 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003449}
3450
Peter Collingbournee9200682011-05-13 03:29:01 +00003451bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003452 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003453 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003454 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003455
3456 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003457 if (TryEvaluateBuiltinObjectSize(E))
3458 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003459
Eric Christopher99469702010-01-19 22:58:35 +00003460 // If evaluating the argument has side-effects we can't determine
3461 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003462 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003463 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003464 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003465 return Success(0, E);
3466 }
Mike Stump876387b2009-10-27 22:09:17 +00003467
Richard Smithf57d8cb2011-12-09 22:58:01 +00003468 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003469 }
3470
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003471 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003472 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003473
Richard Smith10c7c902011-12-09 02:04:48 +00003474 case Builtin::BI__builtin_constant_p: {
3475 const Expr *Arg = E->getArg(0);
3476 QualType ArgType = Arg->getType();
3477 // __builtin_constant_p always has one operand. The rules which gcc follows
3478 // are not precisely documented, but are as follows:
3479 //
3480 // - If the operand is of integral, floating, complex or enumeration type,
3481 // and can be folded to a known value of that type, it returns 1.
3482 // - If the operand and can be folded to a pointer to the first character
3483 // of a string literal (or such a pointer cast to an integral type), it
3484 // returns 1.
3485 //
3486 // Otherwise, it returns 0.
3487 //
3488 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3489 // its support for this does not currently work.
3490 int IsConstant = 0;
3491 if (ArgType->isIntegralOrEnumerationType()) {
3492 // Note, a pointer cast to an integral type is only a constant if it is
3493 // a pointer to the first character of a string literal.
3494 Expr::EvalResult Result;
3495 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3496 APValue &V = Result.Val;
3497 if (V.getKind() == APValue::LValue) {
3498 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3499 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3500 } else {
3501 IsConstant = 1;
3502 }
3503 }
3504 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3505 IsConstant = Arg->isEvaluatable(Info.Ctx);
3506 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3507 LValue LV;
3508 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3509 // during the check.
3510 Expr::EvalStatus Status;
3511 EvalInfo SubInfo(Info.Ctx, Status);
3512 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3513 : EvaluatePointer(Arg, LV, SubInfo)) &&
3514 !Status.HasSideEffects)
3515 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3516 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3517 }
3518
3519 return Success(IsConstant, E);
3520 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003521 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003522 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003523 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003524 return Success(Operand, E);
3525 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003526
3527 case Builtin::BI__builtin_expect:
3528 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003529
3530 case Builtin::BIstrlen:
3531 case Builtin::BI__builtin_strlen:
3532 // As an extension, we support strlen() and __builtin_strlen() as constant
3533 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003534 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003535 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3536 // The string literal may have embedded null characters. Find the first
3537 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003538 StringRef Str = S->getString();
3539 StringRef::size_type Pos = Str.find(0);
3540 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003541 Str = Str.substr(0, Pos);
3542
3543 return Success(Str.size(), E);
3544 }
3545
Richard Smithf57d8cb2011-12-09 22:58:01 +00003546 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003547
3548 case Builtin::BI__atomic_is_lock_free: {
3549 APSInt SizeVal;
3550 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3551 return false;
3552
3553 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3554 // of two less than the maximum inline atomic width, we know it is
3555 // lock-free. If the size isn't a power of two, or greater than the
3556 // maximum alignment where we promote atomics, we know it is not lock-free
3557 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3558 // the answer can only be determined at runtime; for example, 16-byte
3559 // atomics have lock-free implementations on some, but not all,
3560 // x86-64 processors.
3561
3562 // Check power-of-two.
3563 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3564 if (!Size.isPowerOfTwo())
3565#if 0
3566 // FIXME: Suppress this folding until the ABI for the promotion width
3567 // settles.
3568 return Success(0, E);
3569#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003570 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003571#endif
3572
3573#if 0
3574 // Check against promotion width.
3575 // FIXME: Suppress this folding until the ABI for the promotion width
3576 // settles.
3577 unsigned PromoteWidthBits =
3578 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3579 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3580 return Success(0, E);
3581#endif
3582
3583 // Check against inlining width.
3584 unsigned InlineWidthBits =
3585 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3586 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3587 return Success(1, E);
3588
Richard Smithf57d8cb2011-12-09 22:58:01 +00003589 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003590 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003591 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003592}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003593
Richard Smith8b3497e2011-10-31 01:37:14 +00003594static bool HasSameBase(const LValue &A, const LValue &B) {
3595 if (!A.getLValueBase())
3596 return !B.getLValueBase();
3597 if (!B.getLValueBase())
3598 return false;
3599
Richard Smithce40ad62011-11-12 22:28:03 +00003600 if (A.getLValueBase().getOpaqueValue() !=
3601 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003602 const Decl *ADecl = GetLValueBaseDecl(A);
3603 if (!ADecl)
3604 return false;
3605 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003606 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003607 return false;
3608 }
3609
3610 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003611 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003612}
3613
Chris Lattnere13042c2008-07-11 19:10:17 +00003614bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003615 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003616 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003617
John McCalle3027922010-08-25 11:45:40 +00003618 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003619 VisitIgnoredValue(E->getLHS());
3620 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003621 }
3622
3623 if (E->isLogicalOp()) {
3624 // These need to be handled specially because the operands aren't
3625 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003626 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003627
Richard Smith11562c52011-10-28 17:51:58 +00003628 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003629 // We were able to evaluate the LHS, see if we can get away with not
3630 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003631 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003632 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003633
Richard Smith11562c52011-10-28 17:51:58 +00003634 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003635 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003636 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003637 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003638 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003639 }
3640 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003641 // FIXME: If both evaluations fail, we should produce the diagnostic from
3642 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3643 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003644 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003645 // We can't evaluate the LHS; however, sometimes the result
3646 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003647 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003648 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003649 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003650 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003651
3652 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003653 }
3654 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003655 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003656
Eli Friedman5a332ea2008-11-13 06:09:17 +00003657 return false;
3658 }
3659
Anders Carlssonacc79812008-11-16 07:17:21 +00003660 QualType LHSTy = E->getLHS()->getType();
3661 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003662
3663 if (LHSTy->isAnyComplexType()) {
3664 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003665 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003666
3667 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3668 return false;
3669
3670 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3671 return false;
3672
3673 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003674 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003675 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003676 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003677 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3678
John McCalle3027922010-08-25 11:45:40 +00003679 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003680 return Success((CR_r == APFloat::cmpEqual &&
3681 CR_i == APFloat::cmpEqual), E);
3682 else {
John McCalle3027922010-08-25 11:45:40 +00003683 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003684 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003685 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003686 CR_r == APFloat::cmpLessThan ||
3687 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003688 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003689 CR_i == APFloat::cmpLessThan ||
3690 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003691 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003692 } else {
John McCalle3027922010-08-25 11:45:40 +00003693 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003694 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3695 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3696 else {
John McCalle3027922010-08-25 11:45:40 +00003697 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003698 "Invalid compex comparison.");
3699 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3700 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3701 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003702 }
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Anders Carlssonacc79812008-11-16 07:17:21 +00003705 if (LHSTy->isRealFloatingType() &&
3706 RHSTy->isRealFloatingType()) {
3707 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003708
Anders Carlssonacc79812008-11-16 07:17:21 +00003709 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3710 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003711
Anders Carlssonacc79812008-11-16 07:17:21 +00003712 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3713 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003714
Anders Carlssonacc79812008-11-16 07:17:21 +00003715 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003716
Anders Carlssonacc79812008-11-16 07:17:21 +00003717 switch (E->getOpcode()) {
3718 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003719 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003720 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003721 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003722 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003723 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003724 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003725 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003726 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003727 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003728 E);
John McCalle3027922010-08-25 11:45:40 +00003729 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003730 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003731 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003732 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003733 || CR == APFloat::cmpLessThan
3734 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003735 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003736 }
Mike Stump11289f42009-09-09 15:08:12 +00003737
Eli Friedmana38da572009-04-28 19:17:36 +00003738 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003739 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003740 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003741 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3742 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003743
John McCall45d55e42010-05-07 21:00:08 +00003744 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003745 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3746 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003747
Richard Smith8b3497e2011-10-31 01:37:14 +00003748 // Reject differing bases from the normal codepath; we special-case
3749 // comparisons to null.
3750 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003751 // Inequalities and subtractions between unrelated pointers have
3752 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003753 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003754 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003755 // A constant address may compare equal to the address of a symbol.
3756 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003757 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003758 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3759 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003760 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003761 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003762 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003763 // distinct. However, we do know that the address of a literal will be
3764 // non-null.
3765 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3766 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003767 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003768 // We can't tell whether weak symbols will end up pointing to the same
3769 // object.
3770 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003771 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003772 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003773 // (Note that clang defaults to -fmerge-all-constants, which can
3774 // lead to inconsistent results for comparisons involving the address
3775 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003776 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003777 }
Eli Friedman64004332009-03-23 04:38:34 +00003778
Richard Smithf3e9e432011-11-07 09:22:26 +00003779 // FIXME: Implement the C++11 restrictions:
3780 // - Pointer subtractions must be on elements of the same array.
3781 // - Pointer comparisons must be between members with the same access.
3782
John McCalle3027922010-08-25 11:45:40 +00003783 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003784 QualType Type = E->getLHS()->getType();
3785 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003786
Richard Smithd62306a2011-11-10 06:34:14 +00003787 CharUnits ElementSize;
3788 if (!HandleSizeof(Info, ElementType, ElementSize))
3789 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003790
Richard Smithd62306a2011-11-10 06:34:14 +00003791 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003792 RHSValue.getLValueOffset();
3793 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003794 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003795
3796 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3797 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3798 switch (E->getOpcode()) {
3799 default: llvm_unreachable("missing comparison operator");
3800 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3801 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3802 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3803 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3804 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3805 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003806 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003807 }
3808 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003809 if (!LHSTy->isIntegralOrEnumerationType() ||
3810 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003811 // We can't continue from here for non-integral types.
3812 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003813 }
3814
Anders Carlsson9c181652008-07-08 14:35:21 +00003815 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003816 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003817 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003818 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003819
Richard Smith11562c52011-10-28 17:51:58 +00003820 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003821 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003822 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003823
3824 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003825 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003826 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3827 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003828 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003829 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003830 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003831 LHSVal.getLValueOffset() -= AdditionalOffset;
3832 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003833 return true;
3834 }
3835
3836 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003837 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003838 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003839 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3840 LHSVal.getInt().getZExtValue());
3841 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003842 return true;
3843 }
3844
3845 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003846 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003847 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003848
Richard Smith11562c52011-10-28 17:51:58 +00003849 APSInt &LHS = LHSVal.getInt();
3850 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003851
Anders Carlsson9c181652008-07-08 14:35:21 +00003852 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003853 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003854 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003855 case BO_Mul: return Success(LHS * RHS, E);
3856 case BO_Add: return Success(LHS + RHS, E);
3857 case BO_Sub: return Success(LHS - RHS, E);
3858 case BO_And: return Success(LHS & RHS, E);
3859 case BO_Xor: return Success(LHS ^ RHS, E);
3860 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003861 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003862 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003863 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003864 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003865 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003866 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003867 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003868 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003869 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003870 // During constant-folding, a negative shift is an opposite shift.
3871 if (RHS.isSigned() && RHS.isNegative()) {
3872 RHS = -RHS;
3873 goto shift_right;
3874 }
3875
3876 shift_left:
3877 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003878 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3879 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003880 }
John McCalle3027922010-08-25 11:45:40 +00003881 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003882 // During constant-folding, a negative shift is an opposite shift.
3883 if (RHS.isSigned() && RHS.isNegative()) {
3884 RHS = -RHS;
3885 goto shift_left;
3886 }
3887
3888 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003889 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003890 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3891 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003892 }
Mike Stump11289f42009-09-09 15:08:12 +00003893
Richard Smith11562c52011-10-28 17:51:58 +00003894 case BO_LT: return Success(LHS < RHS, E);
3895 case BO_GT: return Success(LHS > RHS, E);
3896 case BO_LE: return Success(LHS <= RHS, E);
3897 case BO_GE: return Success(LHS >= RHS, E);
3898 case BO_EQ: return Success(LHS == RHS, E);
3899 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003900 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003901}
3902
Ken Dyck160146e2010-01-27 17:10:57 +00003903CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003904 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3905 // the result is the size of the referenced type."
3906 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3907 // result shall be the alignment of the referenced type."
3908 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3909 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003910
3911 // __alignof is defined to return the preferred alignment.
3912 return Info.Ctx.toCharUnitsFromBits(
3913 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003914}
3915
Ken Dyck160146e2010-01-27 17:10:57 +00003916CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003917 E = E->IgnoreParens();
3918
3919 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003920 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003921 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003922 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3923 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003924
Chris Lattner68061312009-01-24 21:53:27 +00003925 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003926 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3927 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003928
Chris Lattner24aeeab2009-01-24 21:09:06 +00003929 return GetAlignOfType(E->getType());
3930}
3931
3932
Peter Collingbournee190dee2011-03-11 19:24:49 +00003933/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3934/// a result as the expression's type.
3935bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3936 const UnaryExprOrTypeTraitExpr *E) {
3937 switch(E->getKind()) {
3938 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003939 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003940 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003941 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003942 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003943 }
Eli Friedman64004332009-03-23 04:38:34 +00003944
Peter Collingbournee190dee2011-03-11 19:24:49 +00003945 case UETT_VecStep: {
3946 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003947
Peter Collingbournee190dee2011-03-11 19:24:49 +00003948 if (Ty->isVectorType()) {
3949 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003950
Peter Collingbournee190dee2011-03-11 19:24:49 +00003951 // The vec_step built-in functions that take a 3-component
3952 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3953 if (n == 3)
3954 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003955
Peter Collingbournee190dee2011-03-11 19:24:49 +00003956 return Success(n, E);
3957 } else
3958 return Success(1, E);
3959 }
3960
3961 case UETT_SizeOf: {
3962 QualType SrcTy = E->getTypeOfArgument();
3963 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3964 // the result is the size of the referenced type."
3965 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3966 // result shall be the alignment of the referenced type."
3967 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3968 SrcTy = Ref->getPointeeType();
3969
Richard Smithd62306a2011-11-10 06:34:14 +00003970 CharUnits Sizeof;
3971 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003972 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003973 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003974 }
3975 }
3976
3977 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003978 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003979}
3980
Peter Collingbournee9200682011-05-13 03:29:01 +00003981bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003982 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003983 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003984 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003985 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003986 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003987 for (unsigned i = 0; i != n; ++i) {
3988 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3989 switch (ON.getKind()) {
3990 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003991 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003992 APSInt IdxResult;
3993 if (!EvaluateInteger(Idx, IdxResult, Info))
3994 return false;
3995 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3996 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003997 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003998 CurrentType = AT->getElementType();
3999 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4000 Result += IdxResult.getSExtValue() * ElementSize;
4001 break;
4002 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004003
Douglas Gregor882211c2010-04-28 22:16:22 +00004004 case OffsetOfExpr::OffsetOfNode::Field: {
4005 FieldDecl *MemberDecl = ON.getField();
4006 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004007 if (!RT)
4008 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004009 RecordDecl *RD = RT->getDecl();
4010 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004011 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004012 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004013 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004014 CurrentType = MemberDecl->getType().getNonReferenceType();
4015 break;
4016 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004017
Douglas Gregor882211c2010-04-28 22:16:22 +00004018 case OffsetOfExpr::OffsetOfNode::Identifier:
4019 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004020 return Error(OOE);
4021
Douglas Gregord1702062010-04-29 00:18:15 +00004022 case OffsetOfExpr::OffsetOfNode::Base: {
4023 CXXBaseSpecifier *BaseSpec = ON.getBase();
4024 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004025 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004026
4027 // Find the layout of the class whose base we are looking into.
4028 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 if (!RT)
4030 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004031 RecordDecl *RD = RT->getDecl();
4032 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4033
4034 // Find the base class itself.
4035 CurrentType = BaseSpec->getType();
4036 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4037 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004038 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004039
4040 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004041 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004042 break;
4043 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004044 }
4045 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004046 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004047}
4048
Chris Lattnere13042c2008-07-11 19:10:17 +00004049bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004050 switch (E->getOpcode()) {
4051 default:
4052 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4053 // See C99 6.6p3.
4054 return Error(E);
4055 case UO_Extension:
4056 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4057 // If so, we could clear the diagnostic ID.
4058 return Visit(E->getSubExpr());
4059 case UO_Plus:
4060 // The result is just the value.
4061 return Visit(E->getSubExpr());
4062 case UO_Minus: {
4063 if (!Visit(E->getSubExpr()))
4064 return false;
4065 if (!Result.isInt()) return Error(E);
4066 return Success(-Result.getInt(), E);
4067 }
4068 case UO_Not: {
4069 if (!Visit(E->getSubExpr()))
4070 return false;
4071 if (!Result.isInt()) return Error(E);
4072 return Success(~Result.getInt(), E);
4073 }
4074 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004075 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004076 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004077 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004078 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004079 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004080 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004081}
Mike Stump11289f42009-09-09 15:08:12 +00004082
Chris Lattner477c4be2008-07-12 01:15:53 +00004083/// HandleCast - This is used to evaluate implicit or explicit casts where the
4084/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004085bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4086 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004087 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004088 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004089
Eli Friedmanc757de22011-03-25 00:43:55 +00004090 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004091 case CK_BaseToDerived:
4092 case CK_DerivedToBase:
4093 case CK_UncheckedDerivedToBase:
4094 case CK_Dynamic:
4095 case CK_ToUnion:
4096 case CK_ArrayToPointerDecay:
4097 case CK_FunctionToPointerDecay:
4098 case CK_NullToPointer:
4099 case CK_NullToMemberPointer:
4100 case CK_BaseToDerivedMemberPointer:
4101 case CK_DerivedToBaseMemberPointer:
4102 case CK_ConstructorConversion:
4103 case CK_IntegralToPointer:
4104 case CK_ToVoid:
4105 case CK_VectorSplat:
4106 case CK_IntegralToFloating:
4107 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004108 case CK_CPointerToObjCPointerCast:
4109 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004110 case CK_AnyPointerToBlockPointerCast:
4111 case CK_ObjCObjectLValueCast:
4112 case CK_FloatingRealToComplex:
4113 case CK_FloatingComplexToReal:
4114 case CK_FloatingComplexCast:
4115 case CK_FloatingComplexToIntegralComplex:
4116 case CK_IntegralRealToComplex:
4117 case CK_IntegralComplexCast:
4118 case CK_IntegralComplexToFloatingComplex:
4119 llvm_unreachable("invalid cast kind for integral value");
4120
Eli Friedman9faf2f92011-03-25 19:07:11 +00004121 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004122 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004123 case CK_LValueBitCast:
4124 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004125 case CK_ARCProduceObject:
4126 case CK_ARCConsumeObject:
4127 case CK_ARCReclaimReturnedObject:
4128 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004129 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004130
4131 case CK_LValueToRValue:
4132 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004133 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004134
4135 case CK_MemberPointerToBoolean:
4136 case CK_PointerToBoolean:
4137 case CK_IntegralToBoolean:
4138 case CK_FloatingToBoolean:
4139 case CK_FloatingComplexToBoolean:
4140 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004141 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004142 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004143 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004144 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004145 }
4146
Eli Friedmanc757de22011-03-25 00:43:55 +00004147 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004148 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004149 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004150
Eli Friedman742421e2009-02-20 01:15:07 +00004151 if (!Result.isInt()) {
4152 // Only allow casts of lvalues if they are lossless.
4153 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4154 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004155
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004156 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004157 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004158 }
Mike Stump11289f42009-09-09 15:08:12 +00004159
Eli Friedmanc757de22011-03-25 00:43:55 +00004160 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4162
John McCall45d55e42010-05-07 21:00:08 +00004163 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004164 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004165 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004166
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004167 if (LV.getLValueBase()) {
4168 // Only allow based lvalue casts if they are lossless.
4169 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004170 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004171
Richard Smithcf74da72011-11-16 07:18:12 +00004172 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004173 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004174 return true;
4175 }
4176
Ken Dyck02990832010-01-15 12:37:54 +00004177 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4178 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004179 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004180 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004181
Eli Friedmanc757de22011-03-25 00:43:55 +00004182 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004183 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004184 if (!EvaluateComplex(SubExpr, C, Info))
4185 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004186 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004187 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004188
Eli Friedmanc757de22011-03-25 00:43:55 +00004189 case CK_FloatingToIntegral: {
4190 APFloat F(0.0);
4191 if (!EvaluateFloat(SubExpr, F, Info))
4192 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004193
Richard Smith357362d2011-12-13 06:39:58 +00004194 APSInt Value;
4195 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4196 return false;
4197 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004198 }
4199 }
Mike Stump11289f42009-09-09 15:08:12 +00004200
Eli Friedmanc757de22011-03-25 00:43:55 +00004201 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004202 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004203}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004204
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004205bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4206 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004207 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004208 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4209 return false;
4210 if (!LV.isComplexInt())
4211 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004212 return Success(LV.getComplexIntReal(), E);
4213 }
4214
4215 return Visit(E->getSubExpr());
4216}
4217
Eli Friedman4e7a2412009-02-27 04:45:43 +00004218bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004219 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004220 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004221 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4222 return false;
4223 if (!LV.isComplexInt())
4224 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004225 return Success(LV.getComplexIntImag(), E);
4226 }
4227
Richard Smith4a678122011-10-24 18:44:57 +00004228 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004229 return Success(0, E);
4230}
4231
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004232bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4233 return Success(E->getPackLength(), E);
4234}
4235
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004236bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4237 return Success(E->getValue(), E);
4238}
4239
Chris Lattner05706e882008-07-11 18:11:29 +00004240//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004241// Float Evaluation
4242//===----------------------------------------------------------------------===//
4243
4244namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004245class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004246 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004247 APFloat &Result;
4248public:
4249 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004250 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004251
Richard Smith0b0a0b62011-10-29 20:57:55 +00004252 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004253 Result = V.getFloat();
4254 return true;
4255 }
Eli Friedman24c01542008-08-22 00:06:13 +00004256
Richard Smith4ce706a2011-10-11 21:43:33 +00004257 bool ValueInitialization(const Expr *E) {
4258 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4259 return true;
4260 }
4261
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004262 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004263
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004264 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004265 bool VisitBinaryOperator(const BinaryOperator *E);
4266 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004267 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004268
John McCallb1fb0d32010-05-07 22:08:54 +00004269 bool VisitUnaryReal(const UnaryOperator *E);
4270 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004271
John McCallb1fb0d32010-05-07 22:08:54 +00004272 // FIXME: Missing: array subscript of vector, member of vector,
4273 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004274};
4275} // end anonymous namespace
4276
4277static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004278 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004279 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004280}
4281
Jay Foad39c79802011-01-12 09:06:06 +00004282static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004283 QualType ResultTy,
4284 const Expr *Arg,
4285 bool SNaN,
4286 llvm::APFloat &Result) {
4287 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4288 if (!S) return false;
4289
4290 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4291
4292 llvm::APInt fill;
4293
4294 // Treat empty strings as if they were zero.
4295 if (S->getString().empty())
4296 fill = llvm::APInt(32, 0);
4297 else if (S->getString().getAsInteger(0, fill))
4298 return false;
4299
4300 if (SNaN)
4301 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4302 else
4303 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4304 return true;
4305}
4306
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004307bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004308 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004309 default:
4310 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4311
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004312 case Builtin::BI__builtin_huge_val:
4313 case Builtin::BI__builtin_huge_valf:
4314 case Builtin::BI__builtin_huge_vall:
4315 case Builtin::BI__builtin_inf:
4316 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004317 case Builtin::BI__builtin_infl: {
4318 const llvm::fltSemantics &Sem =
4319 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004320 Result = llvm::APFloat::getInf(Sem);
4321 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
John McCall16291492010-02-28 13:00:19 +00004324 case Builtin::BI__builtin_nans:
4325 case Builtin::BI__builtin_nansf:
4326 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004327 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4328 true, Result))
4329 return Error(E);
4330 return true;
John McCall16291492010-02-28 13:00:19 +00004331
Chris Lattner0b7282e2008-10-06 06:31:58 +00004332 case Builtin::BI__builtin_nan:
4333 case Builtin::BI__builtin_nanf:
4334 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004335 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004336 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004337 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4338 false, Result))
4339 return Error(E);
4340 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004341
4342 case Builtin::BI__builtin_fabs:
4343 case Builtin::BI__builtin_fabsf:
4344 case Builtin::BI__builtin_fabsl:
4345 if (!EvaluateFloat(E->getArg(0), Result, Info))
4346 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004347
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004348 if (Result.isNegative())
4349 Result.changeSign();
4350 return true;
4351
Mike Stump11289f42009-09-09 15:08:12 +00004352 case Builtin::BI__builtin_copysign:
4353 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004354 case Builtin::BI__builtin_copysignl: {
4355 APFloat RHS(0.);
4356 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4357 !EvaluateFloat(E->getArg(1), RHS, Info))
4358 return false;
4359 Result.copySign(RHS);
4360 return true;
4361 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004362 }
4363}
4364
John McCallb1fb0d32010-05-07 22:08:54 +00004365bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004366 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4367 ComplexValue CV;
4368 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4369 return false;
4370 Result = CV.FloatReal;
4371 return true;
4372 }
4373
4374 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004375}
4376
4377bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004378 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4379 ComplexValue CV;
4380 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4381 return false;
4382 Result = CV.FloatImag;
4383 return true;
4384 }
4385
Richard Smith4a678122011-10-24 18:44:57 +00004386 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004387 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4388 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004389 return true;
4390}
4391
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004392bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004393 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004394 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004395 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004396 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004397 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004398 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4399 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004400 Result.changeSign();
4401 return true;
4402 }
4403}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004404
Eli Friedman24c01542008-08-22 00:06:13 +00004405bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004406 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4407 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004408
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004409 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004410 if (!EvaluateFloat(E->getLHS(), Result, Info))
4411 return false;
4412 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4413 return false;
4414
4415 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004417 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004418 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4419 return true;
John McCalle3027922010-08-25 11:45:40 +00004420 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004421 Result.add(RHS, APFloat::rmNearestTiesToEven);
4422 return true;
John McCalle3027922010-08-25 11:45:40 +00004423 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004424 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4425 return true;
John McCalle3027922010-08-25 11:45:40 +00004426 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004427 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4428 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004429 }
4430}
4431
4432bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4433 Result = E->getValue();
4434 return true;
4435}
4436
Peter Collingbournee9200682011-05-13 03:29:01 +00004437bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4438 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004439
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004440 switch (E->getCastKind()) {
4441 default:
Richard Smith11562c52011-10-28 17:51:58 +00004442 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004443
4444 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004445 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004446 return EvaluateInteger(SubExpr, IntResult, Info) &&
4447 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4448 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004449 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004450
4451 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004452 if (!Visit(SubExpr))
4453 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004454 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4455 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004456 }
John McCalld7646252010-11-14 08:17:51 +00004457
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004458 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004459 ComplexValue V;
4460 if (!EvaluateComplex(SubExpr, V, Info))
4461 return false;
4462 Result = V.getComplexFloatReal();
4463 return true;
4464 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004465 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004466
Richard Smithf57d8cb2011-12-09 22:58:01 +00004467 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004468}
4469
Eli Friedman24c01542008-08-22 00:06:13 +00004470//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004471// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004472//===----------------------------------------------------------------------===//
4473
4474namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004475class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004476 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004477 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004478
Anders Carlsson537969c2008-11-16 20:27:53 +00004479public:
John McCall93d91dc2010-05-07 17:22:02 +00004480 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004481 : ExprEvaluatorBaseTy(info), Result(Result) {}
4482
Richard Smith0b0a0b62011-10-29 20:57:55 +00004483 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004484 Result.setFrom(V);
4485 return true;
4486 }
Mike Stump11289f42009-09-09 15:08:12 +00004487
Anders Carlsson537969c2008-11-16 20:27:53 +00004488 //===--------------------------------------------------------------------===//
4489 // Visitor Methods
4490 //===--------------------------------------------------------------------===//
4491
Peter Collingbournee9200682011-05-13 03:29:01 +00004492 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004493
Peter Collingbournee9200682011-05-13 03:29:01 +00004494 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004495
John McCall93d91dc2010-05-07 17:22:02 +00004496 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004497 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004498 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004499};
4500} // end anonymous namespace
4501
John McCall93d91dc2010-05-07 17:22:02 +00004502static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4503 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004504 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004505 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004506}
4507
Peter Collingbournee9200682011-05-13 03:29:01 +00004508bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4509 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004510
4511 if (SubExpr->getType()->isRealFloatingType()) {
4512 Result.makeComplexFloat();
4513 APFloat &Imag = Result.FloatImag;
4514 if (!EvaluateFloat(SubExpr, Imag, Info))
4515 return false;
4516
4517 Result.FloatReal = APFloat(Imag.getSemantics());
4518 return true;
4519 } else {
4520 assert(SubExpr->getType()->isIntegerType() &&
4521 "Unexpected imaginary literal.");
4522
4523 Result.makeComplexInt();
4524 APSInt &Imag = Result.IntImag;
4525 if (!EvaluateInteger(SubExpr, Imag, Info))
4526 return false;
4527
4528 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4529 return true;
4530 }
4531}
4532
Peter Collingbournee9200682011-05-13 03:29:01 +00004533bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004534
John McCallfcef3cf2010-12-14 17:51:41 +00004535 switch (E->getCastKind()) {
4536 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004537 case CK_BaseToDerived:
4538 case CK_DerivedToBase:
4539 case CK_UncheckedDerivedToBase:
4540 case CK_Dynamic:
4541 case CK_ToUnion:
4542 case CK_ArrayToPointerDecay:
4543 case CK_FunctionToPointerDecay:
4544 case CK_NullToPointer:
4545 case CK_NullToMemberPointer:
4546 case CK_BaseToDerivedMemberPointer:
4547 case CK_DerivedToBaseMemberPointer:
4548 case CK_MemberPointerToBoolean:
4549 case CK_ConstructorConversion:
4550 case CK_IntegralToPointer:
4551 case CK_PointerToIntegral:
4552 case CK_PointerToBoolean:
4553 case CK_ToVoid:
4554 case CK_VectorSplat:
4555 case CK_IntegralCast:
4556 case CK_IntegralToBoolean:
4557 case CK_IntegralToFloating:
4558 case CK_FloatingToIntegral:
4559 case CK_FloatingToBoolean:
4560 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004561 case CK_CPointerToObjCPointerCast:
4562 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004563 case CK_AnyPointerToBlockPointerCast:
4564 case CK_ObjCObjectLValueCast:
4565 case CK_FloatingComplexToReal:
4566 case CK_FloatingComplexToBoolean:
4567 case CK_IntegralComplexToReal:
4568 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004569 case CK_ARCProduceObject:
4570 case CK_ARCConsumeObject:
4571 case CK_ARCReclaimReturnedObject:
4572 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004573 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004574
John McCallfcef3cf2010-12-14 17:51:41 +00004575 case CK_LValueToRValue:
4576 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004577 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004578
4579 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004580 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004581 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004582 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004583
4584 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004585 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004586 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004587 return false;
4588
John McCallfcef3cf2010-12-14 17:51:41 +00004589 Result.makeComplexFloat();
4590 Result.FloatImag = APFloat(Real.getSemantics());
4591 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004592 }
4593
John McCallfcef3cf2010-12-14 17:51:41 +00004594 case CK_FloatingComplexCast: {
4595 if (!Visit(E->getSubExpr()))
4596 return false;
4597
4598 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4599 QualType From
4600 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4601
Richard Smith357362d2011-12-13 06:39:58 +00004602 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4603 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004604 }
4605
4606 case CK_FloatingComplexToIntegralComplex: {
4607 if (!Visit(E->getSubExpr()))
4608 return false;
4609
4610 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4611 QualType From
4612 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4613 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004614 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4615 To, Result.IntReal) &&
4616 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4617 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004618 }
4619
4620 case CK_IntegralRealToComplex: {
4621 APSInt &Real = Result.IntReal;
4622 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4623 return false;
4624
4625 Result.makeComplexInt();
4626 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4627 return true;
4628 }
4629
4630 case CK_IntegralComplexCast: {
4631 if (!Visit(E->getSubExpr()))
4632 return false;
4633
4634 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4635 QualType From
4636 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4637
4638 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4639 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4640 return true;
4641 }
4642
4643 case CK_IntegralComplexToFloatingComplex: {
4644 if (!Visit(E->getSubExpr()))
4645 return false;
4646
4647 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4648 QualType From
4649 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4650 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004651 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4652 To, Result.FloatReal) &&
4653 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4654 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004655 }
4656 }
4657
4658 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004659 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004660}
4661
John McCall93d91dc2010-05-07 17:22:02 +00004662bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004663 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004664 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4665
John McCall93d91dc2010-05-07 17:22:02 +00004666 if (!Visit(E->getLHS()))
4667 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004668
John McCall93d91dc2010-05-07 17:22:02 +00004669 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004670 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004671 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004672
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004673 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4674 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004675 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004676 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004677 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004678 if (Result.isComplexFloat()) {
4679 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4680 APFloat::rmNearestTiesToEven);
4681 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4682 APFloat::rmNearestTiesToEven);
4683 } else {
4684 Result.getComplexIntReal() += RHS.getComplexIntReal();
4685 Result.getComplexIntImag() += RHS.getComplexIntImag();
4686 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004687 break;
John McCalle3027922010-08-25 11:45:40 +00004688 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004689 if (Result.isComplexFloat()) {
4690 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4691 APFloat::rmNearestTiesToEven);
4692 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4693 APFloat::rmNearestTiesToEven);
4694 } else {
4695 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4696 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4697 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004698 break;
John McCalle3027922010-08-25 11:45:40 +00004699 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004700 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004701 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004702 APFloat &LHS_r = LHS.getComplexFloatReal();
4703 APFloat &LHS_i = LHS.getComplexFloatImag();
4704 APFloat &RHS_r = RHS.getComplexFloatReal();
4705 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004706
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004707 APFloat Tmp = LHS_r;
4708 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4709 Result.getComplexFloatReal() = Tmp;
4710 Tmp = LHS_i;
4711 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4712 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4713
4714 Tmp = LHS_r;
4715 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4716 Result.getComplexFloatImag() = Tmp;
4717 Tmp = LHS_i;
4718 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4719 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4720 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004721 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004722 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004723 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4724 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004725 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004726 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4727 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4728 }
4729 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004730 case BO_Div:
4731 if (Result.isComplexFloat()) {
4732 ComplexValue LHS = Result;
4733 APFloat &LHS_r = LHS.getComplexFloatReal();
4734 APFloat &LHS_i = LHS.getComplexFloatImag();
4735 APFloat &RHS_r = RHS.getComplexFloatReal();
4736 APFloat &RHS_i = RHS.getComplexFloatImag();
4737 APFloat &Res_r = Result.getComplexFloatReal();
4738 APFloat &Res_i = Result.getComplexFloatImag();
4739
4740 APFloat Den = RHS_r;
4741 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4742 APFloat Tmp = RHS_i;
4743 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4744 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4745
4746 Res_r = LHS_r;
4747 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4748 Tmp = LHS_i;
4749 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4750 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4751 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4752
4753 Res_i = LHS_i;
4754 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4755 Tmp = LHS_r;
4756 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4757 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4758 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4759 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004760 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4761 return Error(E, diag::note_expr_divide_by_zero);
4762
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004763 ComplexValue LHS = Result;
4764 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4765 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4766 Result.getComplexIntReal() =
4767 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4768 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4769 Result.getComplexIntImag() =
4770 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4771 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4772 }
4773 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004774 }
4775
John McCall93d91dc2010-05-07 17:22:02 +00004776 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004777}
4778
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004779bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4780 // Get the operand value into 'Result'.
4781 if (!Visit(E->getSubExpr()))
4782 return false;
4783
4784 switch (E->getOpcode()) {
4785 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004786 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004787 case UO_Extension:
4788 return true;
4789 case UO_Plus:
4790 // The result is always just the subexpr.
4791 return true;
4792 case UO_Minus:
4793 if (Result.isComplexFloat()) {
4794 Result.getComplexFloatReal().changeSign();
4795 Result.getComplexFloatImag().changeSign();
4796 }
4797 else {
4798 Result.getComplexIntReal() = -Result.getComplexIntReal();
4799 Result.getComplexIntImag() = -Result.getComplexIntImag();
4800 }
4801 return true;
4802 case UO_Not:
4803 if (Result.isComplexFloat())
4804 Result.getComplexFloatImag().changeSign();
4805 else
4806 Result.getComplexIntImag() = -Result.getComplexIntImag();
4807 return true;
4808 }
4809}
4810
Anders Carlsson537969c2008-11-16 20:27:53 +00004811//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004812// Void expression evaluation, primarily for a cast to void on the LHS of a
4813// comma operator
4814//===----------------------------------------------------------------------===//
4815
4816namespace {
4817class VoidExprEvaluator
4818 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4819public:
4820 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4821
4822 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004823
4824 bool VisitCastExpr(const CastExpr *E) {
4825 switch (E->getCastKind()) {
4826 default:
4827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4828 case CK_ToVoid:
4829 VisitIgnoredValue(E->getSubExpr());
4830 return true;
4831 }
4832 }
4833};
4834} // end anonymous namespace
4835
4836static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4837 assert(E->isRValue() && E->getType()->isVoidType());
4838 return VoidExprEvaluator(Info).Visit(E);
4839}
4840
4841//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004842// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004843//===----------------------------------------------------------------------===//
4844
Richard Smith0b0a0b62011-10-29 20:57:55 +00004845static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004846 // In C, function designators are not lvalues, but we evaluate them as if they
4847 // are.
4848 if (E->isGLValue() || E->getType()->isFunctionType()) {
4849 LValue LV;
4850 if (!EvaluateLValue(E, LV, Info))
4851 return false;
4852 LV.moveInto(Result);
4853 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004854 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004855 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004856 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004857 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004858 return false;
John McCall45d55e42010-05-07 21:00:08 +00004859 } else if (E->getType()->hasPointerRepresentation()) {
4860 LValue LV;
4861 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004862 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004863 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004864 } else if (E->getType()->isRealFloatingType()) {
4865 llvm::APFloat F(0.0);
4866 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004867 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004868 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004869 } else if (E->getType()->isAnyComplexType()) {
4870 ComplexValue C;
4871 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004872 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004873 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004874 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004875 MemberPtr P;
4876 if (!EvaluateMemberPointer(E, P, Info))
4877 return false;
4878 P.moveInto(Result);
4879 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004880 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004881 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004882 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004883 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004884 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004885 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004886 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004887 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004888 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004889 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4890 return false;
4891 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004892 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00004893 if (Info.getLangOpts().CPlusPlus0x)
4894 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4895 << E->getType();
4896 else
4897 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00004898 if (!EvaluateVoid(E, Info))
4899 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004900 } else if (Info.getLangOpts().CPlusPlus0x) {
4901 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4902 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004903 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004904 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004905 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004906 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004907
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004908 return true;
4909}
4910
Richard Smithed5165f2011-11-04 05:33:44 +00004911/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4912/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4913/// since later initializers for an object can indirectly refer to subobjects
4914/// which were initialized earlier.
4915static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00004916 const LValue &This, const Expr *E,
4917 CheckConstantExpressionKind CCEK) {
Richard Smithed5165f2011-11-04 05:33:44 +00004918 if (E->isRValue() && E->getType()->isLiteralType()) {
4919 // Evaluate arrays and record types in-place, so that later initializers can
4920 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004921 if (E->getType()->isArrayType())
4922 return EvaluateArray(E, This, Result, Info);
4923 else if (E->getType()->isRecordType())
4924 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004925 }
4926
4927 // For any other type, in-place evaluation is unimportant.
4928 CCValue CoreConstResult;
4929 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00004930 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00004931}
4932
Richard Smithf57d8cb2011-12-09 22:58:01 +00004933/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4934/// lvalue-to-rvalue cast if it is an lvalue.
4935static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4936 CCValue Value;
4937 if (!::Evaluate(Value, Info, E))
4938 return false;
4939
4940 if (E->isGLValue()) {
4941 LValue LV;
4942 LV.setFrom(Value);
4943 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4944 return false;
4945 }
4946
4947 // Check this core constant expression is a constant expression, and if so,
4948 // convert it to one.
4949 return CheckConstantExpression(Info, E, Value, Result);
4950}
Richard Smith11562c52011-10-28 17:51:58 +00004951
Richard Smith7b553f12011-10-29 00:50:52 +00004952/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004953/// any crazy technique (that has nothing to do with language standards) that
4954/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004955/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4956/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004957bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004958 // Fast-path evaluations of integer literals, since we sometimes see files
4959 // containing vast quantities of these.
4960 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4961 Result.Val = APValue(APSInt(L->getValue(),
4962 L->getType()->isUnsignedIntegerType()));
4963 return true;
4964 }
4965
Richard Smith5686e752011-11-10 03:30:42 +00004966 // FIXME: Evaluating initializers for large arrays can cause performance
4967 // problems, and we don't use such values yet. Once we have a more efficient
4968 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004969 // The same problem affects large records.
4970 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4971 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004972 return false;
4973
Richard Smithd62306a2011-11-10 06:34:14 +00004974 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004975 EvalInfo Info(Ctx, Result);
4976 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004977}
4978
Jay Foad39c79802011-01-12 09:06:06 +00004979bool Expr::EvaluateAsBooleanCondition(bool &Result,
4980 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004981 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004982 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004983 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004984 Result);
John McCall1be1c632010-01-05 23:42:56 +00004985}
4986
Richard Smithcaf33902011-10-10 18:28:20 +00004987bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004988 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004989 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004990 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004991 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992
Richard Smith11562c52011-10-28 17:51:58 +00004993 Result = ExprResult.Val.getInt();
4994 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004995}
4996
Jay Foad39c79802011-01-12 09:06:06 +00004997bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004998 EvalInfo Info(Ctx, Result);
4999
John McCall45d55e42010-05-07 21:00:08 +00005000 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005001 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005002 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5003 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005004}
5005
Richard Smithd0b4dd62011-12-19 06:19:21 +00005006bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5007 const VarDecl *VD,
5008 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5009 Expr::EvalStatus EStatus;
5010 EStatus.Diag = &Notes;
5011
5012 EvalInfo InitInfo(Ctx, EStatus);
5013 InitInfo.setEvaluatingDecl(VD, Value);
5014
5015 LValue LVal;
5016 LVal.set(VD);
5017
5018 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5019 !EStatus.HasSideEffects;
5020}
5021
Richard Smith7b553f12011-10-29 00:50:52 +00005022/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5023/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005024bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005025 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005026 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005027}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005028
Jay Foad39c79802011-01-12 09:06:06 +00005029bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005030 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005031}
5032
Richard Smithcaf33902011-10-10 18:28:20 +00005033APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005034 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005035 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005036 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005037 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005038 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005039
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005040 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005041}
John McCall864e3962010-05-07 05:32:02 +00005042
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005043 bool Expr::EvalResult::isGlobalLValue() const {
5044 assert(Val.isLValue());
5045 return IsGlobalLValue(Val.getLValueBase());
5046 }
5047
5048
John McCall864e3962010-05-07 05:32:02 +00005049/// isIntegerConstantExpr - this recursive routine will test if an expression is
5050/// an integer constant expression.
5051
5052/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5053/// comma, etc
5054///
5055/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5056/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5057/// cast+dereference.
5058
5059// CheckICE - This function does the fundamental ICE checking: the returned
5060// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5061// Note that to reduce code duplication, this helper does no evaluation
5062// itself; the caller checks whether the expression is evaluatable, and
5063// in the rare cases where CheckICE actually cares about the evaluated
5064// value, it calls into Evalute.
5065//
5066// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005067// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005068// 1: This expression is not an ICE, but if it isn't evaluated, it's
5069// a legal subexpression for an ICE. This return value is used to handle
5070// the comma operator in C99 mode.
5071// 2: This expression is not an ICE, and is not a legal subexpression for one.
5072
Dan Gohman28ade552010-07-26 21:25:24 +00005073namespace {
5074
John McCall864e3962010-05-07 05:32:02 +00005075struct ICEDiag {
5076 unsigned Val;
5077 SourceLocation Loc;
5078
5079 public:
5080 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5081 ICEDiag() : Val(0) {}
5082};
5083
Dan Gohman28ade552010-07-26 21:25:24 +00005084}
5085
5086static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005087
5088static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5089 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005090 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005091 !EVResult.Val.isInt()) {
5092 return ICEDiag(2, E->getLocStart());
5093 }
5094 return NoDiag();
5095}
5096
5097static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5098 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005099 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005100 return ICEDiag(2, E->getLocStart());
5101 }
5102
5103 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005104#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005105#define STMT(Node, Base) case Expr::Node##Class:
5106#define EXPR(Node, Base)
5107#include "clang/AST/StmtNodes.inc"
5108 case Expr::PredefinedExprClass:
5109 case Expr::FloatingLiteralClass:
5110 case Expr::ImaginaryLiteralClass:
5111 case Expr::StringLiteralClass:
5112 case Expr::ArraySubscriptExprClass:
5113 case Expr::MemberExprClass:
5114 case Expr::CompoundAssignOperatorClass:
5115 case Expr::CompoundLiteralExprClass:
5116 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005117 case Expr::DesignatedInitExprClass:
5118 case Expr::ImplicitValueInitExprClass:
5119 case Expr::ParenListExprClass:
5120 case Expr::VAArgExprClass:
5121 case Expr::AddrLabelExprClass:
5122 case Expr::StmtExprClass:
5123 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005124 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005125 case Expr::CXXDynamicCastExprClass:
5126 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005127 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005128 case Expr::CXXNullPtrLiteralExprClass:
5129 case Expr::CXXThisExprClass:
5130 case Expr::CXXThrowExprClass:
5131 case Expr::CXXNewExprClass:
5132 case Expr::CXXDeleteExprClass:
5133 case Expr::CXXPseudoDestructorExprClass:
5134 case Expr::UnresolvedLookupExprClass:
5135 case Expr::DependentScopeDeclRefExprClass:
5136 case Expr::CXXConstructExprClass:
5137 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005138 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005139 case Expr::CXXTemporaryObjectExprClass:
5140 case Expr::CXXUnresolvedConstructExprClass:
5141 case Expr::CXXDependentScopeMemberExprClass:
5142 case Expr::UnresolvedMemberExprClass:
5143 case Expr::ObjCStringLiteralClass:
5144 case Expr::ObjCEncodeExprClass:
5145 case Expr::ObjCMessageExprClass:
5146 case Expr::ObjCSelectorExprClass:
5147 case Expr::ObjCProtocolExprClass:
5148 case Expr::ObjCIvarRefExprClass:
5149 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005150 case Expr::ObjCIsaExprClass:
5151 case Expr::ShuffleVectorExprClass:
5152 case Expr::BlockExprClass:
5153 case Expr::BlockDeclRefExprClass:
5154 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005155 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005156 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005157 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005158 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005159 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005160 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005161 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005162 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005163 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005164 return ICEDiag(2, E->getLocStart());
5165
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005166 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005167 case Expr::GNUNullExprClass:
5168 // GCC considers the GNU __null value to be an integral constant expression.
5169 return NoDiag();
5170
John McCall7c454bb2011-07-15 05:09:51 +00005171 case Expr::SubstNonTypeTemplateParmExprClass:
5172 return
5173 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5174
John McCall864e3962010-05-07 05:32:02 +00005175 case Expr::ParenExprClass:
5176 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005177 case Expr::GenericSelectionExprClass:
5178 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005179 case Expr::IntegerLiteralClass:
5180 case Expr::CharacterLiteralClass:
5181 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005182 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005183 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005184 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005185 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005186 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005187 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005188 return NoDiag();
5189 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005190 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005191 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5192 // constant expressions, but they can never be ICEs because an ICE cannot
5193 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005194 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005195 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005196 return CheckEvalInICE(E, Ctx);
5197 return ICEDiag(2, E->getLocStart());
5198 }
5199 case Expr::DeclRefExprClass:
5200 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5201 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005202 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005203 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5204
5205 // Parameter variables are never constants. Without this check,
5206 // getAnyInitializer() can find a default argument, which leads
5207 // to chaos.
5208 if (isa<ParmVarDecl>(D))
5209 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5210
5211 // C++ 7.1.5.1p2
5212 // A variable of non-volatile const-qualified integral or enumeration
5213 // type initialized by an ICE can be used in ICEs.
5214 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005215 if (!Dcl->getType()->isIntegralOrEnumerationType())
5216 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5217
Richard Smithd0b4dd62011-12-19 06:19:21 +00005218 const VarDecl *VD;
5219 // Look for a declaration of this variable that has an initializer, and
5220 // check whether it is an ICE.
5221 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5222 return NoDiag();
5223 else
5224 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005225 }
5226 }
5227 return ICEDiag(2, E->getLocStart());
5228 case Expr::UnaryOperatorClass: {
5229 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5230 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005231 case UO_PostInc:
5232 case UO_PostDec:
5233 case UO_PreInc:
5234 case UO_PreDec:
5235 case UO_AddrOf:
5236 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005237 // C99 6.6/3 allows increment and decrement within unevaluated
5238 // subexpressions of constant expressions, but they can never be ICEs
5239 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005240 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005241 case UO_Extension:
5242 case UO_LNot:
5243 case UO_Plus:
5244 case UO_Minus:
5245 case UO_Not:
5246 case UO_Real:
5247 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005248 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005249 }
5250
5251 // OffsetOf falls through here.
5252 }
5253 case Expr::OffsetOfExprClass: {
5254 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005255 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005256 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005257 // compliance: we should warn earlier for offsetof expressions with
5258 // array subscripts that aren't ICEs, and if the array subscripts
5259 // are ICEs, the value of the offsetof must be an integer constant.
5260 return CheckEvalInICE(E, Ctx);
5261 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005262 case Expr::UnaryExprOrTypeTraitExprClass: {
5263 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5264 if ((Exp->getKind() == UETT_SizeOf) &&
5265 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005266 return ICEDiag(2, E->getLocStart());
5267 return NoDiag();
5268 }
5269 case Expr::BinaryOperatorClass: {
5270 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5271 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005272 case BO_PtrMemD:
5273 case BO_PtrMemI:
5274 case BO_Assign:
5275 case BO_MulAssign:
5276 case BO_DivAssign:
5277 case BO_RemAssign:
5278 case BO_AddAssign:
5279 case BO_SubAssign:
5280 case BO_ShlAssign:
5281 case BO_ShrAssign:
5282 case BO_AndAssign:
5283 case BO_XorAssign:
5284 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005285 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5286 // constant expressions, but they can never be ICEs because an ICE cannot
5287 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005288 return ICEDiag(2, E->getLocStart());
5289
John McCalle3027922010-08-25 11:45:40 +00005290 case BO_Mul:
5291 case BO_Div:
5292 case BO_Rem:
5293 case BO_Add:
5294 case BO_Sub:
5295 case BO_Shl:
5296 case BO_Shr:
5297 case BO_LT:
5298 case BO_GT:
5299 case BO_LE:
5300 case BO_GE:
5301 case BO_EQ:
5302 case BO_NE:
5303 case BO_And:
5304 case BO_Xor:
5305 case BO_Or:
5306 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005307 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5308 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005309 if (Exp->getOpcode() == BO_Div ||
5310 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005311 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005312 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005313 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005314 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005315 if (REval == 0)
5316 return ICEDiag(1, E->getLocStart());
5317 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005318 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005319 if (LEval.isMinSignedValue())
5320 return ICEDiag(1, E->getLocStart());
5321 }
5322 }
5323 }
John McCalle3027922010-08-25 11:45:40 +00005324 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005325 if (Ctx.getLangOptions().C99) {
5326 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5327 // if it isn't evaluated.
5328 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5329 return ICEDiag(1, E->getLocStart());
5330 } else {
5331 // In both C89 and C++, commas in ICEs are illegal.
5332 return ICEDiag(2, E->getLocStart());
5333 }
5334 }
5335 if (LHSResult.Val >= RHSResult.Val)
5336 return LHSResult;
5337 return RHSResult;
5338 }
John McCalle3027922010-08-25 11:45:40 +00005339 case BO_LAnd:
5340 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005341 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5342 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5343 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5344 // Rare case where the RHS has a comma "side-effect"; we need
5345 // to actually check the condition to see whether the side
5346 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005347 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005348 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005349 return RHSResult;
5350 return NoDiag();
5351 }
5352
5353 if (LHSResult.Val >= RHSResult.Val)
5354 return LHSResult;
5355 return RHSResult;
5356 }
5357 }
5358 }
5359 case Expr::ImplicitCastExprClass:
5360 case Expr::CStyleCastExprClass:
5361 case Expr::CXXFunctionalCastExprClass:
5362 case Expr::CXXStaticCastExprClass:
5363 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005364 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005365 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005366 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005367 if (isa<ExplicitCastExpr>(E)) {
5368 if (const FloatingLiteral *FL
5369 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5370 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5371 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5372 APSInt IgnoredVal(DestWidth, !DestSigned);
5373 bool Ignored;
5374 // If the value does not fit in the destination type, the behavior is
5375 // undefined, so we are not required to treat it as a constant
5376 // expression.
5377 if (FL->getValue().convertToInteger(IgnoredVal,
5378 llvm::APFloat::rmTowardZero,
5379 &Ignored) & APFloat::opInvalidOp)
5380 return ICEDiag(2, E->getLocStart());
5381 return NoDiag();
5382 }
5383 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005384 switch (cast<CastExpr>(E)->getCastKind()) {
5385 case CK_LValueToRValue:
5386 case CK_NoOp:
5387 case CK_IntegralToBoolean:
5388 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005389 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005390 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005391 return ICEDiag(2, E->getLocStart());
5392 }
John McCall864e3962010-05-07 05:32:02 +00005393 }
John McCallc07a0c72011-02-17 10:25:35 +00005394 case Expr::BinaryConditionalOperatorClass: {
5395 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5396 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5397 if (CommonResult.Val == 2) return CommonResult;
5398 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5399 if (FalseResult.Val == 2) return FalseResult;
5400 if (CommonResult.Val == 1) return CommonResult;
5401 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005402 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005403 return FalseResult;
5404 }
John McCall864e3962010-05-07 05:32:02 +00005405 case Expr::ConditionalOperatorClass: {
5406 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5407 // If the condition (ignoring parens) is a __builtin_constant_p call,
5408 // then only the true side is actually considered in an integer constant
5409 // expression, and it is fully evaluated. This is an important GNU
5410 // extension. See GCC PR38377 for discussion.
5411 if (const CallExpr *CallCE
5412 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005413 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005414 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005415 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005416 !EVResult.Val.isInt()) {
5417 return ICEDiag(2, E->getLocStart());
5418 }
5419 return NoDiag();
5420 }
5421 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005422 if (CondResult.Val == 2)
5423 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005424
Richard Smithf57d8cb2011-12-09 22:58:01 +00005425 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5426 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005427
John McCall864e3962010-05-07 05:32:02 +00005428 if (TrueResult.Val == 2)
5429 return TrueResult;
5430 if (FalseResult.Val == 2)
5431 return FalseResult;
5432 if (CondResult.Val == 1)
5433 return CondResult;
5434 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5435 return NoDiag();
5436 // Rare case where the diagnostics depend on which side is evaluated
5437 // Note that if we get here, CondResult is 0, and at least one of
5438 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005439 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005440 return FalseResult;
5441 }
5442 return TrueResult;
5443 }
5444 case Expr::CXXDefaultArgExprClass:
5445 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5446 case Expr::ChooseExprClass: {
5447 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5448 }
5449 }
5450
5451 // Silence a GCC warning
5452 return ICEDiag(2, E->getLocStart());
5453}
5454
Richard Smithf57d8cb2011-12-09 22:58:01 +00005455/// Evaluate an expression as a C++11 integral constant expression.
5456static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5457 const Expr *E,
5458 llvm::APSInt *Value,
5459 SourceLocation *Loc) {
5460 if (!E->getType()->isIntegralOrEnumerationType()) {
5461 if (Loc) *Loc = E->getExprLoc();
5462 return false;
5463 }
5464
5465 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005466 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5467 Result.Diag = &Diags;
5468 EvalInfo Info(Ctx, Result);
5469
5470 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5471 if (!Diags.empty()) {
5472 IsICE = false;
5473 if (Loc) *Loc = Diags[0].first;
5474 } else if (!IsICE && Loc) {
5475 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005476 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005477
5478 if (!IsICE)
5479 return false;
5480
5481 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5482 if (Value) *Value = Result.Val.getInt();
5483 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005484}
5485
Richard Smith92b1ce02011-12-12 09:28:41 +00005486bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005487 if (Ctx.getLangOptions().CPlusPlus0x)
5488 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5489
John McCall864e3962010-05-07 05:32:02 +00005490 ICEDiag d = CheckICE(this, Ctx);
5491 if (d.Val != 0) {
5492 if (Loc) *Loc = d.Loc;
5493 return false;
5494 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005495 return true;
5496}
5497
5498bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5499 SourceLocation *Loc, bool isEvaluated) const {
5500 if (Ctx.getLangOptions().CPlusPlus0x)
5501 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5502
5503 if (!isIntegerConstantExpr(Ctx, Loc))
5504 return false;
5505 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005506 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005507 return true;
5508}