blob: 3c2ffbd0f7b3397785a43796c410546f948b7ab0 [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 Smith357362d2011-12-13 06:39:58 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
348 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000349 // If we have a prior diagnostic, it will be noting that the expression
350 // isn't a constant expression. This diagnostic is more important.
351 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000353 unsigned CallStackNotes = CallStackDepth - 1;
354 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
355 if (Limit)
356 CallStackNotes = std::min(CallStackNotes, Limit + 1);
357
Richard Smith357362d2011-12-13 06:39:58 +0000358 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000359 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000360 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
361 addDiag(Loc, DiagId);
362 addCallStack(Limit);
363 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 }
Richard Smith357362d2011-12-13 06:39:58 +0000365 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000366 return OptionalDiagnostic();
367 }
368
369 /// Diagnose that the evaluation does not produce a C++11 core constant
370 /// expression.
Richard Smith357362d2011-12-13 06:39:58 +0000371 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
372 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000373 // Don't override a previous diagnostic.
374 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
375 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000376 return Diag(Loc, DiagId, ExtraNotes);
377 }
378
379 /// Add a note to a prior diagnostic.
380 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
381 if (!HasActiveDiagnostic)
382 return OptionalDiagnostic();
383 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000384 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000385
386 /// Add a stack of notes to a prior diagnostic.
387 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
388 if (HasActiveDiagnostic) {
389 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
390 Diags.begin(), Diags.end());
391 }
392 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000393 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000394}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395
Richard Smithf6f003a2011-12-16 19:06:07 +0000396CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
397 const FunctionDecl *Callee, const LValue *This,
398 const CCValue *Arguments)
399 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
400 This(This), Arguments(Arguments) {
401 Info.CurrentCall = this;
402 ++Info.CallStackDepth;
403}
404
405CallStackFrame::~CallStackFrame() {
406 assert(Info.CurrentCall == this && "calls retired out of order");
407 --Info.CallStackDepth;
408 Info.CurrentCall = Caller;
409}
410
411/// Produce a string describing the given constexpr call.
412static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
413 unsigned ArgIndex = 0;
414 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
415 !isa<CXXConstructorDecl>(Frame->Callee);
416
417 if (!IsMemberCall)
418 Out << *Frame->Callee << '(';
419
420 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
421 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
422 if (ArgIndex > IsMemberCall)
423 Out << ", ";
424
425 const ParmVarDecl *Param = *I;
426 const CCValue &Arg = Frame->Arguments[ArgIndex];
427 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
428 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
429 else {
430 // Deliberately slice off the frame to form an APValue we can print.
431 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
432 Arg.getLValueDesignator().Entries,
433 Arg.getLValueDesignator().OnePastTheEnd);
434 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
435 }
436
437 if (ArgIndex == 0 && IsMemberCall)
438 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 }
440
Richard Smithf6f003a2011-12-16 19:06:07 +0000441 Out << ')';
442}
443
444void EvalInfo::addCallStack(unsigned Limit) {
445 // Determine which calls to skip, if any.
446 unsigned ActiveCalls = CallStackDepth - 1;
447 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
448 if (Limit && Limit < ActiveCalls) {
449 SkipStart = Limit / 2 + Limit % 2;
450 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000451 }
452
Richard Smithf6f003a2011-12-16 19:06:07 +0000453 // Walk the call stack and add the diagnostics.
454 unsigned CallIdx = 0;
455 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
456 Frame = Frame->Caller, ++CallIdx) {
457 // Skip this call?
458 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
459 if (CallIdx == SkipStart) {
460 // Note that we're skipping calls.
461 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
462 << unsigned(ActiveCalls - Limit);
463 }
464 continue;
465 }
466
467 llvm::SmallVector<char, 128> Buffer;
468 llvm::raw_svector_ostream Out(Buffer);
469 describeCall(Frame, Out);
470 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
471 }
472}
473
474namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000475 struct ComplexValue {
476 private:
477 bool IsInt;
478
479 public:
480 APSInt IntReal, IntImag;
481 APFloat FloatReal, FloatImag;
482
483 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
484
485 void makeComplexFloat() { IsInt = false; }
486 bool isComplexFloat() const { return !IsInt; }
487 APFloat &getComplexFloatReal() { return FloatReal; }
488 APFloat &getComplexFloatImag() { return FloatImag; }
489
490 void makeComplexInt() { IsInt = true; }
491 bool isComplexInt() const { return IsInt; }
492 APSInt &getComplexIntReal() { return IntReal; }
493 APSInt &getComplexIntImag() { return IntImag; }
494
Richard Smith0b0a0b62011-10-29 20:57:55 +0000495 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000496 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000497 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000498 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000502 assert(v.isComplexFloat() || v.isComplexInt());
503 if (v.isComplexFloat()) {
504 makeComplexFloat();
505 FloatReal = v.getComplexFloatReal();
506 FloatImag = v.getComplexFloatImag();
507 } else {
508 makeComplexInt();
509 IntReal = v.getComplexIntReal();
510 IntImag = v.getComplexIntImag();
511 }
512 }
John McCall93d91dc2010-05-07 17:22:02 +0000513 };
John McCall45d55e42010-05-07 21:00:08 +0000514
515 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000516 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000517 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000518 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000519 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000520
Richard Smithce40ad62011-11-12 22:28:03 +0000521 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000522 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000523 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000524 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000525 SubobjectDesignator &getLValueDesignator() { return Designator; }
526 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000527
Richard Smith0b0a0b62011-10-29 20:57:55 +0000528 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000529 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000530 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000531 void setFrom(const CCValue &V) {
532 assert(V.isLValue());
533 Base = V.getLValueBase();
534 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000535 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000536 Designator = V.getLValueDesignator();
537 }
538
Richard Smithce40ad62011-11-12 22:28:03 +0000539 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
540 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000541 Offset = CharUnits::Zero();
542 Frame = F;
543 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000544 }
John McCall45d55e42010-05-07 21:00:08 +0000545 };
Richard Smith027bf112011-11-17 22:56:20 +0000546
547 struct MemberPtr {
548 MemberPtr() {}
549 explicit MemberPtr(const ValueDecl *Decl) :
550 DeclAndIsDerivedMember(Decl, false), Path() {}
551
552 /// The member or (direct or indirect) field referred to by this member
553 /// pointer, or 0 if this is a null member pointer.
554 const ValueDecl *getDecl() const {
555 return DeclAndIsDerivedMember.getPointer();
556 }
557 /// Is this actually a member of some type derived from the relevant class?
558 bool isDerivedMember() const {
559 return DeclAndIsDerivedMember.getInt();
560 }
561 /// Get the class which the declaration actually lives in.
562 const CXXRecordDecl *getContainingRecord() const {
563 return cast<CXXRecordDecl>(
564 DeclAndIsDerivedMember.getPointer()->getDeclContext());
565 }
566
567 void moveInto(CCValue &V) const {
568 V = CCValue(getDecl(), isDerivedMember(), Path);
569 }
570 void setFrom(const CCValue &V) {
571 assert(V.isMemberPointer());
572 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
573 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
574 Path.clear();
575 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
576 Path.insert(Path.end(), P.begin(), P.end());
577 }
578
579 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
580 /// whether the member is a member of some class derived from the class type
581 /// of the member pointer.
582 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
583 /// Path - The path of base/derived classes from the member declaration's
584 /// class (exclusive) to the class type of the member pointer (inclusive).
585 SmallVector<const CXXRecordDecl*, 4> Path;
586
587 /// Perform a cast towards the class of the Decl (either up or down the
588 /// hierarchy).
589 bool castBack(const CXXRecordDecl *Class) {
590 assert(!Path.empty());
591 const CXXRecordDecl *Expected;
592 if (Path.size() >= 2)
593 Expected = Path[Path.size() - 2];
594 else
595 Expected = getContainingRecord();
596 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
597 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
598 // if B does not contain the original member and is not a base or
599 // derived class of the class containing the original member, the result
600 // of the cast is undefined.
601 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
602 // (D::*). We consider that to be a language defect.
603 return false;
604 }
605 Path.pop_back();
606 return true;
607 }
608 /// Perform a base-to-derived member pointer cast.
609 bool castToDerived(const CXXRecordDecl *Derived) {
610 if (!getDecl())
611 return true;
612 if (!isDerivedMember()) {
613 Path.push_back(Derived);
614 return true;
615 }
616 if (!castBack(Derived))
617 return false;
618 if (Path.empty())
619 DeclAndIsDerivedMember.setInt(false);
620 return true;
621 }
622 /// Perform a derived-to-base member pointer cast.
623 bool castToBase(const CXXRecordDecl *Base) {
624 if (!getDecl())
625 return true;
626 if (Path.empty())
627 DeclAndIsDerivedMember.setInt(true);
628 if (isDerivedMember()) {
629 Path.push_back(Base);
630 return true;
631 }
632 return castBack(Base);
633 }
634 };
Richard Smith357362d2011-12-13 06:39:58 +0000635
636 /// Kinds of constant expression checking, for diagnostics.
637 enum CheckConstantExpressionKind {
638 CCEK_Constant, ///< A normal constant.
639 CCEK_ReturnValue, ///< A constexpr function return value.
640 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
641 };
John McCall93d91dc2010-05-07 17:22:02 +0000642}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000643
Richard Smith0b0a0b62011-10-29 20:57:55 +0000644static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000645static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000646 const LValue &This, const Expr *E,
647 CheckConstantExpressionKind CCEK
648 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000649static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
650static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000651static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
652 EvalInfo &Info);
653static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000654static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000655static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000656 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000657static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000658static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000659
660//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000661// Misc utilities
662//===----------------------------------------------------------------------===//
663
Richard Smithd62306a2011-11-10 06:34:14 +0000664/// Should this call expression be treated as a string literal?
665static bool IsStringLiteralCall(const CallExpr *E) {
666 unsigned Builtin = E->isBuiltinCall();
667 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
668 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
669}
670
Richard Smithce40ad62011-11-12 22:28:03 +0000671static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000672 // C++11 [expr.const]p3 An address constant expression is a prvalue core
673 // constant expression of pointer type that evaluates to...
674
675 // ... a null pointer value, or a prvalue core constant expression of type
676 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000677 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000678
Richard Smithce40ad62011-11-12 22:28:03 +0000679 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
680 // ... the address of an object with static storage duration,
681 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
682 return VD->hasGlobalStorage();
683 // ... the address of a function,
684 return isa<FunctionDecl>(D);
685 }
686
687 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000688 switch (E->getStmtClass()) {
689 default:
690 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000691 case Expr::CompoundLiteralExprClass:
692 return cast<CompoundLiteralExpr>(E)->isFileScope();
693 // A string literal has static storage duration.
694 case Expr::StringLiteralClass:
695 case Expr::PredefinedExprClass:
696 case Expr::ObjCStringLiteralClass:
697 case Expr::ObjCEncodeExprClass:
698 return true;
699 case Expr::CallExprClass:
700 return IsStringLiteralCall(cast<CallExpr>(E));
701 // For GCC compatibility, &&label has static storage duration.
702 case Expr::AddrLabelExprClass:
703 return true;
704 // A Block literal expression may be used as the initialization value for
705 // Block variables at global or local static scope.
706 case Expr::BlockExprClass:
707 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
708 }
John McCall95007602010-05-10 23:27:23 +0000709}
710
Richard Smith80815602011-11-07 05:07:52 +0000711/// Check that this reference or pointer core constant expression is a valid
712/// value for a constant expression. Type T should be either LValue or CCValue.
713template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000714static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000715 const T &LVal, APValue &Value,
716 CheckConstantExpressionKind CCEK) {
717 APValue::LValueBase Base = LVal.getLValueBase();
718 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
719
720 if (!IsGlobalLValue(Base)) {
721 if (Info.getLangOpts().CPlusPlus0x) {
722 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
723 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
724 << E->isGLValue() << !Designator.Entries.empty()
725 << !!VD << CCEK << VD;
726 if (VD)
727 Info.Note(VD->getLocation(), diag::note_declared_at);
728 else
729 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
730 diag::note_constexpr_temporary_here);
731 } else {
732 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
733 }
Richard Smith80815602011-11-07 05:07:52 +0000734 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000735 }
Richard Smith80815602011-11-07 05:07:52 +0000736
Richard Smith80815602011-11-07 05:07:52 +0000737 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000738 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000739 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000740 // FIXME: This is not a core constant expression. We should have already
741 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000742 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
743 APValue::NoLValuePath());
744 return true;
745 }
746
Richard Smith357362d2011-12-13 06:39:58 +0000747 // Does this refer one past the end of some object?
748 // This is technically not an address constant expression nor a reference
749 // constant expression, but we allow it for address constant expressions.
750 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
751 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
752 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
753 << !Designator.Entries.empty() << !!VD << VD;
754 if (VD)
755 Info.Note(VD->getLocation(), diag::note_declared_at);
756 else
757 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
758 diag::note_constexpr_temporary_here);
759 return false;
760 }
761
Richard Smith80815602011-11-07 05:07:52 +0000762 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000763 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000764 return true;
765}
766
Richard Smith0b0a0b62011-10-29 20:57:55 +0000767/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000768/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000769/// If not, report an appropriate diagnostic.
770static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000771 const CCValue &CCValue, APValue &Value,
772 CheckConstantExpressionKind CCEK
773 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000774 if (!CCValue.isLValue()) {
775 Value = CCValue;
776 return true;
777 }
Richard Smith357362d2011-12-13 06:39:58 +0000778 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000779}
780
Richard Smith83c68212011-10-31 05:11:32 +0000781const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000782 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000783}
784
785static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000786 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000787}
788
Richard Smithcecf1842011-11-01 21:06:14 +0000789static bool IsWeakLValue(const LValue &Value) {
790 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000791 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000792}
793
Richard Smith027bf112011-11-17 22:56:20 +0000794static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000795 // A null base expression indicates a null pointer. These are always
796 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000797 if (!Value.getLValueBase()) {
798 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000799 return true;
800 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000801
John McCall95007602010-05-10 23:27:23 +0000802 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000803 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000804 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000805
Richard Smith027bf112011-11-17 22:56:20 +0000806 // We have a non-null base. These are generally known to be true, but if it's
807 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000808 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000809 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000810 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000811}
812
Richard Smith0b0a0b62011-10-29 20:57:55 +0000813static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000814 switch (Val.getKind()) {
815 case APValue::Uninitialized:
816 return false;
817 case APValue::Int:
818 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000819 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000820 case APValue::Float:
821 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000822 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000823 case APValue::ComplexInt:
824 Result = Val.getComplexIntReal().getBoolValue() ||
825 Val.getComplexIntImag().getBoolValue();
826 return true;
827 case APValue::ComplexFloat:
828 Result = !Val.getComplexFloatReal().isZero() ||
829 !Val.getComplexFloatImag().isZero();
830 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000831 case APValue::LValue:
832 return EvalPointerValueAsBool(Val, Result);
833 case APValue::MemberPointer:
834 Result = Val.getMemberPointerDecl();
835 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000836 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000837 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000838 case APValue::Struct:
839 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000840 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000841 }
842
Richard Smith11562c52011-10-28 17:51:58 +0000843 llvm_unreachable("unknown APValue kind");
844}
845
846static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
847 EvalInfo &Info) {
848 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000849 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000850 if (!Evaluate(Val, Info, E))
851 return false;
852 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000853}
854
Richard Smith357362d2011-12-13 06:39:58 +0000855template<typename T>
856static bool HandleOverflow(EvalInfo &Info, const Expr *E,
857 const T &SrcValue, QualType DestType) {
858 llvm::SmallVector<char, 32> Buffer;
859 SrcValue.toString(Buffer);
860 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
861 << StringRef(Buffer.data(), Buffer.size()) << DestType;
862 return false;
863}
864
865static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
866 QualType SrcType, const APFloat &Value,
867 QualType DestType, APSInt &Result) {
868 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000869 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000870 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Smith357362d2011-12-13 06:39:58 +0000872 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000873 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000874 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
875 & APFloat::opInvalidOp)
876 return HandleOverflow(Info, E, Value, DestType);
877 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000878}
879
Richard Smith357362d2011-12-13 06:39:58 +0000880static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
881 QualType SrcType, QualType DestType,
882 APFloat &Result) {
883 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000884 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000885 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
886 APFloat::rmNearestTiesToEven, &ignored)
887 & APFloat::opOverflow)
888 return HandleOverflow(Info, E, Value, DestType);
889 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000890}
891
Mike Stump11289f42009-09-09 15:08:12 +0000892static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000893 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000894 unsigned DestWidth = Ctx.getIntWidth(DestType);
895 APSInt Result = Value;
896 // Figure out if this is a truncate, extend or noop cast.
897 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000898 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000899 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000900 return Result;
901}
902
Richard Smith357362d2011-12-13 06:39:58 +0000903static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
904 QualType SrcType, const APSInt &Value,
905 QualType DestType, APFloat &Result) {
906 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
907 if (Result.convertFromAPInt(Value, Value.isSigned(),
908 APFloat::rmNearestTiesToEven)
909 & APFloat::opOverflow)
910 return HandleOverflow(Info, E, Value, DestType);
911 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000912}
913
Richard Smith027bf112011-11-17 22:56:20 +0000914static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
915 const CXXRecordDecl *&MostDerivedType,
916 unsigned &MostDerivedPathLength,
917 bool &MostDerivedIsArrayElement) {
918 const SubobjectDesignator &D = LVal.Designator;
919 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000920 return false;
921
Richard Smith027bf112011-11-17 22:56:20 +0000922 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000923
924 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000925 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000926 MostDerivedPathLength = 0;
927 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000928
929 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
930 bool IsArray = T && T->isArrayType();
931 if (IsArray)
932 T = T->getBaseElementTypeUnsafe();
933 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
934 T = FD->getType().getTypePtr();
935 else
936 T = 0;
937
938 if (T) {
939 MostDerivedType = T->getAsCXXRecordDecl();
940 MostDerivedPathLength = I + 1;
941 MostDerivedIsArrayElement = IsArray;
942 }
943 }
944
Richard Smithd62306a2011-11-10 06:34:14 +0000945 // (B*)&d + 1 has no most-derived object.
946 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
947 return false;
948
Richard Smith027bf112011-11-17 22:56:20 +0000949 return MostDerivedType != 0;
950}
951
952static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
953 const RecordDecl *TruncatedType,
954 unsigned TruncatedElements,
955 bool IsArrayElement) {
956 SubobjectDesignator &D = Result.Designator;
957 const RecordDecl *RD = TruncatedType;
958 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000959 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
960 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000961 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000962 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000963 else
Richard Smithd62306a2011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getBaseClassOffset(Base);
965 RD = Base;
966 }
Richard Smith027bf112011-11-17 22:56:20 +0000967 D.Entries.resize(TruncatedElements);
968 D.ArrayElement = IsArrayElement;
969}
970
971/// If the given LValue refers to a base subobject of some object, find the most
972/// derived object and the corresponding complete record type. This is necessary
973/// in order to find the offset of a virtual base class.
974static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
975 const CXXRecordDecl *&MostDerivedType) {
976 unsigned MostDerivedPathLength;
977 bool MostDerivedIsArrayElement;
978 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
979 MostDerivedPathLength, MostDerivedIsArrayElement))
980 return false;
981
982 // Remove the trailing base class path entries and their offsets.
983 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
984 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000985 return true;
986}
987
988static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
989 const CXXRecordDecl *Derived,
990 const CXXRecordDecl *Base,
991 const ASTRecordLayout *RL = 0) {
992 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
993 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
994 Obj.Designator.addDecl(Base, /*Virtual*/ false);
995}
996
997static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
998 const CXXRecordDecl *DerivedDecl,
999 const CXXBaseSpecifier *Base) {
1000 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1001
1002 if (!Base->isVirtual()) {
1003 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1004 return true;
1005 }
1006
1007 // Extract most-derived object and corresponding type.
1008 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1009 return false;
1010
1011 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1012 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1013 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1014 return true;
1015}
1016
1017/// Update LVal to refer to the given field, which must be a member of the type
1018/// currently described by LVal.
1019static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1020 const FieldDecl *FD,
1021 const ASTRecordLayout *RL = 0) {
1022 if (!RL)
1023 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1024
1025 unsigned I = FD->getFieldIndex();
1026 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1027 LVal.Designator.addDecl(FD);
1028}
1029
1030/// Get the size of the given type in char units.
1031static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1032 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1033 // extension.
1034 if (Type->isVoidType() || Type->isFunctionType()) {
1035 Size = CharUnits::One();
1036 return true;
1037 }
1038
1039 if (!Type->isConstantSizeType()) {
1040 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1041 return false;
1042 }
1043
1044 Size = Info.Ctx.getTypeSizeInChars(Type);
1045 return true;
1046}
1047
1048/// Update a pointer value to model pointer arithmetic.
1049/// \param Info - Information about the ongoing evaluation.
1050/// \param LVal - The pointer value to be updated.
1051/// \param EltTy - The pointee type represented by LVal.
1052/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1053static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1054 QualType EltTy, int64_t Adjustment) {
1055 CharUnits SizeOfPointee;
1056 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1057 return false;
1058
1059 // Compute the new offset in the appropriate width.
1060 LVal.Offset += Adjustment * SizeOfPointee;
1061 LVal.Designator.adjustIndex(Adjustment);
1062 return true;
1063}
1064
Richard Smith27908702011-10-24 17:54:18 +00001065/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001066static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1067 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001068 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001069 // If this is a parameter to an active constexpr function call, perform
1070 // argument substitution.
1071 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001072 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001073 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001074 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001075 }
Richard Smithfec09922011-11-01 16:57:24 +00001076 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1077 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001078 }
Richard Smith27908702011-10-24 17:54:18 +00001079
Richard Smithd0b4dd62011-12-19 06:19:21 +00001080 // Dig out the initializer, and use the declaration which it's attached to.
1081 const Expr *Init = VD->getAnyInitializer(VD);
1082 if (!Init || Init->isValueDependent()) {
1083 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1084 return false;
1085 }
1086
Richard Smithd62306a2011-11-10 06:34:14 +00001087 // If we're currently evaluating the initializer of this declaration, use that
1088 // in-flight value.
1089 if (Info.EvaluatingDecl == VD) {
1090 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1091 return !Result.isUninit();
1092 }
1093
Richard Smithcecf1842011-11-01 21:06:14 +00001094 // Never evaluate the initializer of a weak variable. We can't be sure that
1095 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001096 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001097 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001098 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001099 }
Richard Smithcecf1842011-11-01 21:06:14 +00001100
Richard Smithd0b4dd62011-12-19 06:19:21 +00001101 // Check that we can fold the initializer. In C++, we will have already done
1102 // this in the cases where it matters for conformance.
1103 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1104 if (!VD->evaluateValue(Notes)) {
1105 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1106 Notes.size() + 1) << VD;
1107 Info.Note(VD->getLocation(), diag::note_declared_at);
1108 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001109 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001110 } else if (!VD->checkInitIsICE()) {
1111 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1112 Notes.size() + 1) << VD;
1113 Info.Note(VD->getLocation(), diag::note_declared_at);
1114 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001115 }
Richard Smith27908702011-10-24 17:54:18 +00001116
Richard Smithd0b4dd62011-12-19 06:19:21 +00001117 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001118 return true;
Richard Smith27908702011-10-24 17:54:18 +00001119}
1120
Richard Smith11562c52011-10-28 17:51:58 +00001121static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001122 Qualifiers Quals = T.getQualifiers();
1123 return Quals.hasConst() && !Quals.hasVolatile();
1124}
1125
Richard Smithe97cbd72011-11-11 04:05:33 +00001126/// Get the base index of the given base class within an APValue representing
1127/// the given derived class.
1128static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1129 const CXXRecordDecl *Base) {
1130 Base = Base->getCanonicalDecl();
1131 unsigned Index = 0;
1132 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1133 E = Derived->bases_end(); I != E; ++I, ++Index) {
1134 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1135 return Index;
1136 }
1137
1138 llvm_unreachable("base class missing from derived class's bases list");
1139}
1140
Richard Smithf3e9e432011-11-07 09:22:26 +00001141/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001142static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1143 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001144 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001145 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001146 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001147 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001148 }
Richard Smith6804be52011-11-11 08:28:03 +00001149 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001150 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001151
1152 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1153 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001154 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001155 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001156 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001157 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001158 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001159 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001160 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001161 if (CAT->getSize().ule(Index)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001162 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001163 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001164 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001165 if (O->getArrayInitializedElts() > Index)
1166 O = &O->getArrayInitializedElt(Index);
1167 else
1168 O = &O->getArrayFiller();
1169 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001170 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1171 // Next subobject is a class, struct or union field.
1172 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1173 if (RD->isUnion()) {
1174 const FieldDecl *UnionField = O->getUnionField();
1175 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001176 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001177 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001178 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001179 }
Richard Smithd62306a2011-11-10 06:34:14 +00001180 O = &O->getUnionValue();
1181 } else
1182 O = &O->getStructField(Field->getFieldIndex());
1183 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001184 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001185 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001186 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1187 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1188 O = &O->getStructBase(getBaseIndex(Derived, Base));
1189 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001190 }
Richard Smithd62306a2011-11-10 06:34:14 +00001191
Richard Smithf57d8cb2011-12-09 22:58:01 +00001192 if (O->isUninit()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001193 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001194 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001195 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001196 }
1197
Richard Smithf3e9e432011-11-07 09:22:26 +00001198 Obj = CCValue(*O, CCValue::GlobalValue());
1199 return true;
1200}
1201
Richard Smithd62306a2011-11-10 06:34:14 +00001202/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1203/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1204/// for looking up the glvalue referred to by an entity of reference type.
1205///
1206/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001207/// \param Conv - The expression for which we are performing the conversion.
1208/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001209/// \param Type - The type we expect this conversion to produce.
1210/// \param LVal - The glvalue on which we are attempting to perform this action.
1211/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001212static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1213 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001214 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001215 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001216 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001217
Richard Smithf57d8cb2011-12-09 22:58:01 +00001218 if (!LVal.Base) {
1219 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith92b1ce02011-12-12 09:28:41 +00001220 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001221 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001222 }
Richard Smith11562c52011-10-28 17:51:58 +00001223
Richard Smithce40ad62011-11-12 22:28:03 +00001224 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001225 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1226 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001227 // expressions are constant expressions too. Inside constexpr functions,
1228 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001229 // In C, such things can also be folded, although they are not ICEs.
1230 //
Richard Smith254a73d2011-10-28 22:34:42 +00001231 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1232 // interpretation of C++11 suggests that volatile parameters are OK if
1233 // they're never read (there's no prohibition against constructing volatile
1234 // objects in constant expressions), but lvalue-to-rvalue conversions on
1235 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001236 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001237 if (!VD || VD->isInvalidDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001238 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
1241
Richard Smithce40ad62011-11-12 22:28:03 +00001242 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001243 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001244 if (!IsConstNonVolatile(VT)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001245 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001246 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001247 }
Richard Smitha08acd82011-11-07 03:22:51 +00001248 // FIXME: Allow folding of values of any literal type in all languages.
1249 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001250 !VD->isConstexpr()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001251 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001252 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001253 }
Richard Smith96e0c102011-11-04 02:25:55 +00001254 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001255 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001256 return false;
1257
Richard Smith0b0a0b62011-10-29 20:57:55 +00001258 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001259 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001260
1261 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1262 // conversion. This happens when the declaration and the lvalue should be
1263 // considered synonymous, for instance when initializing an array of char
1264 // from a string literal. Continue as if the initializer lvalue was the
1265 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001266 assert(RVal.getLValueOffset().isZero() &&
1267 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001268 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001269 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001270 }
1271
Richard Smith96e0c102011-11-04 02:25:55 +00001272 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1273 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1274 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001275 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001276 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001277 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001278 }
Richard Smith96e0c102011-11-04 02:25:55 +00001279
1280 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001281 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001282 if (Index > S->getLength()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001283 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001284 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 }
Richard Smith96e0c102011-11-04 02:25:55 +00001286 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1287 Type->isUnsignedIntegerType());
1288 if (Index < S->getLength())
1289 Value = S->getCodeUnit(Index);
1290 RVal = CCValue(Value);
1291 return true;
1292 }
1293
Richard Smithf3e9e432011-11-07 09:22:26 +00001294 if (Frame) {
1295 // If this is a temporary expression with a nontrivial initializer, grab the
1296 // value from the relevant stack frame.
1297 RVal = Frame->Temporaries[Base];
1298 } else if (const CompoundLiteralExpr *CLE
1299 = dyn_cast<CompoundLiteralExpr>(Base)) {
1300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1301 // initializer until now for such expressions. Such an expression can't be
1302 // an ICE in C, so this only matters for fold.
1303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1304 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1305 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001306 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001307 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001308 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001309 }
Richard Smith96e0c102011-11-04 02:25:55 +00001310
Richard Smithf57d8cb2011-12-09 22:58:01 +00001311 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1312 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001313}
1314
Richard Smithe97cbd72011-11-11 04:05:33 +00001315/// Build an lvalue for the object argument of a member function call.
1316static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1317 LValue &This) {
1318 if (Object->getType()->isPointerType())
1319 return EvaluatePointer(Object, This, Info);
1320
1321 if (Object->isGLValue())
1322 return EvaluateLValue(Object, This, Info);
1323
Richard Smith027bf112011-11-17 22:56:20 +00001324 if (Object->getType()->isLiteralType())
1325 return EvaluateTemporary(Object, This, Info);
1326
1327 return false;
1328}
1329
1330/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1331/// lvalue referring to the result.
1332///
1333/// \param Info - Information about the ongoing evaluation.
1334/// \param BO - The member pointer access operation.
1335/// \param LV - Filled in with a reference to the resulting object.
1336/// \param IncludeMember - Specifies whether the member itself is included in
1337/// the resulting LValue subobject designator. This is not possible when
1338/// creating a bound member function.
1339/// \return The field or method declaration to which the member pointer refers,
1340/// or 0 if evaluation fails.
1341static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1342 const BinaryOperator *BO,
1343 LValue &LV,
1344 bool IncludeMember = true) {
1345 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1346
1347 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1348 return 0;
1349
1350 MemberPtr MemPtr;
1351 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1352 return 0;
1353
1354 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1355 // member value, the behavior is undefined.
1356 if (!MemPtr.getDecl())
1357 return 0;
1358
1359 if (MemPtr.isDerivedMember()) {
1360 // This is a member of some derived class. Truncate LV appropriately.
1361 const CXXRecordDecl *MostDerivedType;
1362 unsigned MostDerivedPathLength;
1363 bool MostDerivedIsArrayElement;
1364 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1365 MostDerivedIsArrayElement))
1366 return 0;
1367
1368 // The end of the derived-to-base path for the base object must match the
1369 // derived-to-base path for the member pointer.
1370 if (MostDerivedPathLength + MemPtr.Path.size() >
1371 LV.Designator.Entries.size())
1372 return 0;
1373 unsigned PathLengthToMember =
1374 LV.Designator.Entries.size() - MemPtr.Path.size();
1375 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1376 const CXXRecordDecl *LVDecl = getAsBaseClass(
1377 LV.Designator.Entries[PathLengthToMember + I]);
1378 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1379 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1380 return 0;
1381 }
1382
1383 // Truncate the lvalue to the appropriate derived class.
1384 bool ResultIsArray = false;
1385 if (PathLengthToMember == MostDerivedPathLength)
1386 ResultIsArray = MostDerivedIsArrayElement;
1387 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1388 PathLengthToMember, ResultIsArray);
1389 } else if (!MemPtr.Path.empty()) {
1390 // Extend the LValue path with the member pointer's path.
1391 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1392 MemPtr.Path.size() + IncludeMember);
1393
1394 // Walk down to the appropriate base class.
1395 QualType LVType = BO->getLHS()->getType();
1396 if (const PointerType *PT = LVType->getAs<PointerType>())
1397 LVType = PT->getPointeeType();
1398 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1399 assert(RD && "member pointer access on non-class-type expression");
1400 // The first class in the path is that of the lvalue.
1401 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1402 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1403 HandleLValueDirectBase(Info, LV, RD, Base);
1404 RD = Base;
1405 }
1406 // Finally cast to the class containing the member.
1407 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1408 }
1409
1410 // Add the member. Note that we cannot build bound member functions here.
1411 if (IncludeMember) {
1412 // FIXME: Deal with IndirectFieldDecls.
1413 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1414 if (!FD) return 0;
1415 HandleLValueMember(Info, LV, FD);
1416 }
1417
1418 return MemPtr.getDecl();
1419}
1420
1421/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1422/// the provided lvalue, which currently refers to the base object.
1423static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1424 LValue &Result) {
1425 const CXXRecordDecl *MostDerivedType;
1426 unsigned MostDerivedPathLength;
1427 bool MostDerivedIsArrayElement;
1428
1429 // Check this cast doesn't take us outside the object.
1430 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1431 MostDerivedPathLength,
1432 MostDerivedIsArrayElement))
1433 return false;
1434 SubobjectDesignator &D = Result.Designator;
1435 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1436 return false;
1437
1438 // Check the type of the final cast. We don't need to check the path,
1439 // since a cast can only be formed if the path is unique.
1440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1441 bool ResultIsArray = false;
1442 QualType TargetQT = E->getType();
1443 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1444 TargetQT = PT->getPointeeType();
1445 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1446 const CXXRecordDecl *FinalType;
1447 if (NewEntriesSize == MostDerivedPathLength) {
1448 ResultIsArray = MostDerivedIsArrayElement;
1449 FinalType = MostDerivedType;
1450 } else
1451 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1452 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1453 return false;
1454
1455 // Truncate the lvalue to the appropriate derived class.
1456 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1457 ResultIsArray);
1458 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001459}
1460
Mike Stump876387b2009-10-27 22:09:17 +00001461namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001462enum EvalStmtResult {
1463 /// Evaluation failed.
1464 ESR_Failed,
1465 /// Hit a 'return' statement.
1466 ESR_Returned,
1467 /// Evaluation succeeded.
1468 ESR_Succeeded
1469};
1470}
1471
1472// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001473static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001474 const Stmt *S) {
1475 switch (S->getStmtClass()) {
1476 default:
1477 return ESR_Failed;
1478
1479 case Stmt::NullStmtClass:
1480 case Stmt::DeclStmtClass:
1481 return ESR_Succeeded;
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483 case Stmt::ReturnStmtClass: {
1484 CCValue CCResult;
1485 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1486 if (!Evaluate(CCResult, Info, RetExpr) ||
1487 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1488 CCEK_ReturnValue))
1489 return ESR_Failed;
1490 return ESR_Returned;
1491 }
Richard Smith254a73d2011-10-28 22:34:42 +00001492
1493 case Stmt::CompoundStmtClass: {
1494 const CompoundStmt *CS = cast<CompoundStmt>(S);
1495 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1496 BE = CS->body_end(); BI != BE; ++BI) {
1497 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1498 if (ESR != ESR_Succeeded)
1499 return ESR;
1500 }
1501 return ESR_Succeeded;
1502 }
1503 }
1504}
1505
Richard Smith357362d2011-12-13 06:39:58 +00001506/// CheckConstexprFunction - Check that a function can be called in a constant
1507/// expression.
1508static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1509 const FunctionDecl *Declaration,
1510 const FunctionDecl *Definition) {
1511 // Can we evaluate this function call?
1512 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1513 return true;
1514
1515 if (Info.getLangOpts().CPlusPlus0x) {
1516 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001517 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1518 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001519 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1520 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1521 << DiagDecl;
1522 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1523 } else {
1524 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1525 }
1526 return false;
1527}
1528
Richard Smithd62306a2011-11-10 06:34:14 +00001529namespace {
Richard Smith60494462011-11-11 05:48:57 +00001530typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001531}
1532
1533/// EvaluateArgs - Evaluate the arguments to a function call.
1534static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1535 EvalInfo &Info) {
1536 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1537 I != E; ++I)
1538 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1539 return false;
1540 return true;
1541}
1542
Richard Smith254a73d2011-10-28 22:34:42 +00001543/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001544static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1545 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001546 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001547 EvalInfo &Info, APValue &Result) {
1548 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001549 return false;
1550
Richard Smithd62306a2011-11-10 06:34:14 +00001551 ArgVector ArgValues(Args.size());
1552 if (!EvaluateArgs(Args, ArgValues, Info))
1553 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001554
Richard Smithf6f003a2011-12-16 19:06:07 +00001555 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1556 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001557 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1558}
1559
Richard Smithd62306a2011-11-10 06:34:14 +00001560/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001561static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001562 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001563 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001564 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001565 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001566 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001567 return false;
1568
1569 ArgVector ArgValues(Args.size());
1570 if (!EvaluateArgs(Args, ArgValues, Info))
1571 return false;
1572
Richard Smithf6f003a2011-12-16 19:06:07 +00001573 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1574 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001575
1576 // If it's a delegating constructor, just delegate.
1577 if (Definition->isDelegatingConstructor()) {
1578 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1579 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1580 }
1581
1582 // Reserve space for the struct members.
1583 const CXXRecordDecl *RD = Definition->getParent();
1584 if (!RD->isUnion())
1585 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1586 std::distance(RD->field_begin(), RD->field_end()));
1587
1588 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1589
1590 unsigned BasesSeen = 0;
1591#ifndef NDEBUG
1592 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1593#endif
1594 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1595 E = Definition->init_end(); I != E; ++I) {
1596 if ((*I)->isBaseInitializer()) {
1597 QualType BaseType((*I)->getBaseClass(), 0);
1598#ifndef NDEBUG
1599 // Non-virtual base classes are initialized in the order in the class
1600 // definition. We cannot have a virtual base class for a literal type.
1601 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1602 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1603 "base class initializers not in expected order");
1604 ++BaseIt;
1605#endif
1606 LValue Subobject = This;
1607 HandleLValueDirectBase(Info, Subobject, RD,
1608 BaseType->getAsCXXRecordDecl(), &Layout);
1609 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1610 Subobject, (*I)->getInit()))
1611 return false;
1612 } else if (FieldDecl *FD = (*I)->getMember()) {
1613 LValue Subobject = This;
1614 HandleLValueMember(Info, Subobject, FD, &Layout);
1615 if (RD->isUnion()) {
1616 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001617 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1618 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001619 return false;
1620 } else if (!EvaluateConstantExpression(
1621 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001622 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001623 return false;
1624 } else {
1625 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001626 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001627 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001628 return false;
1629 }
1630 }
1631
1632 return true;
1633}
1634
Richard Smith254a73d2011-10-28 22:34:42 +00001635namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001636class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001637 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001638 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001639public:
1640
Richard Smith725810a2011-10-16 21:26:27 +00001641 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001642
1643 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001644 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001645 return true;
1646 }
1647
Peter Collingbournee9200682011-05-13 03:29:01 +00001648 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1649 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001650 return Visit(E->getResultExpr());
1651 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001652 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001653 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001654 return true;
1655 return false;
1656 }
John McCall31168b02011-06-15 23:02:42 +00001657 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001658 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001659 return true;
1660 return false;
1661 }
1662 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001663 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001664 return true;
1665 return false;
1666 }
1667
Mike Stump876387b2009-10-27 22:09:17 +00001668 // We don't want to evaluate BlockExprs multiple times, as they generate
1669 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001670 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1671 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1672 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001673 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001674 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1675 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1676 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1677 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1678 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1679 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001680 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001681 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001682 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001683 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001684 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001685 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1686 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1687 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1688 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001689 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001690 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1691 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1692 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1693 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1694 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001695 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001696 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001697 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001699 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001700
1701 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001703 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1704 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001705 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001706 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001707 return false;
1708 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001709
Peter Collingbournee9200682011-05-13 03:29:01 +00001710 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001711};
1712
John McCallc07a0c72011-02-17 10:25:35 +00001713class OpaqueValueEvaluation {
1714 EvalInfo &info;
1715 OpaqueValueExpr *opaqueValue;
1716
1717public:
1718 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1719 Expr *value)
1720 : info(info), opaqueValue(opaqueValue) {
1721
1722 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001723 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001724 this->opaqueValue = 0;
1725 return;
1726 }
John McCallc07a0c72011-02-17 10:25:35 +00001727 }
1728
1729 bool hasError() const { return opaqueValue == 0; }
1730
1731 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001732 // FIXME: This will not work for recursive constexpr functions using opaque
1733 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001734 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1735 }
1736};
1737
Mike Stump876387b2009-10-27 22:09:17 +00001738} // end anonymous namespace
1739
Eli Friedman9a156e52008-11-12 09:44:48 +00001740//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001741// Generic Evaluation
1742//===----------------------------------------------------------------------===//
1743namespace {
1744
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745// FIXME: RetTy is always bool. Remove it.
1746template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001747class ExprEvaluatorBase
1748 : public ConstStmtVisitor<Derived, RetTy> {
1749private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001750 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001751 return static_cast<Derived*>(this)->Success(V, E);
1752 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001753 RetTy DerivedValueInitialization(const Expr *E) {
1754 return static_cast<Derived*>(this)->ValueInitialization(E);
1755 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001756
1757protected:
1758 EvalInfo &Info;
1759 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1760 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1761
Richard Smith92b1ce02011-12-12 09:28:41 +00001762 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001763 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 }
1765
1766 /// Report an evaluation error. This should only be called when an error is
1767 /// first discovered. When propagating an error, just return false.
1768 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001769 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001770 return false;
1771 }
1772 bool Error(const Expr *E) {
1773 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1774 }
1775
1776 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001777
Peter Collingbournee9200682011-05-13 03:29:01 +00001778public:
1779 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1780
1781 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001782 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001783 }
1784 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001785 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001786 }
1787
1788 RetTy VisitParenExpr(const ParenExpr *E)
1789 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1790 RetTy VisitUnaryExtension(const UnaryOperator *E)
1791 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1792 RetTy VisitUnaryPlus(const UnaryOperator *E)
1793 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1794 RetTy VisitChooseExpr(const ChooseExpr *E)
1795 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1796 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1797 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001798 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1799 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001800 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1801 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001802 // We cannot create any objects for which cleanups are required, so there is
1803 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1804 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1805 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001806
Richard Smith6d6ecc32011-12-12 12:46:16 +00001807 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1808 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1809 return static_cast<Derived*>(this)->VisitCastExpr(E);
1810 }
1811 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1812 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1813 return static_cast<Derived*>(this)->VisitCastExpr(E);
1814 }
1815
Richard Smith027bf112011-11-17 22:56:20 +00001816 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1817 switch (E->getOpcode()) {
1818 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001819 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001820
1821 case BO_Comma:
1822 VisitIgnoredValue(E->getLHS());
1823 return StmtVisitorTy::Visit(E->getRHS());
1824
1825 case BO_PtrMemD:
1826 case BO_PtrMemI: {
1827 LValue Obj;
1828 if (!HandleMemberPointerAccess(Info, E, Obj))
1829 return false;
1830 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001831 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001832 return false;
1833 return DerivedSuccess(Result, E);
1834 }
1835 }
1836 }
1837
Peter Collingbournee9200682011-05-13 03:29:01 +00001838 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1839 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1840 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001841 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001842
1843 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001844 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001845 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001846
1847 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1848 }
1849
1850 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1851 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001852 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001853 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001854
Richard Smith11562c52011-10-28 17:51:58 +00001855 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001856 return StmtVisitorTy::Visit(EvalExpr);
1857 }
1858
1859 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001860 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001861 if (!Value) {
1862 const Expr *Source = E->getSourceExpr();
1863 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001864 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001865 if (Source == E) { // sanity checking.
1866 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001867 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001868 }
1869 return StmtVisitorTy::Visit(Source);
1870 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001871 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001872 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001873
Richard Smith254a73d2011-10-28 22:34:42 +00001874 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001875 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001876 QualType CalleeType = Callee->getType();
1877
Richard Smith254a73d2011-10-28 22:34:42 +00001878 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001879 LValue *This = 0, ThisVal;
1880 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001881
Richard Smithe97cbd72011-11-11 04:05:33 +00001882 // Extract function decl and 'this' pointer from the callee.
1883 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001884 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001885 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1886 // Explicit bound member calls, such as x.f() or p->g();
1887 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001888 return false;
1889 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001890 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001891 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1892 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001893 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1894 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001895 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001896 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001897 return Error(Callee);
1898
1899 FD = dyn_cast<FunctionDecl>(Member);
1900 if (!FD)
1901 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001902 } else if (CalleeType->isFunctionPointerType()) {
1903 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001904 if (!Evaluate(Call, Info, Callee))
1905 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001906
Richard Smithf57d8cb2011-12-09 22:58:01 +00001907 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1908 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001909 FD = dyn_cast_or_null<FunctionDecl>(
1910 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001911 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001912 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001913
1914 // Overloaded operator calls to member functions are represented as normal
1915 // calls with '*this' as the first argument.
1916 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1917 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001918 // FIXME: When selecting an implicit conversion for an overloaded
1919 // operator delete, we sometimes try to evaluate calls to conversion
1920 // operators without a 'this' parameter!
1921 if (Args.empty())
1922 return Error(E);
1923
Richard Smithe97cbd72011-11-11 04:05:33 +00001924 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1925 return false;
1926 This = &ThisVal;
1927 Args = Args.slice(1);
1928 }
1929
1930 // Don't call function pointers which have been cast to some other type.
1931 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001932 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001933 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001934 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001935
Richard Smith357362d2011-12-13 06:39:58 +00001936 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00001937 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001938 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001939
Richard Smith357362d2011-12-13 06:39:58 +00001940 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00001941 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001942 return false;
1943
1944 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001945 }
1946
Richard Smith11562c52011-10-28 17:51:58 +00001947 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1948 return StmtVisitorTy::Visit(E->getInitializer());
1949 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001950 RetTy VisitInitListExpr(const InitListExpr *E) {
1951 if (Info.getLangOpts().CPlusPlus0x) {
1952 if (E->getNumInits() == 0)
1953 return DerivedValueInitialization(E);
1954 if (E->getNumInits() == 1)
1955 return StmtVisitorTy::Visit(E->getInit(0));
1956 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001957 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001958 }
1959 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1960 return DerivedValueInitialization(E);
1961 }
1962 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1963 return DerivedValueInitialization(E);
1964 }
Richard Smith027bf112011-11-17 22:56:20 +00001965 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1966 return DerivedValueInitialization(E);
1967 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001968
Richard Smithd62306a2011-11-10 06:34:14 +00001969 /// A member expression where the object is a prvalue is itself a prvalue.
1970 RetTy VisitMemberExpr(const MemberExpr *E) {
1971 assert(!E->isArrow() && "missing call to bound member function?");
1972
1973 CCValue Val;
1974 if (!Evaluate(Val, Info, E->getBase()))
1975 return false;
1976
1977 QualType BaseTy = E->getBase()->getType();
1978
1979 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001980 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001981 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1982 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1983 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1984
1985 SubobjectDesignator Designator;
1986 Designator.addDecl(FD);
1987
Richard Smithf57d8cb2011-12-09 22:58:01 +00001988 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001989 DerivedSuccess(Val, E);
1990 }
1991
Richard Smith11562c52011-10-28 17:51:58 +00001992 RetTy VisitCastExpr(const CastExpr *E) {
1993 switch (E->getCastKind()) {
1994 default:
1995 break;
1996
1997 case CK_NoOp:
1998 return StmtVisitorTy::Visit(E->getSubExpr());
1999
2000 case CK_LValueToRValue: {
2001 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002002 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2003 return false;
2004 CCValue RVal;
2005 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2006 return false;
2007 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002008 }
2009 }
2010
Richard Smithf57d8cb2011-12-09 22:58:01 +00002011 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002012 }
2013
Richard Smith4a678122011-10-24 18:44:57 +00002014 /// Visit a value which is evaluated, but whose value is ignored.
2015 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002016 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002017 if (!Evaluate(Scratch, Info, E))
2018 Info.EvalStatus.HasSideEffects = true;
2019 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002020};
2021
2022}
2023
2024//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002025// Common base class for lvalue and temporary evaluation.
2026//===----------------------------------------------------------------------===//
2027namespace {
2028template<class Derived>
2029class LValueExprEvaluatorBase
2030 : public ExprEvaluatorBase<Derived, bool> {
2031protected:
2032 LValue &Result;
2033 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2034 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2035
2036 bool Success(APValue::LValueBase B) {
2037 Result.set(B);
2038 return true;
2039 }
2040
2041public:
2042 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2043 ExprEvaluatorBaseTy(Info), Result(Result) {}
2044
2045 bool Success(const CCValue &V, const Expr *E) {
2046 Result.setFrom(V);
2047 return true;
2048 }
Richard Smith027bf112011-11-17 22:56:20 +00002049
2050 bool CheckValidLValue() {
2051 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2052 // there are no null references, nor once-past-the-end references.
2053 // FIXME: Check for one-past-the-end array indices
2054 return Result.Base && !Result.Designator.Invalid &&
2055 !Result.Designator.OnePastTheEnd;
2056 }
2057
2058 bool VisitMemberExpr(const MemberExpr *E) {
2059 // Handle non-static data members.
2060 QualType BaseTy;
2061 if (E->isArrow()) {
2062 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2063 return false;
2064 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002065 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002066 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002067 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2068 return false;
2069 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002070 } else {
2071 if (!this->Visit(E->getBase()))
2072 return false;
2073 BaseTy = E->getBase()->getType();
2074 }
2075 // FIXME: In C++11, require the result to be a valid lvalue.
2076
2077 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2078 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002079 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002080 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2081 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2082 (void)BaseTy;
2083
2084 HandleLValueMember(this->Info, Result, FD);
2085
2086 if (FD->getType()->isReferenceType()) {
2087 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002088 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002089 RefValue))
2090 return false;
2091 return Success(RefValue, E);
2092 }
2093 return true;
2094 }
2095
2096 bool VisitBinaryOperator(const BinaryOperator *E) {
2097 switch (E->getOpcode()) {
2098 default:
2099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2100
2101 case BO_PtrMemD:
2102 case BO_PtrMemI:
2103 return HandleMemberPointerAccess(this->Info, E, Result);
2104 }
2105 }
2106
2107 bool VisitCastExpr(const CastExpr *E) {
2108 switch (E->getCastKind()) {
2109 default:
2110 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2111
2112 case CK_DerivedToBase:
2113 case CK_UncheckedDerivedToBase: {
2114 if (!this->Visit(E->getSubExpr()))
2115 return false;
2116 if (!CheckValidLValue())
2117 return false;
2118
2119 // Now figure out the necessary offset to add to the base LV to get from
2120 // the derived class to the base class.
2121 QualType Type = E->getSubExpr()->getType();
2122
2123 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2124 PathE = E->path_end(); PathI != PathE; ++PathI) {
2125 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2126 *PathI))
2127 return false;
2128 Type = (*PathI)->getType();
2129 }
2130
2131 return true;
2132 }
2133 }
2134 }
2135};
2136}
2137
2138//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002139// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002140//
2141// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2142// function designators (in C), decl references to void objects (in C), and
2143// temporaries (if building with -Wno-address-of-temporary).
2144//
2145// LValue evaluation produces values comprising a base expression of one of the
2146// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002147// - Declarations
2148// * VarDecl
2149// * FunctionDecl
2150// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002151// * CompoundLiteralExpr in C
2152// * StringLiteral
2153// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002154// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002155// * ObjCEncodeExpr
2156// * AddrLabelExpr
2157// * BlockExpr
2158// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002159// - Locals and temporaries
2160// * Any Expr, with a Frame indicating the function in which the temporary was
2161// evaluated.
2162// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002163//===----------------------------------------------------------------------===//
2164namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002165class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002166 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002167public:
Richard Smith027bf112011-11-17 22:56:20 +00002168 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2169 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002170
Richard Smith11562c52011-10-28 17:51:58 +00002171 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2172
Peter Collingbournee9200682011-05-13 03:29:01 +00002173 bool VisitDeclRefExpr(const DeclRefExpr *E);
2174 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002175 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002176 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2177 bool VisitMemberExpr(const MemberExpr *E);
2178 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2179 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2180 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2181 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002182
Peter Collingbournee9200682011-05-13 03:29:01 +00002183 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002184 switch (E->getCastKind()) {
2185 default:
Richard Smith027bf112011-11-17 22:56:20 +00002186 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002187
Eli Friedmance3e02a2011-10-11 00:13:24 +00002188 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002189 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002190 if (!Visit(E->getSubExpr()))
2191 return false;
2192 Result.Designator.setInvalid();
2193 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002194
Richard Smith027bf112011-11-17 22:56:20 +00002195 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002196 if (!Visit(E->getSubExpr()))
2197 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002198 if (!CheckValidLValue())
2199 return false;
2200 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002201 }
2202 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002203
Eli Friedman449fe542009-03-23 04:56:01 +00002204 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002205
Eli Friedman9a156e52008-11-12 09:44:48 +00002206};
2207} // end anonymous namespace
2208
Richard Smith11562c52011-10-28 17:51:58 +00002209/// Evaluate an expression as an lvalue. This can be legitimately called on
2210/// expressions which are not glvalues, in a few cases:
2211/// * function designators in C,
2212/// * "extern void" objects,
2213/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002214static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002215 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2216 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2217 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002218 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002219}
2220
Peter Collingbournee9200682011-05-13 03:29:01 +00002221bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002222 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2223 return Success(FD);
2224 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002225 return VisitVarDecl(E, VD);
2226 return Error(E);
2227}
Richard Smith733237d2011-10-24 23:14:33 +00002228
Richard Smith11562c52011-10-28 17:51:58 +00002229bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002230 if (!VD->getType()->isReferenceType()) {
2231 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002232 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002233 return true;
2234 }
Richard Smithce40ad62011-11-12 22:28:03 +00002235 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002236 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002237
Richard Smith0b0a0b62011-10-29 20:57:55 +00002238 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002239 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2240 return false;
2241 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002242}
2243
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002244bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2245 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002246 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002247 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002248 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2249
2250 Result.set(E, Info.CurrentCall);
2251 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2252 Result, E->GetTemporaryExpr());
2253 }
2254
2255 // Materialization of an lvalue temporary occurs when we need to force a copy
2256 // (for instance, if it's a bitfield).
2257 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2258 if (!Visit(E->GetTemporaryExpr()))
2259 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002260 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002261 Info.CurrentCall->Temporaries[E]))
2262 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002263 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002264 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002265}
2266
Peter Collingbournee9200682011-05-13 03:29:01 +00002267bool
2268LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002269 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2270 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2271 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002272 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002273}
2274
Peter Collingbournee9200682011-05-13 03:29:01 +00002275bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002276 // Handle static data members.
2277 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2278 VisitIgnoredValue(E->getBase());
2279 return VisitVarDecl(E, VD);
2280 }
2281
Richard Smith254a73d2011-10-28 22:34:42 +00002282 // Handle static member functions.
2283 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2284 if (MD->isStatic()) {
2285 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002286 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002287 }
2288 }
2289
Richard Smithd62306a2011-11-10 06:34:14 +00002290 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002291 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002292}
2293
Peter Collingbournee9200682011-05-13 03:29:01 +00002294bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002295 // FIXME: Deal with vectors as array subscript bases.
2296 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002297 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002298
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002299 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002300 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002301
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002302 APSInt Index;
2303 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002304 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002305 int64_t IndexValue
2306 = Index.isSigned() ? Index.getSExtValue()
2307 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002308
Richard Smith027bf112011-11-17 22:56:20 +00002309 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002310 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002311}
Eli Friedman9a156e52008-11-12 09:44:48 +00002312
Peter Collingbournee9200682011-05-13 03:29:01 +00002313bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002314 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002315 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002316}
2317
Eli Friedman9a156e52008-11-12 09:44:48 +00002318//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002319// Pointer Evaluation
2320//===----------------------------------------------------------------------===//
2321
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002322namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002323class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002324 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002325 LValue &Result;
2326
Peter Collingbournee9200682011-05-13 03:29:01 +00002327 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002328 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002329 return true;
2330 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002331public:
Mike Stump11289f42009-09-09 15:08:12 +00002332
John McCall45d55e42010-05-07 21:00:08 +00002333 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002334 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002335
Richard Smith0b0a0b62011-10-29 20:57:55 +00002336 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002337 Result.setFrom(V);
2338 return true;
2339 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002340 bool ValueInitialization(const Expr *E) {
2341 return Success((Expr*)0);
2342 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002343
John McCall45d55e42010-05-07 21:00:08 +00002344 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002345 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002346 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002347 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002348 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002349 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002350 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002351 bool VisitCallExpr(const CallExpr *E);
2352 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002353 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002354 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002355 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002356 }
Richard Smithd62306a2011-11-10 06:34:14 +00002357 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2358 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002359 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002360 Result = *Info.CurrentCall->This;
2361 return true;
2362 }
John McCallc07a0c72011-02-17 10:25:35 +00002363
Eli Friedman449fe542009-03-23 04:56:01 +00002364 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002365};
Chris Lattner05706e882008-07-11 18:11:29 +00002366} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002367
John McCall45d55e42010-05-07 21:00:08 +00002368static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002369 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002370 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002371}
2372
John McCall45d55e42010-05-07 21:00:08 +00002373bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002374 if (E->getOpcode() != BO_Add &&
2375 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002376 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattner05706e882008-07-11 18:11:29 +00002378 const Expr *PExp = E->getLHS();
2379 const Expr *IExp = E->getRHS();
2380 if (IExp->getType()->isPointerType())
2381 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002382
John McCall45d55e42010-05-07 21:00:08 +00002383 if (!EvaluatePointer(PExp, Result, Info))
2384 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002385
John McCall45d55e42010-05-07 21:00:08 +00002386 llvm::APSInt Offset;
2387 if (!EvaluateInteger(IExp, Offset, Info))
2388 return false;
2389 int64_t AdditionalOffset
2390 = Offset.isSigned() ? Offset.getSExtValue()
2391 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002392 if (E->getOpcode() == BO_Sub)
2393 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002394
Richard Smithd62306a2011-11-10 06:34:14 +00002395 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002396 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002397 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002398}
Eli Friedman9a156e52008-11-12 09:44:48 +00002399
John McCall45d55e42010-05-07 21:00:08 +00002400bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2401 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002402}
Mike Stump11289f42009-09-09 15:08:12 +00002403
Peter Collingbournee9200682011-05-13 03:29:01 +00002404bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2405 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002406
Eli Friedman847a2bc2009-12-27 05:43:15 +00002407 switch (E->getCastKind()) {
2408 default:
2409 break;
2410
John McCalle3027922010-08-25 11:45:40 +00002411 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002412 case CK_CPointerToObjCPointerCast:
2413 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002414 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002415 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2416 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2417 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002418 if (!E->getType()->isVoidPointerType()) {
2419 if (SubExpr->getType()->isVoidPointerType())
2420 CCEDiag(E, diag::note_constexpr_invalid_cast)
2421 << 3 << SubExpr->getType();
2422 else
2423 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2424 }
Richard Smith96e0c102011-11-04 02:25:55 +00002425 if (!Visit(SubExpr))
2426 return false;
2427 Result.Designator.setInvalid();
2428 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002429
Anders Carlsson18275092010-10-31 20:41:46 +00002430 case CK_DerivedToBase:
2431 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002432 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002433 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002434 if (!Result.Base && Result.Offset.isZero())
2435 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002436
Richard Smithd62306a2011-11-10 06:34:14 +00002437 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002438 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002439 QualType Type =
2440 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002441
Richard Smithd62306a2011-11-10 06:34:14 +00002442 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002443 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002444 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002445 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002446 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002447 }
2448
Anders Carlsson18275092010-10-31 20:41:46 +00002449 return true;
2450 }
2451
Richard Smith027bf112011-11-17 22:56:20 +00002452 case CK_BaseToDerived:
2453 if (!Visit(E->getSubExpr()))
2454 return false;
2455 if (!Result.Base && Result.Offset.isZero())
2456 return true;
2457 return HandleBaseToDerivedCast(Info, E, Result);
2458
Richard Smith0b0a0b62011-10-29 20:57:55 +00002459 case CK_NullToPointer:
2460 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002461
John McCalle3027922010-08-25 11:45:40 +00002462 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002463 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2464
Richard Smith0b0a0b62011-10-29 20:57:55 +00002465 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002466 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002467 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002468
John McCall45d55e42010-05-07 21:00:08 +00002469 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002470 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2471 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002472 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002473 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002474 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002475 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002476 return true;
2477 } else {
2478 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002479 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002480 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002481 }
2482 }
John McCalle3027922010-08-25 11:45:40 +00002483 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002484 if (SubExpr->isGLValue()) {
2485 if (!EvaluateLValue(SubExpr, Result, Info))
2486 return false;
2487 } else {
2488 Result.set(SubExpr, Info.CurrentCall);
2489 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2490 Info, Result, SubExpr))
2491 return false;
2492 }
Richard Smith96e0c102011-11-04 02:25:55 +00002493 // The result is a pointer to the first element of the array.
2494 Result.Designator.addIndex(0);
2495 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002496
John McCalle3027922010-08-25 11:45:40 +00002497 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002498 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002499 }
2500
Richard Smith11562c52011-10-28 17:51:58 +00002501 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002502}
Chris Lattner05706e882008-07-11 18:11:29 +00002503
Peter Collingbournee9200682011-05-13 03:29:01 +00002504bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002505 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002506 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002507
Peter Collingbournee9200682011-05-13 03:29:01 +00002508 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002509}
Chris Lattner05706e882008-07-11 18:11:29 +00002510
2511//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002512// Member Pointer Evaluation
2513//===----------------------------------------------------------------------===//
2514
2515namespace {
2516class MemberPointerExprEvaluator
2517 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2518 MemberPtr &Result;
2519
2520 bool Success(const ValueDecl *D) {
2521 Result = MemberPtr(D);
2522 return true;
2523 }
2524public:
2525
2526 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2527 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2528
2529 bool Success(const CCValue &V, const Expr *E) {
2530 Result.setFrom(V);
2531 return true;
2532 }
Richard Smith027bf112011-11-17 22:56:20 +00002533 bool ValueInitialization(const Expr *E) {
2534 return Success((const ValueDecl*)0);
2535 }
2536
2537 bool VisitCastExpr(const CastExpr *E);
2538 bool VisitUnaryAddrOf(const UnaryOperator *E);
2539};
2540} // end anonymous namespace
2541
2542static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2543 EvalInfo &Info) {
2544 assert(E->isRValue() && E->getType()->isMemberPointerType());
2545 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2546}
2547
2548bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2549 switch (E->getCastKind()) {
2550 default:
2551 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2552
2553 case CK_NullToMemberPointer:
2554 return ValueInitialization(E);
2555
2556 case CK_BaseToDerivedMemberPointer: {
2557 if (!Visit(E->getSubExpr()))
2558 return false;
2559 if (E->path_empty())
2560 return true;
2561 // Base-to-derived member pointer casts store the path in derived-to-base
2562 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2563 // the wrong end of the derived->base arc, so stagger the path by one class.
2564 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2565 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2566 PathI != PathE; ++PathI) {
2567 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2568 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2569 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002570 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002571 }
2572 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2573 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002574 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002575 return true;
2576 }
2577
2578 case CK_DerivedToBaseMemberPointer:
2579 if (!Visit(E->getSubExpr()))
2580 return false;
2581 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2582 PathE = E->path_end(); PathI != PathE; ++PathI) {
2583 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2584 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2585 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002586 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002587 }
2588 return true;
2589 }
2590}
2591
2592bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2593 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2594 // member can be formed.
2595 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2596}
2597
2598//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002599// Record Evaluation
2600//===----------------------------------------------------------------------===//
2601
2602namespace {
2603 class RecordExprEvaluator
2604 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2605 const LValue &This;
2606 APValue &Result;
2607 public:
2608
2609 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2610 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2611
2612 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002613 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002614 }
Richard Smithd62306a2011-11-10 06:34:14 +00002615
Richard Smithe97cbd72011-11-11 04:05:33 +00002616 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002617 bool VisitInitListExpr(const InitListExpr *E);
2618 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2619 };
2620}
2621
Richard Smithe97cbd72011-11-11 04:05:33 +00002622bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2623 switch (E->getCastKind()) {
2624 default:
2625 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2626
2627 case CK_ConstructorConversion:
2628 return Visit(E->getSubExpr());
2629
2630 case CK_DerivedToBase:
2631 case CK_UncheckedDerivedToBase: {
2632 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002633 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002634 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002635 if (!DerivedObject.isStruct())
2636 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002637
2638 // Derived-to-base rvalue conversion: just slice off the derived part.
2639 APValue *Value = &DerivedObject;
2640 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2641 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2642 PathE = E->path_end(); PathI != PathE; ++PathI) {
2643 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2644 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2645 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2646 RD = Base;
2647 }
2648 Result = *Value;
2649 return true;
2650 }
2651 }
2652}
2653
Richard Smithd62306a2011-11-10 06:34:14 +00002654bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2655 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2656 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2657
2658 if (RD->isUnion()) {
2659 Result = APValue(E->getInitializedFieldInUnion());
2660 if (!E->getNumInits())
2661 return true;
2662 LValue Subobject = This;
2663 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2664 &Layout);
2665 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2666 Subobject, E->getInit(0));
2667 }
2668
2669 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2670 "initializer list for class with base classes");
2671 Result = APValue(APValue::UninitStruct(), 0,
2672 std::distance(RD->field_begin(), RD->field_end()));
2673 unsigned ElementNo = 0;
2674 for (RecordDecl::field_iterator Field = RD->field_begin(),
2675 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2676 // Anonymous bit-fields are not considered members of the class for
2677 // purposes of aggregate initialization.
2678 if (Field->isUnnamedBitfield())
2679 continue;
2680
2681 LValue Subobject = This;
2682 HandleLValueMember(Info, Subobject, *Field, &Layout);
2683
2684 if (ElementNo < E->getNumInits()) {
2685 if (!EvaluateConstantExpression(
2686 Result.getStructField((*Field)->getFieldIndex()),
2687 Info, Subobject, E->getInit(ElementNo++)))
2688 return false;
2689 } else {
2690 // Perform an implicit value-initialization for members beyond the end of
2691 // the initializer list.
2692 ImplicitValueInitExpr VIE(Field->getType());
2693 if (!EvaluateConstantExpression(
2694 Result.getStructField((*Field)->getFieldIndex()),
2695 Info, Subobject, &VIE))
2696 return false;
2697 }
2698 }
2699
2700 return true;
2701}
2702
2703bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2704 const CXXConstructorDecl *FD = E->getConstructor();
2705 const FunctionDecl *Definition = 0;
2706 FD->getBody(Definition);
2707
Richard Smith357362d2011-12-13 06:39:58 +00002708 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2709 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002710
2711 // FIXME: Elide the copy/move construction wherever we can.
2712 if (E->isElidable())
2713 if (const MaterializeTemporaryExpr *ME
2714 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2715 return Visit(ME->GetTemporaryExpr());
2716
2717 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002718 return HandleConstructorCall(E, This, Args,
2719 cast<CXXConstructorDecl>(Definition), Info,
2720 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002721}
2722
2723static bool EvaluateRecord(const Expr *E, const LValue &This,
2724 APValue &Result, EvalInfo &Info) {
2725 assert(E->isRValue() && E->getType()->isRecordType() &&
2726 E->getType()->isLiteralType() &&
2727 "can't evaluate expression as a record rvalue");
2728 return RecordExprEvaluator(Info, This, Result).Visit(E);
2729}
2730
2731//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002732// Temporary Evaluation
2733//
2734// Temporaries are represented in the AST as rvalues, but generally behave like
2735// lvalues. The full-object of which the temporary is a subobject is implicitly
2736// materialized so that a reference can bind to it.
2737//===----------------------------------------------------------------------===//
2738namespace {
2739class TemporaryExprEvaluator
2740 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2741public:
2742 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2743 LValueExprEvaluatorBaseTy(Info, Result) {}
2744
2745 /// Visit an expression which constructs the value of this temporary.
2746 bool VisitConstructExpr(const Expr *E) {
2747 Result.set(E, Info.CurrentCall);
2748 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2749 Result, E);
2750 }
2751
2752 bool VisitCastExpr(const CastExpr *E) {
2753 switch (E->getCastKind()) {
2754 default:
2755 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2756
2757 case CK_ConstructorConversion:
2758 return VisitConstructExpr(E->getSubExpr());
2759 }
2760 }
2761 bool VisitInitListExpr(const InitListExpr *E) {
2762 return VisitConstructExpr(E);
2763 }
2764 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2765 return VisitConstructExpr(E);
2766 }
2767 bool VisitCallExpr(const CallExpr *E) {
2768 return VisitConstructExpr(E);
2769 }
2770};
2771} // end anonymous namespace
2772
2773/// Evaluate an expression of record type as a temporary.
2774static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002775 assert(E->isRValue() && E->getType()->isRecordType());
2776 if (!E->getType()->isLiteralType()) {
2777 if (Info.getLangOpts().CPlusPlus0x)
2778 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2779 << E->getType();
2780 else
2781 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2782 return false;
2783 }
Richard Smith027bf112011-11-17 22:56:20 +00002784 return TemporaryExprEvaluator(Info, Result).Visit(E);
2785}
2786
2787//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002788// Vector Evaluation
2789//===----------------------------------------------------------------------===//
2790
2791namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002792 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002793 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2794 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002795 public:
Mike Stump11289f42009-09-09 15:08:12 +00002796
Richard Smith2d406342011-10-22 21:10:00 +00002797 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2798 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002799
Richard Smith2d406342011-10-22 21:10:00 +00002800 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2801 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2802 // FIXME: remove this APValue copy.
2803 Result = APValue(V.data(), V.size());
2804 return true;
2805 }
Richard Smithed5165f2011-11-04 05:33:44 +00002806 bool Success(const CCValue &V, const Expr *E) {
2807 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002808 Result = V;
2809 return true;
2810 }
Richard Smith2d406342011-10-22 21:10:00 +00002811 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002812
Richard Smith2d406342011-10-22 21:10:00 +00002813 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002814 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002815 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002816 bool VisitInitListExpr(const InitListExpr *E);
2817 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002818 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002819 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002820 // shufflevector, ExtVectorElementExpr
2821 // (Note that these require implementing conversions
2822 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002823 };
2824} // end anonymous namespace
2825
2826static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002827 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002828 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002829}
2830
Richard Smith2d406342011-10-22 21:10:00 +00002831bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2832 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002833 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002834
Richard Smith161f09a2011-12-06 22:44:34 +00002835 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002836 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002837
Eli Friedmanc757de22011-03-25 00:43:55 +00002838 switch (E->getCastKind()) {
2839 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002840 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002841 if (SETy->isIntegerType()) {
2842 APSInt IntResult;
2843 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002844 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002845 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002846 } else if (SETy->isRealFloatingType()) {
2847 APFloat F(0.0);
2848 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002849 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002850 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002851 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002852 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002853 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002854
2855 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002856 SmallVector<APValue, 4> Elts(NElts, Val);
2857 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002858 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002859 default:
Richard Smith11562c52011-10-28 17:51:58 +00002860 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002861 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002862}
2863
Richard Smith2d406342011-10-22 21:10:00 +00002864bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002865VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002866 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002867 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002868 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002869
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002870 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002871 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002872
John McCall875679e2010-06-11 17:54:15 +00002873 // If a vector is initialized with a single element, that value
2874 // becomes every element of the vector, not just the first.
2875 // This is the behavior described in the IBM AltiVec documentation.
2876 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002877
2878 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002879 // vector (OpenCL 6.1.6).
2880 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002881 return Visit(E->getInit(0));
2882
John McCall875679e2010-06-11 17:54:15 +00002883 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002884 if (EltTy->isIntegerType()) {
2885 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002886 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002887 return false;
John McCall875679e2010-06-11 17:54:15 +00002888 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002889 } else {
2890 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002891 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002892 return false;
John McCall875679e2010-06-11 17:54:15 +00002893 InitValue = APValue(f);
2894 }
2895 for (unsigned i = 0; i < NumElements; i++) {
2896 Elements.push_back(InitValue);
2897 }
2898 } else {
2899 for (unsigned i = 0; i < NumElements; i++) {
2900 if (EltTy->isIntegerType()) {
2901 llvm::APSInt sInt(32);
2902 if (i < NumInits) {
2903 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002904 return false;
John McCall875679e2010-06-11 17:54:15 +00002905 } else {
2906 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2907 }
2908 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002909 } else {
John McCall875679e2010-06-11 17:54:15 +00002910 llvm::APFloat f(0.0);
2911 if (i < NumInits) {
2912 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002913 return false;
John McCall875679e2010-06-11 17:54:15 +00002914 } else {
2915 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2916 }
2917 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002918 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002919 }
2920 }
Richard Smith2d406342011-10-22 21:10:00 +00002921 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002922}
2923
Richard Smith2d406342011-10-22 21:10:00 +00002924bool
2925VectorExprEvaluator::ValueInitialization(const Expr *E) {
2926 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002927 QualType EltTy = VT->getElementType();
2928 APValue ZeroElement;
2929 if (EltTy->isIntegerType())
2930 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2931 else
2932 ZeroElement =
2933 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2934
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002935 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002936 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002937}
2938
Richard Smith2d406342011-10-22 21:10:00 +00002939bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002940 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002941 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002942}
2943
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002944//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002945// Array Evaluation
2946//===----------------------------------------------------------------------===//
2947
2948namespace {
2949 class ArrayExprEvaluator
2950 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002951 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002952 APValue &Result;
2953 public:
2954
Richard Smithd62306a2011-11-10 06:34:14 +00002955 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2956 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002957
2958 bool Success(const APValue &V, const Expr *E) {
2959 assert(V.isArray() && "Expected array type");
2960 Result = V;
2961 return true;
2962 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002963
Richard Smithd62306a2011-11-10 06:34:14 +00002964 bool ValueInitialization(const Expr *E) {
2965 const ConstantArrayType *CAT =
2966 Info.Ctx.getAsConstantArrayType(E->getType());
2967 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002968 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002969
2970 Result = APValue(APValue::UninitArray(), 0,
2971 CAT->getSize().getZExtValue());
2972 if (!Result.hasArrayFiller()) return true;
2973
2974 // Value-initialize all elements.
2975 LValue Subobject = This;
2976 Subobject.Designator.addIndex(0);
2977 ImplicitValueInitExpr VIE(CAT->getElementType());
2978 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2979 Subobject, &VIE);
2980 }
2981
Richard Smithf3e9e432011-11-07 09:22:26 +00002982 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002983 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002984 };
2985} // end anonymous namespace
2986
Richard Smithd62306a2011-11-10 06:34:14 +00002987static bool EvaluateArray(const Expr *E, const LValue &This,
2988 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002989 assert(E->isRValue() && E->getType()->isArrayType() &&
2990 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002991 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002992}
2993
2994bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2995 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2996 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002997 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002998
2999 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3000 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003001 LValue Subobject = This;
3002 Subobject.Designator.addIndex(0);
3003 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003004 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003005 I != End; ++I, ++Index) {
3006 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3007 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003008 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003009 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3010 return false;
3011 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003012
3013 if (!Result.hasArrayFiller()) return true;
3014 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003015 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3016 // but sometimes does:
3017 // struct S { constexpr S() : p(&p) {} void *p; };
3018 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003019 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003020 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003021}
3022
Richard Smith027bf112011-11-17 22:56:20 +00003023bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3024 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3025 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003026 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003027
3028 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3029 if (!Result.hasArrayFiller())
3030 return true;
3031
3032 const CXXConstructorDecl *FD = E->getConstructor();
3033 const FunctionDecl *Definition = 0;
3034 FD->getBody(Definition);
3035
Richard Smith357362d2011-12-13 06:39:58 +00003036 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3037 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003038
3039 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3040 // but sometimes does:
3041 // struct S { constexpr S() : p(&p) {} void *p; };
3042 // S s[10];
3043 LValue Subobject = This;
3044 Subobject.Designator.addIndex(0);
3045 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003046 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003047 cast<CXXConstructorDecl>(Definition),
3048 Info, Result.getArrayFiller());
3049}
3050
Richard Smithf3e9e432011-11-07 09:22:26 +00003051//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003052// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003053//
3054// As a GNU extension, we support casting pointers to sufficiently-wide integer
3055// types and back in constant folding. Integer values are thus represented
3056// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003057//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003058
3059namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003060class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003061 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003062 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003063public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003064 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003065 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003066
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003067 bool Success(const llvm::APSInt &SI, const Expr *E) {
3068 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003069 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003070 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003071 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003072 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003073 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003074 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003075 return true;
3076 }
3077
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003078 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003079 assert(E->getType()->isIntegralOrEnumerationType() &&
3080 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003081 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003082 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003083 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003084 Result.getInt().setIsUnsigned(
3085 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003086 return true;
3087 }
3088
3089 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003090 assert(E->getType()->isIntegralOrEnumerationType() &&
3091 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003092 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003093 return true;
3094 }
3095
Ken Dyckdbc01912011-03-11 02:13:43 +00003096 bool Success(CharUnits Size, const Expr *E) {
3097 return Success(Size.getQuantity(), E);
3098 }
3099
Richard Smith0b0a0b62011-10-29 20:57:55 +00003100 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003101 if (V.isLValue()) {
3102 Result = V;
3103 return true;
3104 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003105 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003106 }
Mike Stump11289f42009-09-09 15:08:12 +00003107
Richard Smith4ce706a2011-10-11 21:43:33 +00003108 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3109
Peter Collingbournee9200682011-05-13 03:29:01 +00003110 //===--------------------------------------------------------------------===//
3111 // Visitor Methods
3112 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003113
Chris Lattner7174bf32008-07-12 00:38:25 +00003114 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003115 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003116 }
3117 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003118 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003119 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003120
3121 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3122 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003123 if (CheckReferencedDecl(E, E->getDecl()))
3124 return true;
3125
3126 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003127 }
3128 bool VisitMemberExpr(const MemberExpr *E) {
3129 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003130 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003131 return true;
3132 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003133
3134 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003135 }
3136
Peter Collingbournee9200682011-05-13 03:29:01 +00003137 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003138 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003139 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003140 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003141
Peter Collingbournee9200682011-05-13 03:29:01 +00003142 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003143 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003144
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003145 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003146 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003147 }
Mike Stump11289f42009-09-09 15:08:12 +00003148
Richard Smith4ce706a2011-10-11 21:43:33 +00003149 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003150 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003151 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003152 }
3153
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003154 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003155 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003156 }
3157
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003158 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3159 return Success(E->getValue(), E);
3160 }
3161
John Wiegley6242b6a2011-04-28 00:16:57 +00003162 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3163 return Success(E->getValue(), E);
3164 }
3165
John Wiegleyf9f65842011-04-25 06:54:41 +00003166 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3167 return Success(E->getValue(), E);
3168 }
3169
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003170 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003171 bool VisitUnaryImag(const UnaryOperator *E);
3172
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003173 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003174 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003175
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003176private:
Ken Dyck160146e2010-01-27 17:10:57 +00003177 CharUnits GetAlignOfExpr(const Expr *E);
3178 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003179 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003180 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003181 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003182};
Chris Lattner05706e882008-07-11 18:11:29 +00003183} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003184
Richard Smith11562c52011-10-28 17:51:58 +00003185/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3186/// produce either the integer value or a pointer.
3187///
3188/// GCC has a heinous extension which folds casts between pointer types and
3189/// pointer-sized integral types. We support this by allowing the evaluation of
3190/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3191/// Some simple arithmetic on such values is supported (they are treated much
3192/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003193static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003194 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003195 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003196 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003197}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003198
Richard Smithf57d8cb2011-12-09 22:58:01 +00003199static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003200 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003201 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003202 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003203 if (!Val.isInt()) {
3204 // FIXME: It would be better to produce the diagnostic for casting
3205 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003206 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003207 return false;
3208 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003209 Result = Val.getInt();
3210 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003211}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003212
Richard Smithf57d8cb2011-12-09 22:58:01 +00003213/// Check whether the given declaration can be directly converted to an integral
3214/// rvalue. If not, no diagnostic is produced; there are other things we can
3215/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003216bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003217 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003218 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003219 // Check for signedness/width mismatches between E type and ECD value.
3220 bool SameSign = (ECD->getInitVal().isSigned()
3221 == E->getType()->isSignedIntegerOrEnumerationType());
3222 bool SameWidth = (ECD->getInitVal().getBitWidth()
3223 == Info.Ctx.getIntWidth(E->getType()));
3224 if (SameSign && SameWidth)
3225 return Success(ECD->getInitVal(), E);
3226 else {
3227 // Get rid of mismatch (otherwise Success assertions will fail)
3228 // by computing a new value matching the type of E.
3229 llvm::APSInt Val = ECD->getInitVal();
3230 if (!SameSign)
3231 Val.setIsSigned(!ECD->getInitVal().isSigned());
3232 if (!SameWidth)
3233 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3234 return Success(Val, E);
3235 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003236 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003237 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003238}
3239
Chris Lattner86ee2862008-10-06 06:40:35 +00003240/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3241/// as GCC.
3242static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3243 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003244 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003245 enum gcc_type_class {
3246 no_type_class = -1,
3247 void_type_class, integer_type_class, char_type_class,
3248 enumeral_type_class, boolean_type_class,
3249 pointer_type_class, reference_type_class, offset_type_class,
3250 real_type_class, complex_type_class,
3251 function_type_class, method_type_class,
3252 record_type_class, union_type_class,
3253 array_type_class, string_type_class,
3254 lang_type_class
3255 };
Mike Stump11289f42009-09-09 15:08:12 +00003256
3257 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003258 // ideal, however it is what gcc does.
3259 if (E->getNumArgs() == 0)
3260 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003261
Chris Lattner86ee2862008-10-06 06:40:35 +00003262 QualType ArgTy = E->getArg(0)->getType();
3263 if (ArgTy->isVoidType())
3264 return void_type_class;
3265 else if (ArgTy->isEnumeralType())
3266 return enumeral_type_class;
3267 else if (ArgTy->isBooleanType())
3268 return boolean_type_class;
3269 else if (ArgTy->isCharType())
3270 return string_type_class; // gcc doesn't appear to use char_type_class
3271 else if (ArgTy->isIntegerType())
3272 return integer_type_class;
3273 else if (ArgTy->isPointerType())
3274 return pointer_type_class;
3275 else if (ArgTy->isReferenceType())
3276 return reference_type_class;
3277 else if (ArgTy->isRealType())
3278 return real_type_class;
3279 else if (ArgTy->isComplexType())
3280 return complex_type_class;
3281 else if (ArgTy->isFunctionType())
3282 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003283 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003284 return record_type_class;
3285 else if (ArgTy->isUnionType())
3286 return union_type_class;
3287 else if (ArgTy->isArrayType())
3288 return array_type_class;
3289 else if (ArgTy->isUnionType())
3290 return union_type_class;
3291 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003292 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003293 return -1;
3294}
3295
John McCall95007602010-05-10 23:27:23 +00003296/// Retrieves the "underlying object type" of the given expression,
3297/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003298QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3299 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3300 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003301 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003302 } else if (const Expr *E = B.get<const Expr*>()) {
3303 if (isa<CompoundLiteralExpr>(E))
3304 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003305 }
3306
3307 return QualType();
3308}
3309
Peter Collingbournee9200682011-05-13 03:29:01 +00003310bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003311 // TODO: Perhaps we should let LLVM lower this?
3312 LValue Base;
3313 if (!EvaluatePointer(E->getArg(0), Base, Info))
3314 return false;
3315
3316 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003317 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003318
Richard Smithce40ad62011-11-12 22:28:03 +00003319 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003320 if (T.isNull() ||
3321 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003322 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003323 T->isVariablyModifiedType() ||
3324 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003325 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003326
3327 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3328 CharUnits Offset = Base.getLValueOffset();
3329
3330 if (!Offset.isNegative() && Offset <= Size)
3331 Size -= Offset;
3332 else
3333 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003334 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003335}
3336
Peter Collingbournee9200682011-05-13 03:29:01 +00003337bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003338 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003339 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003340 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003341
3342 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003343 if (TryEvaluateBuiltinObjectSize(E))
3344 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003345
Eric Christopher99469702010-01-19 22:58:35 +00003346 // If evaluating the argument has side-effects we can't determine
3347 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003348 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003349 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003350 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003351 return Success(0, E);
3352 }
Mike Stump876387b2009-10-27 22:09:17 +00003353
Richard Smithf57d8cb2011-12-09 22:58:01 +00003354 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003355 }
3356
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003357 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003358 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003359
Richard Smith10c7c902011-12-09 02:04:48 +00003360 case Builtin::BI__builtin_constant_p: {
3361 const Expr *Arg = E->getArg(0);
3362 QualType ArgType = Arg->getType();
3363 // __builtin_constant_p always has one operand. The rules which gcc follows
3364 // are not precisely documented, but are as follows:
3365 //
3366 // - If the operand is of integral, floating, complex or enumeration type,
3367 // and can be folded to a known value of that type, it returns 1.
3368 // - If the operand and can be folded to a pointer to the first character
3369 // of a string literal (or such a pointer cast to an integral type), it
3370 // returns 1.
3371 //
3372 // Otherwise, it returns 0.
3373 //
3374 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3375 // its support for this does not currently work.
3376 int IsConstant = 0;
3377 if (ArgType->isIntegralOrEnumerationType()) {
3378 // Note, a pointer cast to an integral type is only a constant if it is
3379 // a pointer to the first character of a string literal.
3380 Expr::EvalResult Result;
3381 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3382 APValue &V = Result.Val;
3383 if (V.getKind() == APValue::LValue) {
3384 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3385 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3386 } else {
3387 IsConstant = 1;
3388 }
3389 }
3390 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3391 IsConstant = Arg->isEvaluatable(Info.Ctx);
3392 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3393 LValue LV;
3394 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3395 // during the check.
3396 Expr::EvalStatus Status;
3397 EvalInfo SubInfo(Info.Ctx, Status);
3398 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3399 : EvaluatePointer(Arg, LV, SubInfo)) &&
3400 !Status.HasSideEffects)
3401 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3402 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3403 }
3404
3405 return Success(IsConstant, E);
3406 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003407 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003408 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003409 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003410 return Success(Operand, E);
3411 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003412
3413 case Builtin::BI__builtin_expect:
3414 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003415
3416 case Builtin::BIstrlen:
3417 case Builtin::BI__builtin_strlen:
3418 // As an extension, we support strlen() and __builtin_strlen() as constant
3419 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003420 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003421 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3422 // The string literal may have embedded null characters. Find the first
3423 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003424 StringRef Str = S->getString();
3425 StringRef::size_type Pos = Str.find(0);
3426 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003427 Str = Str.substr(0, Pos);
3428
3429 return Success(Str.size(), E);
3430 }
3431
Richard Smithf57d8cb2011-12-09 22:58:01 +00003432 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003433
3434 case Builtin::BI__atomic_is_lock_free: {
3435 APSInt SizeVal;
3436 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3437 return false;
3438
3439 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3440 // of two less than the maximum inline atomic width, we know it is
3441 // lock-free. If the size isn't a power of two, or greater than the
3442 // maximum alignment where we promote atomics, we know it is not lock-free
3443 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3444 // the answer can only be determined at runtime; for example, 16-byte
3445 // atomics have lock-free implementations on some, but not all,
3446 // x86-64 processors.
3447
3448 // Check power-of-two.
3449 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3450 if (!Size.isPowerOfTwo())
3451#if 0
3452 // FIXME: Suppress this folding until the ABI for the promotion width
3453 // settles.
3454 return Success(0, E);
3455#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003456 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003457#endif
3458
3459#if 0
3460 // Check against promotion width.
3461 // FIXME: Suppress this folding until the ABI for the promotion width
3462 // settles.
3463 unsigned PromoteWidthBits =
3464 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3465 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3466 return Success(0, E);
3467#endif
3468
3469 // Check against inlining width.
3470 unsigned InlineWidthBits =
3471 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3472 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3473 return Success(1, E);
3474
Richard Smithf57d8cb2011-12-09 22:58:01 +00003475 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003476 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003477 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003478}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003479
Richard Smith8b3497e2011-10-31 01:37:14 +00003480static bool HasSameBase(const LValue &A, const LValue &B) {
3481 if (!A.getLValueBase())
3482 return !B.getLValueBase();
3483 if (!B.getLValueBase())
3484 return false;
3485
Richard Smithce40ad62011-11-12 22:28:03 +00003486 if (A.getLValueBase().getOpaqueValue() !=
3487 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003488 const Decl *ADecl = GetLValueBaseDecl(A);
3489 if (!ADecl)
3490 return false;
3491 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003492 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003493 return false;
3494 }
3495
3496 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003497 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003498}
3499
Chris Lattnere13042c2008-07-11 19:10:17 +00003500bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003501 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003502 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003503
John McCalle3027922010-08-25 11:45:40 +00003504 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003505 VisitIgnoredValue(E->getLHS());
3506 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003507 }
3508
3509 if (E->isLogicalOp()) {
3510 // These need to be handled specially because the operands aren't
3511 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003512 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003513
Richard Smith11562c52011-10-28 17:51:58 +00003514 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003515 // We were able to evaluate the LHS, see if we can get away with not
3516 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003517 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003518 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003519
Richard Smith11562c52011-10-28 17:51:58 +00003520 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003521 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003522 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003523 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003524 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003525 }
3526 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003527 // FIXME: If both evaluations fail, we should produce the diagnostic from
3528 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3529 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003530 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003531 // We can't evaluate the LHS; however, sometimes the result
3532 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003533 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003534 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003535 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003536 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003537
3538 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003539 }
3540 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003541 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003542
Eli Friedman5a332ea2008-11-13 06:09:17 +00003543 return false;
3544 }
3545
Anders Carlssonacc79812008-11-16 07:17:21 +00003546 QualType LHSTy = E->getLHS()->getType();
3547 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003548
3549 if (LHSTy->isAnyComplexType()) {
3550 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003551 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003552
3553 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3554 return false;
3555
3556 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3557 return false;
3558
3559 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003560 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003561 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003562 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003563 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3564
John McCalle3027922010-08-25 11:45:40 +00003565 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003566 return Success((CR_r == APFloat::cmpEqual &&
3567 CR_i == APFloat::cmpEqual), E);
3568 else {
John McCalle3027922010-08-25 11:45:40 +00003569 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003570 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003571 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003572 CR_r == APFloat::cmpLessThan ||
3573 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003574 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003575 CR_i == APFloat::cmpLessThan ||
3576 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003577 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003578 } else {
John McCalle3027922010-08-25 11:45:40 +00003579 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003580 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3581 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3582 else {
John McCalle3027922010-08-25 11:45:40 +00003583 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003584 "Invalid compex comparison.");
3585 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3586 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3587 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003588 }
3589 }
Mike Stump11289f42009-09-09 15:08:12 +00003590
Anders Carlssonacc79812008-11-16 07:17:21 +00003591 if (LHSTy->isRealFloatingType() &&
3592 RHSTy->isRealFloatingType()) {
3593 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003594
Anders Carlssonacc79812008-11-16 07:17:21 +00003595 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3596 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003597
Anders Carlssonacc79812008-11-16 07:17:21 +00003598 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3599 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003600
Anders Carlssonacc79812008-11-16 07:17:21 +00003601 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003602
Anders Carlssonacc79812008-11-16 07:17:21 +00003603 switch (E->getOpcode()) {
3604 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003605 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003606 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003607 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003608 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003609 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003610 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003611 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003612 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003613 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003614 E);
John McCalle3027922010-08-25 11:45:40 +00003615 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003616 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003617 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003618 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003619 || CR == APFloat::cmpLessThan
3620 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003621 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003622 }
Mike Stump11289f42009-09-09 15:08:12 +00003623
Eli Friedmana38da572009-04-28 19:17:36 +00003624 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003625 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003626 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003627 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3628 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003629
John McCall45d55e42010-05-07 21:00:08 +00003630 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003631 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3632 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003633
Richard Smith8b3497e2011-10-31 01:37:14 +00003634 // Reject differing bases from the normal codepath; we special-case
3635 // comparisons to null.
3636 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003637 // Inequalities and subtractions between unrelated pointers have
3638 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003639 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003640 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003641 // A constant address may compare equal to the address of a symbol.
3642 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003643 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003644 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3645 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003646 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003647 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003648 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003649 // distinct. However, we do know that the address of a literal will be
3650 // non-null.
3651 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3652 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003653 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003654 // We can't tell whether weak symbols will end up pointing to the same
3655 // object.
3656 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003657 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003658 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003659 // (Note that clang defaults to -fmerge-all-constants, which can
3660 // lead to inconsistent results for comparisons involving the address
3661 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003662 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003663 }
Eli Friedman64004332009-03-23 04:38:34 +00003664
Richard Smithf3e9e432011-11-07 09:22:26 +00003665 // FIXME: Implement the C++11 restrictions:
3666 // - Pointer subtractions must be on elements of the same array.
3667 // - Pointer comparisons must be between members with the same access.
3668
John McCalle3027922010-08-25 11:45:40 +00003669 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003670 QualType Type = E->getLHS()->getType();
3671 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003672
Richard Smithd62306a2011-11-10 06:34:14 +00003673 CharUnits ElementSize;
3674 if (!HandleSizeof(Info, ElementType, ElementSize))
3675 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003676
Richard Smithd62306a2011-11-10 06:34:14 +00003677 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003678 RHSValue.getLValueOffset();
3679 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003680 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003681
3682 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3683 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3684 switch (E->getOpcode()) {
3685 default: llvm_unreachable("missing comparison operator");
3686 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3687 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3688 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3689 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3690 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3691 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003692 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003693 }
3694 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003695 if (!LHSTy->isIntegralOrEnumerationType() ||
3696 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003697 // We can't continue from here for non-integral types.
3698 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003699 }
3700
Anders Carlsson9c181652008-07-08 14:35:21 +00003701 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003702 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003703 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003704 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003705
Richard Smith11562c52011-10-28 17:51:58 +00003706 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003707 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003708 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003709
3710 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003711 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003712 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3713 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003714 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003715 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003716 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003717 LHSVal.getLValueOffset() -= AdditionalOffset;
3718 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003719 return true;
3720 }
3721
3722 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003723 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003724 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003725 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3726 LHSVal.getInt().getZExtValue());
3727 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003728 return true;
3729 }
3730
3731 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003732 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003733 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003734
Richard Smith11562c52011-10-28 17:51:58 +00003735 APSInt &LHS = LHSVal.getInt();
3736 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003737
Anders Carlsson9c181652008-07-08 14:35:21 +00003738 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003739 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003740 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003741 case BO_Mul: return Success(LHS * RHS, E);
3742 case BO_Add: return Success(LHS + RHS, E);
3743 case BO_Sub: return Success(LHS - RHS, E);
3744 case BO_And: return Success(LHS & RHS, E);
3745 case BO_Xor: return Success(LHS ^ RHS, E);
3746 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003747 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003748 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003749 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003750 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003751 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003752 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003753 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003754 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003755 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003756 // During constant-folding, a negative shift is an opposite shift.
3757 if (RHS.isSigned() && RHS.isNegative()) {
3758 RHS = -RHS;
3759 goto shift_right;
3760 }
3761
3762 shift_left:
3763 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003764 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3765 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003766 }
John McCalle3027922010-08-25 11:45:40 +00003767 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003768 // During constant-folding, a negative shift is an opposite shift.
3769 if (RHS.isSigned() && RHS.isNegative()) {
3770 RHS = -RHS;
3771 goto shift_left;
3772 }
3773
3774 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003775 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003776 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3777 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
Richard Smith11562c52011-10-28 17:51:58 +00003780 case BO_LT: return Success(LHS < RHS, E);
3781 case BO_GT: return Success(LHS > RHS, E);
3782 case BO_LE: return Success(LHS <= RHS, E);
3783 case BO_GE: return Success(LHS >= RHS, E);
3784 case BO_EQ: return Success(LHS == RHS, E);
3785 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003786 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003787}
3788
Ken Dyck160146e2010-01-27 17:10:57 +00003789CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003790 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3791 // the result is the size of the referenced type."
3792 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3793 // result shall be the alignment of the referenced type."
3794 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3795 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003796
3797 // __alignof is defined to return the preferred alignment.
3798 return Info.Ctx.toCharUnitsFromBits(
3799 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003800}
3801
Ken Dyck160146e2010-01-27 17:10:57 +00003802CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003803 E = E->IgnoreParens();
3804
3805 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003806 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003808 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3809 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003810
Chris Lattner68061312009-01-24 21:53:27 +00003811 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003812 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3813 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003814
Chris Lattner24aeeab2009-01-24 21:09:06 +00003815 return GetAlignOfType(E->getType());
3816}
3817
3818
Peter Collingbournee190dee2011-03-11 19:24:49 +00003819/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3820/// a result as the expression's type.
3821bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3822 const UnaryExprOrTypeTraitExpr *E) {
3823 switch(E->getKind()) {
3824 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003825 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003826 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003827 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003828 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003829 }
Eli Friedman64004332009-03-23 04:38:34 +00003830
Peter Collingbournee190dee2011-03-11 19:24:49 +00003831 case UETT_VecStep: {
3832 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003833
Peter Collingbournee190dee2011-03-11 19:24:49 +00003834 if (Ty->isVectorType()) {
3835 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003836
Peter Collingbournee190dee2011-03-11 19:24:49 +00003837 // The vec_step built-in functions that take a 3-component
3838 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3839 if (n == 3)
3840 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003841
Peter Collingbournee190dee2011-03-11 19:24:49 +00003842 return Success(n, E);
3843 } else
3844 return Success(1, E);
3845 }
3846
3847 case UETT_SizeOf: {
3848 QualType SrcTy = E->getTypeOfArgument();
3849 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3850 // the result is the size of the referenced type."
3851 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3852 // result shall be the alignment of the referenced type."
3853 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3854 SrcTy = Ref->getPointeeType();
3855
Richard Smithd62306a2011-11-10 06:34:14 +00003856 CharUnits Sizeof;
3857 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003858 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003859 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003860 }
3861 }
3862
3863 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003864 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003865}
3866
Peter Collingbournee9200682011-05-13 03:29:01 +00003867bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003868 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003869 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003870 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003871 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003872 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003873 for (unsigned i = 0; i != n; ++i) {
3874 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3875 switch (ON.getKind()) {
3876 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003877 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003878 APSInt IdxResult;
3879 if (!EvaluateInteger(Idx, IdxResult, Info))
3880 return false;
3881 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3882 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003883 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003884 CurrentType = AT->getElementType();
3885 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3886 Result += IdxResult.getSExtValue() * ElementSize;
3887 break;
3888 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003889
Douglas Gregor882211c2010-04-28 22:16:22 +00003890 case OffsetOfExpr::OffsetOfNode::Field: {
3891 FieldDecl *MemberDecl = ON.getField();
3892 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003893 if (!RT)
3894 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003895 RecordDecl *RD = RT->getDecl();
3896 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003897 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003898 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003899 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003900 CurrentType = MemberDecl->getType().getNonReferenceType();
3901 break;
3902 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003903
Douglas Gregor882211c2010-04-28 22:16:22 +00003904 case OffsetOfExpr::OffsetOfNode::Identifier:
3905 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003906 return Error(OOE);
3907
Douglas Gregord1702062010-04-29 00:18:15 +00003908 case OffsetOfExpr::OffsetOfNode::Base: {
3909 CXXBaseSpecifier *BaseSpec = ON.getBase();
3910 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003911 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003912
3913 // Find the layout of the class whose base we are looking into.
3914 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003915 if (!RT)
3916 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003917 RecordDecl *RD = RT->getDecl();
3918 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3919
3920 // Find the base class itself.
3921 CurrentType = BaseSpec->getType();
3922 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3923 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003924 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003925
3926 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003927 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003928 break;
3929 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003930 }
3931 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003932 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003933}
3934
Chris Lattnere13042c2008-07-11 19:10:17 +00003935bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003936 switch (E->getOpcode()) {
3937 default:
3938 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3939 // See C99 6.6p3.
3940 return Error(E);
3941 case UO_Extension:
3942 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3943 // If so, we could clear the diagnostic ID.
3944 return Visit(E->getSubExpr());
3945 case UO_Plus:
3946 // The result is just the value.
3947 return Visit(E->getSubExpr());
3948 case UO_Minus: {
3949 if (!Visit(E->getSubExpr()))
3950 return false;
3951 if (!Result.isInt()) return Error(E);
3952 return Success(-Result.getInt(), E);
3953 }
3954 case UO_Not: {
3955 if (!Visit(E->getSubExpr()))
3956 return false;
3957 if (!Result.isInt()) return Error(E);
3958 return Success(~Result.getInt(), E);
3959 }
3960 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003961 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003962 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003963 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003964 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003965 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003966 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003967}
Mike Stump11289f42009-09-09 15:08:12 +00003968
Chris Lattner477c4be2008-07-12 01:15:53 +00003969/// HandleCast - This is used to evaluate implicit or explicit casts where the
3970/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003971bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3972 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003973 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003974 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003975
Eli Friedmanc757de22011-03-25 00:43:55 +00003976 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003977 case CK_BaseToDerived:
3978 case CK_DerivedToBase:
3979 case CK_UncheckedDerivedToBase:
3980 case CK_Dynamic:
3981 case CK_ToUnion:
3982 case CK_ArrayToPointerDecay:
3983 case CK_FunctionToPointerDecay:
3984 case CK_NullToPointer:
3985 case CK_NullToMemberPointer:
3986 case CK_BaseToDerivedMemberPointer:
3987 case CK_DerivedToBaseMemberPointer:
3988 case CK_ConstructorConversion:
3989 case CK_IntegralToPointer:
3990 case CK_ToVoid:
3991 case CK_VectorSplat:
3992 case CK_IntegralToFloating:
3993 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003994 case CK_CPointerToObjCPointerCast:
3995 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003996 case CK_AnyPointerToBlockPointerCast:
3997 case CK_ObjCObjectLValueCast:
3998 case CK_FloatingRealToComplex:
3999 case CK_FloatingComplexToReal:
4000 case CK_FloatingComplexCast:
4001 case CK_FloatingComplexToIntegralComplex:
4002 case CK_IntegralRealToComplex:
4003 case CK_IntegralComplexCast:
4004 case CK_IntegralComplexToFloatingComplex:
4005 llvm_unreachable("invalid cast kind for integral value");
4006
Eli Friedman9faf2f92011-03-25 19:07:11 +00004007 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004008 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004009 case CK_LValueBitCast:
4010 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004011 case CK_ARCProduceObject:
4012 case CK_ARCConsumeObject:
4013 case CK_ARCReclaimReturnedObject:
4014 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004015 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004016
4017 case CK_LValueToRValue:
4018 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004019 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004020
4021 case CK_MemberPointerToBoolean:
4022 case CK_PointerToBoolean:
4023 case CK_IntegralToBoolean:
4024 case CK_FloatingToBoolean:
4025 case CK_FloatingComplexToBoolean:
4026 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004027 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004028 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004029 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004030 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004031 }
4032
Eli Friedmanc757de22011-03-25 00:43:55 +00004033 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004034 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004035 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004036
Eli Friedman742421e2009-02-20 01:15:07 +00004037 if (!Result.isInt()) {
4038 // Only allow casts of lvalues if they are lossless.
4039 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4040 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004041
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004042 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004043 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045
Eli Friedmanc757de22011-03-25 00:43:55 +00004046 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004047 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4048
John McCall45d55e42010-05-07 21:00:08 +00004049 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004050 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004051 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004052
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004053 if (LV.getLValueBase()) {
4054 // Only allow based lvalue casts if they are lossless.
4055 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004056 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004057
Richard Smithcf74da72011-11-16 07:18:12 +00004058 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004059 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004060 return true;
4061 }
4062
Ken Dyck02990832010-01-15 12:37:54 +00004063 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4064 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004065 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004066 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004067
Eli Friedmanc757de22011-03-25 00:43:55 +00004068 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004069 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004070 if (!EvaluateComplex(SubExpr, C, Info))
4071 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004072 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004073 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004074
Eli Friedmanc757de22011-03-25 00:43:55 +00004075 case CK_FloatingToIntegral: {
4076 APFloat F(0.0);
4077 if (!EvaluateFloat(SubExpr, F, Info))
4078 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004079
Richard Smith357362d2011-12-13 06:39:58 +00004080 APSInt Value;
4081 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4082 return false;
4083 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004084 }
4085 }
Mike Stump11289f42009-09-09 15:08:12 +00004086
Eli Friedmanc757de22011-03-25 00:43:55 +00004087 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004088 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004089}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004090
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004091bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4092 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004093 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004094 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4095 return false;
4096 if (!LV.isComplexInt())
4097 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004098 return Success(LV.getComplexIntReal(), E);
4099 }
4100
4101 return Visit(E->getSubExpr());
4102}
4103
Eli Friedman4e7a2412009-02-27 04:45:43 +00004104bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004105 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004106 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004107 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4108 return false;
4109 if (!LV.isComplexInt())
4110 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004111 return Success(LV.getComplexIntImag(), E);
4112 }
4113
Richard Smith4a678122011-10-24 18:44:57 +00004114 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004115 return Success(0, E);
4116}
4117
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004118bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4119 return Success(E->getPackLength(), E);
4120}
4121
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004122bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4123 return Success(E->getValue(), E);
4124}
4125
Chris Lattner05706e882008-07-11 18:11:29 +00004126//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004127// Float Evaluation
4128//===----------------------------------------------------------------------===//
4129
4130namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004131class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004132 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004133 APFloat &Result;
4134public:
4135 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004136 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004137
Richard Smith0b0a0b62011-10-29 20:57:55 +00004138 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004139 Result = V.getFloat();
4140 return true;
4141 }
Eli Friedman24c01542008-08-22 00:06:13 +00004142
Richard Smith4ce706a2011-10-11 21:43:33 +00004143 bool ValueInitialization(const Expr *E) {
4144 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4145 return true;
4146 }
4147
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004148 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004149
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004150 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004151 bool VisitBinaryOperator(const BinaryOperator *E);
4152 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004153 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004154
John McCallb1fb0d32010-05-07 22:08:54 +00004155 bool VisitUnaryReal(const UnaryOperator *E);
4156 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004157
John McCallb1fb0d32010-05-07 22:08:54 +00004158 // FIXME: Missing: array subscript of vector, member of vector,
4159 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004160};
4161} // end anonymous namespace
4162
4163static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004164 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004165 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004166}
4167
Jay Foad39c79802011-01-12 09:06:06 +00004168static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004169 QualType ResultTy,
4170 const Expr *Arg,
4171 bool SNaN,
4172 llvm::APFloat &Result) {
4173 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4174 if (!S) return false;
4175
4176 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4177
4178 llvm::APInt fill;
4179
4180 // Treat empty strings as if they were zero.
4181 if (S->getString().empty())
4182 fill = llvm::APInt(32, 0);
4183 else if (S->getString().getAsInteger(0, fill))
4184 return false;
4185
4186 if (SNaN)
4187 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4188 else
4189 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4190 return true;
4191}
4192
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004193bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004194 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004195 default:
4196 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4197
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004198 case Builtin::BI__builtin_huge_val:
4199 case Builtin::BI__builtin_huge_valf:
4200 case Builtin::BI__builtin_huge_vall:
4201 case Builtin::BI__builtin_inf:
4202 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004203 case Builtin::BI__builtin_infl: {
4204 const llvm::fltSemantics &Sem =
4205 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004206 Result = llvm::APFloat::getInf(Sem);
4207 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004208 }
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall16291492010-02-28 13:00:19 +00004210 case Builtin::BI__builtin_nans:
4211 case Builtin::BI__builtin_nansf:
4212 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004213 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4214 true, Result))
4215 return Error(E);
4216 return true;
John McCall16291492010-02-28 13:00:19 +00004217
Chris Lattner0b7282e2008-10-06 06:31:58 +00004218 case Builtin::BI__builtin_nan:
4219 case Builtin::BI__builtin_nanf:
4220 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004221 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004222 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004223 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4224 false, Result))
4225 return Error(E);
4226 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004227
4228 case Builtin::BI__builtin_fabs:
4229 case Builtin::BI__builtin_fabsf:
4230 case Builtin::BI__builtin_fabsl:
4231 if (!EvaluateFloat(E->getArg(0), Result, Info))
4232 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004233
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004234 if (Result.isNegative())
4235 Result.changeSign();
4236 return true;
4237
Mike Stump11289f42009-09-09 15:08:12 +00004238 case Builtin::BI__builtin_copysign:
4239 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004240 case Builtin::BI__builtin_copysignl: {
4241 APFloat RHS(0.);
4242 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4243 !EvaluateFloat(E->getArg(1), RHS, Info))
4244 return false;
4245 Result.copySign(RHS);
4246 return true;
4247 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004248 }
4249}
4250
John McCallb1fb0d32010-05-07 22:08:54 +00004251bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004252 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4253 ComplexValue CV;
4254 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4255 return false;
4256 Result = CV.FloatReal;
4257 return true;
4258 }
4259
4260 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004261}
4262
4263bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004264 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4265 ComplexValue CV;
4266 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4267 return false;
4268 Result = CV.FloatImag;
4269 return true;
4270 }
4271
Richard Smith4a678122011-10-24 18:44:57 +00004272 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004273 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4274 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004275 return true;
4276}
4277
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004278bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004279 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004280 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004281 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004282 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004283 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004284 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4285 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004286 Result.changeSign();
4287 return true;
4288 }
4289}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004290
Eli Friedman24c01542008-08-22 00:06:13 +00004291bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004292 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4293 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004294
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004295 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004296 if (!EvaluateFloat(E->getLHS(), Result, Info))
4297 return false;
4298 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4299 return false;
4300
4301 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004302 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004303 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004304 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4305 return true;
John McCalle3027922010-08-25 11:45:40 +00004306 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004307 Result.add(RHS, APFloat::rmNearestTiesToEven);
4308 return true;
John McCalle3027922010-08-25 11:45:40 +00004309 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004310 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4311 return true;
John McCalle3027922010-08-25 11:45:40 +00004312 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004313 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4314 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004315 }
4316}
4317
4318bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4319 Result = E->getValue();
4320 return true;
4321}
4322
Peter Collingbournee9200682011-05-13 03:29:01 +00004323bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4324 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004325
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004326 switch (E->getCastKind()) {
4327 default:
Richard Smith11562c52011-10-28 17:51:58 +00004328 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004329
4330 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004331 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004332 return EvaluateInteger(SubExpr, IntResult, Info) &&
4333 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4334 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004335 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004336
4337 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004338 if (!Visit(SubExpr))
4339 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004340 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4341 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004342 }
John McCalld7646252010-11-14 08:17:51 +00004343
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004344 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004345 ComplexValue V;
4346 if (!EvaluateComplex(SubExpr, V, Info))
4347 return false;
4348 Result = V.getComplexFloatReal();
4349 return true;
4350 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004351 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004352
Richard Smithf57d8cb2011-12-09 22:58:01 +00004353 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004354}
4355
Eli Friedman24c01542008-08-22 00:06:13 +00004356//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004357// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004358//===----------------------------------------------------------------------===//
4359
4360namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004361class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004362 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004363 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004364
Anders Carlsson537969c2008-11-16 20:27:53 +00004365public:
John McCall93d91dc2010-05-07 17:22:02 +00004366 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004367 : ExprEvaluatorBaseTy(info), Result(Result) {}
4368
Richard Smith0b0a0b62011-10-29 20:57:55 +00004369 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004370 Result.setFrom(V);
4371 return true;
4372 }
Mike Stump11289f42009-09-09 15:08:12 +00004373
Anders Carlsson537969c2008-11-16 20:27:53 +00004374 //===--------------------------------------------------------------------===//
4375 // Visitor Methods
4376 //===--------------------------------------------------------------------===//
4377
Peter Collingbournee9200682011-05-13 03:29:01 +00004378 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004379
Peter Collingbournee9200682011-05-13 03:29:01 +00004380 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004381
John McCall93d91dc2010-05-07 17:22:02 +00004382 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004383 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004384 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004385};
4386} // end anonymous namespace
4387
John McCall93d91dc2010-05-07 17:22:02 +00004388static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4389 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004390 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004391 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004392}
4393
Peter Collingbournee9200682011-05-13 03:29:01 +00004394bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4395 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004396
4397 if (SubExpr->getType()->isRealFloatingType()) {
4398 Result.makeComplexFloat();
4399 APFloat &Imag = Result.FloatImag;
4400 if (!EvaluateFloat(SubExpr, Imag, Info))
4401 return false;
4402
4403 Result.FloatReal = APFloat(Imag.getSemantics());
4404 return true;
4405 } else {
4406 assert(SubExpr->getType()->isIntegerType() &&
4407 "Unexpected imaginary literal.");
4408
4409 Result.makeComplexInt();
4410 APSInt &Imag = Result.IntImag;
4411 if (!EvaluateInteger(SubExpr, Imag, Info))
4412 return false;
4413
4414 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4415 return true;
4416 }
4417}
4418
Peter Collingbournee9200682011-05-13 03:29:01 +00004419bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004420
John McCallfcef3cf2010-12-14 17:51:41 +00004421 switch (E->getCastKind()) {
4422 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004423 case CK_BaseToDerived:
4424 case CK_DerivedToBase:
4425 case CK_UncheckedDerivedToBase:
4426 case CK_Dynamic:
4427 case CK_ToUnion:
4428 case CK_ArrayToPointerDecay:
4429 case CK_FunctionToPointerDecay:
4430 case CK_NullToPointer:
4431 case CK_NullToMemberPointer:
4432 case CK_BaseToDerivedMemberPointer:
4433 case CK_DerivedToBaseMemberPointer:
4434 case CK_MemberPointerToBoolean:
4435 case CK_ConstructorConversion:
4436 case CK_IntegralToPointer:
4437 case CK_PointerToIntegral:
4438 case CK_PointerToBoolean:
4439 case CK_ToVoid:
4440 case CK_VectorSplat:
4441 case CK_IntegralCast:
4442 case CK_IntegralToBoolean:
4443 case CK_IntegralToFloating:
4444 case CK_FloatingToIntegral:
4445 case CK_FloatingToBoolean:
4446 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004447 case CK_CPointerToObjCPointerCast:
4448 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004449 case CK_AnyPointerToBlockPointerCast:
4450 case CK_ObjCObjectLValueCast:
4451 case CK_FloatingComplexToReal:
4452 case CK_FloatingComplexToBoolean:
4453 case CK_IntegralComplexToReal:
4454 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004455 case CK_ARCProduceObject:
4456 case CK_ARCConsumeObject:
4457 case CK_ARCReclaimReturnedObject:
4458 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004459 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004460
John McCallfcef3cf2010-12-14 17:51:41 +00004461 case CK_LValueToRValue:
4462 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004463 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004464
4465 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004466 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004467 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004468 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004469
4470 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004471 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004472 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004473 return false;
4474
John McCallfcef3cf2010-12-14 17:51:41 +00004475 Result.makeComplexFloat();
4476 Result.FloatImag = APFloat(Real.getSemantics());
4477 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004478 }
4479
John McCallfcef3cf2010-12-14 17:51:41 +00004480 case CK_FloatingComplexCast: {
4481 if (!Visit(E->getSubExpr()))
4482 return false;
4483
4484 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4485 QualType From
4486 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4487
Richard Smith357362d2011-12-13 06:39:58 +00004488 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4489 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004490 }
4491
4492 case CK_FloatingComplexToIntegralComplex: {
4493 if (!Visit(E->getSubExpr()))
4494 return false;
4495
4496 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4497 QualType From
4498 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4499 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004500 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4501 To, Result.IntReal) &&
4502 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4503 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004504 }
4505
4506 case CK_IntegralRealToComplex: {
4507 APSInt &Real = Result.IntReal;
4508 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4509 return false;
4510
4511 Result.makeComplexInt();
4512 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4513 return true;
4514 }
4515
4516 case CK_IntegralComplexCast: {
4517 if (!Visit(E->getSubExpr()))
4518 return false;
4519
4520 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4521 QualType From
4522 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4523
4524 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4525 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4526 return true;
4527 }
4528
4529 case CK_IntegralComplexToFloatingComplex: {
4530 if (!Visit(E->getSubExpr()))
4531 return false;
4532
4533 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4534 QualType From
4535 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4536 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004537 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4538 To, Result.FloatReal) &&
4539 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4540 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004541 }
4542 }
4543
4544 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004545 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004546}
4547
John McCall93d91dc2010-05-07 17:22:02 +00004548bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004549 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004550 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4551
John McCall93d91dc2010-05-07 17:22:02 +00004552 if (!Visit(E->getLHS()))
4553 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004554
John McCall93d91dc2010-05-07 17:22:02 +00004555 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004556 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004557 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004558
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004559 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4560 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004561 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004562 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004563 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004564 if (Result.isComplexFloat()) {
4565 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4566 APFloat::rmNearestTiesToEven);
4567 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4568 APFloat::rmNearestTiesToEven);
4569 } else {
4570 Result.getComplexIntReal() += RHS.getComplexIntReal();
4571 Result.getComplexIntImag() += RHS.getComplexIntImag();
4572 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004573 break;
John McCalle3027922010-08-25 11:45:40 +00004574 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004575 if (Result.isComplexFloat()) {
4576 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4577 APFloat::rmNearestTiesToEven);
4578 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4579 APFloat::rmNearestTiesToEven);
4580 } else {
4581 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4582 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4583 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004584 break;
John McCalle3027922010-08-25 11:45:40 +00004585 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004586 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004587 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004588 APFloat &LHS_r = LHS.getComplexFloatReal();
4589 APFloat &LHS_i = LHS.getComplexFloatImag();
4590 APFloat &RHS_r = RHS.getComplexFloatReal();
4591 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004592
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004593 APFloat Tmp = LHS_r;
4594 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4595 Result.getComplexFloatReal() = Tmp;
4596 Tmp = LHS_i;
4597 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4598 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4599
4600 Tmp = LHS_r;
4601 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4602 Result.getComplexFloatImag() = Tmp;
4603 Tmp = LHS_i;
4604 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4605 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4606 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004607 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004608 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004609 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4610 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004611 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004612 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4613 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4614 }
4615 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004616 case BO_Div:
4617 if (Result.isComplexFloat()) {
4618 ComplexValue LHS = Result;
4619 APFloat &LHS_r = LHS.getComplexFloatReal();
4620 APFloat &LHS_i = LHS.getComplexFloatImag();
4621 APFloat &RHS_r = RHS.getComplexFloatReal();
4622 APFloat &RHS_i = RHS.getComplexFloatImag();
4623 APFloat &Res_r = Result.getComplexFloatReal();
4624 APFloat &Res_i = Result.getComplexFloatImag();
4625
4626 APFloat Den = RHS_r;
4627 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4628 APFloat Tmp = RHS_i;
4629 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4630 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4631
4632 Res_r = LHS_r;
4633 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4634 Tmp = LHS_i;
4635 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4636 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4637 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4638
4639 Res_i = LHS_i;
4640 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4641 Tmp = LHS_r;
4642 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4643 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4644 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4645 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004646 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4647 return Error(E, diag::note_expr_divide_by_zero);
4648
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004649 ComplexValue LHS = Result;
4650 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4651 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4652 Result.getComplexIntReal() =
4653 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4654 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4655 Result.getComplexIntImag() =
4656 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4657 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4658 }
4659 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004660 }
4661
John McCall93d91dc2010-05-07 17:22:02 +00004662 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004663}
4664
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004665bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4666 // Get the operand value into 'Result'.
4667 if (!Visit(E->getSubExpr()))
4668 return false;
4669
4670 switch (E->getOpcode()) {
4671 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004672 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004673 case UO_Extension:
4674 return true;
4675 case UO_Plus:
4676 // The result is always just the subexpr.
4677 return true;
4678 case UO_Minus:
4679 if (Result.isComplexFloat()) {
4680 Result.getComplexFloatReal().changeSign();
4681 Result.getComplexFloatImag().changeSign();
4682 }
4683 else {
4684 Result.getComplexIntReal() = -Result.getComplexIntReal();
4685 Result.getComplexIntImag() = -Result.getComplexIntImag();
4686 }
4687 return true;
4688 case UO_Not:
4689 if (Result.isComplexFloat())
4690 Result.getComplexFloatImag().changeSign();
4691 else
4692 Result.getComplexIntImag() = -Result.getComplexIntImag();
4693 return true;
4694 }
4695}
4696
Anders Carlsson537969c2008-11-16 20:27:53 +00004697//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004698// Void expression evaluation, primarily for a cast to void on the LHS of a
4699// comma operator
4700//===----------------------------------------------------------------------===//
4701
4702namespace {
4703class VoidExprEvaluator
4704 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4705public:
4706 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4707
4708 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004709
4710 bool VisitCastExpr(const CastExpr *E) {
4711 switch (E->getCastKind()) {
4712 default:
4713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4714 case CK_ToVoid:
4715 VisitIgnoredValue(E->getSubExpr());
4716 return true;
4717 }
4718 }
4719};
4720} // end anonymous namespace
4721
4722static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4723 assert(E->isRValue() && E->getType()->isVoidType());
4724 return VoidExprEvaluator(Info).Visit(E);
4725}
4726
4727//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004728// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004729//===----------------------------------------------------------------------===//
4730
Richard Smith0b0a0b62011-10-29 20:57:55 +00004731static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004732 // In C, function designators are not lvalues, but we evaluate them as if they
4733 // are.
4734 if (E->isGLValue() || E->getType()->isFunctionType()) {
4735 LValue LV;
4736 if (!EvaluateLValue(E, LV, Info))
4737 return false;
4738 LV.moveInto(Result);
4739 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004740 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004741 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004742 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004743 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004744 return false;
John McCall45d55e42010-05-07 21:00:08 +00004745 } else if (E->getType()->hasPointerRepresentation()) {
4746 LValue LV;
4747 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004748 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004749 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004750 } else if (E->getType()->isRealFloatingType()) {
4751 llvm::APFloat F(0.0);
4752 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004753 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004754 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004755 } else if (E->getType()->isAnyComplexType()) {
4756 ComplexValue C;
4757 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004758 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004759 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004760 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004761 MemberPtr P;
4762 if (!EvaluateMemberPointer(E, P, Info))
4763 return false;
4764 P.moveInto(Result);
4765 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004766 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004767 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004768 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004769 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004770 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004771 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004772 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004773 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004774 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004775 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4776 return false;
4777 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004778 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00004779 if (Info.getLangOpts().CPlusPlus0x)
4780 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4781 << E->getType();
4782 else
4783 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00004784 if (!EvaluateVoid(E, Info))
4785 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004786 } else if (Info.getLangOpts().CPlusPlus0x) {
4787 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4788 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004789 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004790 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004791 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004792 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004793
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004794 return true;
4795}
4796
Richard Smithed5165f2011-11-04 05:33:44 +00004797/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4798/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4799/// since later initializers for an object can indirectly refer to subobjects
4800/// which were initialized earlier.
4801static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00004802 const LValue &This, const Expr *E,
4803 CheckConstantExpressionKind CCEK) {
Richard Smithed5165f2011-11-04 05:33:44 +00004804 if (E->isRValue() && E->getType()->isLiteralType()) {
4805 // Evaluate arrays and record types in-place, so that later initializers can
4806 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004807 if (E->getType()->isArrayType())
4808 return EvaluateArray(E, This, Result, Info);
4809 else if (E->getType()->isRecordType())
4810 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004811 }
4812
4813 // For any other type, in-place evaluation is unimportant.
4814 CCValue CoreConstResult;
4815 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00004816 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00004817}
4818
Richard Smithf57d8cb2011-12-09 22:58:01 +00004819/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4820/// lvalue-to-rvalue cast if it is an lvalue.
4821static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4822 CCValue Value;
4823 if (!::Evaluate(Value, Info, E))
4824 return false;
4825
4826 if (E->isGLValue()) {
4827 LValue LV;
4828 LV.setFrom(Value);
4829 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4830 return false;
4831 }
4832
4833 // Check this core constant expression is a constant expression, and if so,
4834 // convert it to one.
4835 return CheckConstantExpression(Info, E, Value, Result);
4836}
Richard Smith11562c52011-10-28 17:51:58 +00004837
Richard Smith7b553f12011-10-29 00:50:52 +00004838/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004839/// any crazy technique (that has nothing to do with language standards) that
4840/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004841/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4842/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004843bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004844 // Fast-path evaluations of integer literals, since we sometimes see files
4845 // containing vast quantities of these.
4846 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4847 Result.Val = APValue(APSInt(L->getValue(),
4848 L->getType()->isUnsignedIntegerType()));
4849 return true;
4850 }
4851
Richard Smith5686e752011-11-10 03:30:42 +00004852 // FIXME: Evaluating initializers for large arrays can cause performance
4853 // problems, and we don't use such values yet. Once we have a more efficient
4854 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004855 // The same problem affects large records.
4856 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4857 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004858 return false;
4859
Richard Smithd62306a2011-11-10 06:34:14 +00004860 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004861 EvalInfo Info(Ctx, Result);
4862 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004863}
4864
Jay Foad39c79802011-01-12 09:06:06 +00004865bool Expr::EvaluateAsBooleanCondition(bool &Result,
4866 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004867 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004868 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004869 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004870 Result);
John McCall1be1c632010-01-05 23:42:56 +00004871}
4872
Richard Smithcaf33902011-10-10 18:28:20 +00004873bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004874 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004875 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004876 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004877 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004878
Richard Smith11562c52011-10-28 17:51:58 +00004879 Result = ExprResult.Val.getInt();
4880 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004881}
4882
Jay Foad39c79802011-01-12 09:06:06 +00004883bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004884 EvalInfo Info(Ctx, Result);
4885
John McCall45d55e42010-05-07 21:00:08 +00004886 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004887 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00004888 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4889 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00004890}
4891
Richard Smithd0b4dd62011-12-19 06:19:21 +00004892bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
4893 const VarDecl *VD,
4894 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
4895 Expr::EvalStatus EStatus;
4896 EStatus.Diag = &Notes;
4897
4898 EvalInfo InitInfo(Ctx, EStatus);
4899 InitInfo.setEvaluatingDecl(VD, Value);
4900
4901 LValue LVal;
4902 LVal.set(VD);
4903
4904 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
4905 !EStatus.HasSideEffects;
4906}
4907
Richard Smith7b553f12011-10-29 00:50:52 +00004908/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4909/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004910bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004911 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004912 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004913}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004914
Jay Foad39c79802011-01-12 09:06:06 +00004915bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004916 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004917}
4918
Richard Smithcaf33902011-10-10 18:28:20 +00004919APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004920 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004921 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004922 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004923 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004924 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004925
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004926 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004927}
John McCall864e3962010-05-07 05:32:02 +00004928
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004929 bool Expr::EvalResult::isGlobalLValue() const {
4930 assert(Val.isLValue());
4931 return IsGlobalLValue(Val.getLValueBase());
4932 }
4933
4934
John McCall864e3962010-05-07 05:32:02 +00004935/// isIntegerConstantExpr - this recursive routine will test if an expression is
4936/// an integer constant expression.
4937
4938/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4939/// comma, etc
4940///
4941/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4942/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4943/// cast+dereference.
4944
4945// CheckICE - This function does the fundamental ICE checking: the returned
4946// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4947// Note that to reduce code duplication, this helper does no evaluation
4948// itself; the caller checks whether the expression is evaluatable, and
4949// in the rare cases where CheckICE actually cares about the evaluated
4950// value, it calls into Evalute.
4951//
4952// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004953// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004954// 1: This expression is not an ICE, but if it isn't evaluated, it's
4955// a legal subexpression for an ICE. This return value is used to handle
4956// the comma operator in C99 mode.
4957// 2: This expression is not an ICE, and is not a legal subexpression for one.
4958
Dan Gohman28ade552010-07-26 21:25:24 +00004959namespace {
4960
John McCall864e3962010-05-07 05:32:02 +00004961struct ICEDiag {
4962 unsigned Val;
4963 SourceLocation Loc;
4964
4965 public:
4966 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4967 ICEDiag() : Val(0) {}
4968};
4969
Dan Gohman28ade552010-07-26 21:25:24 +00004970}
4971
4972static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004973
4974static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4975 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004976 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004977 !EVResult.Val.isInt()) {
4978 return ICEDiag(2, E->getLocStart());
4979 }
4980 return NoDiag();
4981}
4982
4983static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4984 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004985 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004986 return ICEDiag(2, E->getLocStart());
4987 }
4988
4989 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004990#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004991#define STMT(Node, Base) case Expr::Node##Class:
4992#define EXPR(Node, Base)
4993#include "clang/AST/StmtNodes.inc"
4994 case Expr::PredefinedExprClass:
4995 case Expr::FloatingLiteralClass:
4996 case Expr::ImaginaryLiteralClass:
4997 case Expr::StringLiteralClass:
4998 case Expr::ArraySubscriptExprClass:
4999 case Expr::MemberExprClass:
5000 case Expr::CompoundAssignOperatorClass:
5001 case Expr::CompoundLiteralExprClass:
5002 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005003 case Expr::DesignatedInitExprClass:
5004 case Expr::ImplicitValueInitExprClass:
5005 case Expr::ParenListExprClass:
5006 case Expr::VAArgExprClass:
5007 case Expr::AddrLabelExprClass:
5008 case Expr::StmtExprClass:
5009 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005010 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005011 case Expr::CXXDynamicCastExprClass:
5012 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005013 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005014 case Expr::CXXNullPtrLiteralExprClass:
5015 case Expr::CXXThisExprClass:
5016 case Expr::CXXThrowExprClass:
5017 case Expr::CXXNewExprClass:
5018 case Expr::CXXDeleteExprClass:
5019 case Expr::CXXPseudoDestructorExprClass:
5020 case Expr::UnresolvedLookupExprClass:
5021 case Expr::DependentScopeDeclRefExprClass:
5022 case Expr::CXXConstructExprClass:
5023 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005024 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005025 case Expr::CXXTemporaryObjectExprClass:
5026 case Expr::CXXUnresolvedConstructExprClass:
5027 case Expr::CXXDependentScopeMemberExprClass:
5028 case Expr::UnresolvedMemberExprClass:
5029 case Expr::ObjCStringLiteralClass:
5030 case Expr::ObjCEncodeExprClass:
5031 case Expr::ObjCMessageExprClass:
5032 case Expr::ObjCSelectorExprClass:
5033 case Expr::ObjCProtocolExprClass:
5034 case Expr::ObjCIvarRefExprClass:
5035 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005036 case Expr::ObjCIsaExprClass:
5037 case Expr::ShuffleVectorExprClass:
5038 case Expr::BlockExprClass:
5039 case Expr::BlockDeclRefExprClass:
5040 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005041 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005042 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005043 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005044 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005045 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005046 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005047 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005048 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005049 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005050 return ICEDiag(2, E->getLocStart());
5051
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005052 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005053 case Expr::GNUNullExprClass:
5054 // GCC considers the GNU __null value to be an integral constant expression.
5055 return NoDiag();
5056
John McCall7c454bb2011-07-15 05:09:51 +00005057 case Expr::SubstNonTypeTemplateParmExprClass:
5058 return
5059 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5060
John McCall864e3962010-05-07 05:32:02 +00005061 case Expr::ParenExprClass:
5062 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005063 case Expr::GenericSelectionExprClass:
5064 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005065 case Expr::IntegerLiteralClass:
5066 case Expr::CharacterLiteralClass:
5067 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005068 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005069 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005070 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005071 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005072 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005073 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005074 return NoDiag();
5075 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005076 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005077 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5078 // constant expressions, but they can never be ICEs because an ICE cannot
5079 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005080 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005081 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005082 return CheckEvalInICE(E, Ctx);
5083 return ICEDiag(2, E->getLocStart());
5084 }
5085 case Expr::DeclRefExprClass:
5086 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5087 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005088 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005089 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5090
5091 // Parameter variables are never constants. Without this check,
5092 // getAnyInitializer() can find a default argument, which leads
5093 // to chaos.
5094 if (isa<ParmVarDecl>(D))
5095 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5096
5097 // C++ 7.1.5.1p2
5098 // A variable of non-volatile const-qualified integral or enumeration
5099 // type initialized by an ICE can be used in ICEs.
5100 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005101 if (!Dcl->getType()->isIntegralOrEnumerationType())
5102 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5103
Richard Smithd0b4dd62011-12-19 06:19:21 +00005104 const VarDecl *VD;
5105 // Look for a declaration of this variable that has an initializer, and
5106 // check whether it is an ICE.
5107 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5108 return NoDiag();
5109 else
5110 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005111 }
5112 }
5113 return ICEDiag(2, E->getLocStart());
5114 case Expr::UnaryOperatorClass: {
5115 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5116 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005117 case UO_PostInc:
5118 case UO_PostDec:
5119 case UO_PreInc:
5120 case UO_PreDec:
5121 case UO_AddrOf:
5122 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005123 // C99 6.6/3 allows increment and decrement within unevaluated
5124 // subexpressions of constant expressions, but they can never be ICEs
5125 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005126 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005127 case UO_Extension:
5128 case UO_LNot:
5129 case UO_Plus:
5130 case UO_Minus:
5131 case UO_Not:
5132 case UO_Real:
5133 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005134 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005135 }
5136
5137 // OffsetOf falls through here.
5138 }
5139 case Expr::OffsetOfExprClass: {
5140 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005141 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005142 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005143 // compliance: we should warn earlier for offsetof expressions with
5144 // array subscripts that aren't ICEs, and if the array subscripts
5145 // are ICEs, the value of the offsetof must be an integer constant.
5146 return CheckEvalInICE(E, Ctx);
5147 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005148 case Expr::UnaryExprOrTypeTraitExprClass: {
5149 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5150 if ((Exp->getKind() == UETT_SizeOf) &&
5151 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005152 return ICEDiag(2, E->getLocStart());
5153 return NoDiag();
5154 }
5155 case Expr::BinaryOperatorClass: {
5156 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5157 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005158 case BO_PtrMemD:
5159 case BO_PtrMemI:
5160 case BO_Assign:
5161 case BO_MulAssign:
5162 case BO_DivAssign:
5163 case BO_RemAssign:
5164 case BO_AddAssign:
5165 case BO_SubAssign:
5166 case BO_ShlAssign:
5167 case BO_ShrAssign:
5168 case BO_AndAssign:
5169 case BO_XorAssign:
5170 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005171 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5172 // constant expressions, but they can never be ICEs because an ICE cannot
5173 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005174 return ICEDiag(2, E->getLocStart());
5175
John McCalle3027922010-08-25 11:45:40 +00005176 case BO_Mul:
5177 case BO_Div:
5178 case BO_Rem:
5179 case BO_Add:
5180 case BO_Sub:
5181 case BO_Shl:
5182 case BO_Shr:
5183 case BO_LT:
5184 case BO_GT:
5185 case BO_LE:
5186 case BO_GE:
5187 case BO_EQ:
5188 case BO_NE:
5189 case BO_And:
5190 case BO_Xor:
5191 case BO_Or:
5192 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005193 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5194 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005195 if (Exp->getOpcode() == BO_Div ||
5196 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005197 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005198 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005199 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005200 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005201 if (REval == 0)
5202 return ICEDiag(1, E->getLocStart());
5203 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005204 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005205 if (LEval.isMinSignedValue())
5206 return ICEDiag(1, E->getLocStart());
5207 }
5208 }
5209 }
John McCalle3027922010-08-25 11:45:40 +00005210 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005211 if (Ctx.getLangOptions().C99) {
5212 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5213 // if it isn't evaluated.
5214 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5215 return ICEDiag(1, E->getLocStart());
5216 } else {
5217 // In both C89 and C++, commas in ICEs are illegal.
5218 return ICEDiag(2, E->getLocStart());
5219 }
5220 }
5221 if (LHSResult.Val >= RHSResult.Val)
5222 return LHSResult;
5223 return RHSResult;
5224 }
John McCalle3027922010-08-25 11:45:40 +00005225 case BO_LAnd:
5226 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005227 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5228 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5229 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5230 // Rare case where the RHS has a comma "side-effect"; we need
5231 // to actually check the condition to see whether the side
5232 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005233 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005234 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005235 return RHSResult;
5236 return NoDiag();
5237 }
5238
5239 if (LHSResult.Val >= RHSResult.Val)
5240 return LHSResult;
5241 return RHSResult;
5242 }
5243 }
5244 }
5245 case Expr::ImplicitCastExprClass:
5246 case Expr::CStyleCastExprClass:
5247 case Expr::CXXFunctionalCastExprClass:
5248 case Expr::CXXStaticCastExprClass:
5249 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005250 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005251 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005252 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005253 if (isa<ExplicitCastExpr>(E)) {
5254 if (const FloatingLiteral *FL
5255 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5256 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5257 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5258 APSInt IgnoredVal(DestWidth, !DestSigned);
5259 bool Ignored;
5260 // If the value does not fit in the destination type, the behavior is
5261 // undefined, so we are not required to treat it as a constant
5262 // expression.
5263 if (FL->getValue().convertToInteger(IgnoredVal,
5264 llvm::APFloat::rmTowardZero,
5265 &Ignored) & APFloat::opInvalidOp)
5266 return ICEDiag(2, E->getLocStart());
5267 return NoDiag();
5268 }
5269 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005270 switch (cast<CastExpr>(E)->getCastKind()) {
5271 case CK_LValueToRValue:
5272 case CK_NoOp:
5273 case CK_IntegralToBoolean:
5274 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005275 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005276 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005277 return ICEDiag(2, E->getLocStart());
5278 }
John McCall864e3962010-05-07 05:32:02 +00005279 }
John McCallc07a0c72011-02-17 10:25:35 +00005280 case Expr::BinaryConditionalOperatorClass: {
5281 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5282 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5283 if (CommonResult.Val == 2) return CommonResult;
5284 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5285 if (FalseResult.Val == 2) return FalseResult;
5286 if (CommonResult.Val == 1) return CommonResult;
5287 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005288 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005289 return FalseResult;
5290 }
John McCall864e3962010-05-07 05:32:02 +00005291 case Expr::ConditionalOperatorClass: {
5292 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5293 // If the condition (ignoring parens) is a __builtin_constant_p call,
5294 // then only the true side is actually considered in an integer constant
5295 // expression, and it is fully evaluated. This is an important GNU
5296 // extension. See GCC PR38377 for discussion.
5297 if (const CallExpr *CallCE
5298 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005299 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005300 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005301 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005302 !EVResult.Val.isInt()) {
5303 return ICEDiag(2, E->getLocStart());
5304 }
5305 return NoDiag();
5306 }
5307 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005308 if (CondResult.Val == 2)
5309 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005310
Richard Smithf57d8cb2011-12-09 22:58:01 +00005311 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5312 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005313
John McCall864e3962010-05-07 05:32:02 +00005314 if (TrueResult.Val == 2)
5315 return TrueResult;
5316 if (FalseResult.Val == 2)
5317 return FalseResult;
5318 if (CondResult.Val == 1)
5319 return CondResult;
5320 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5321 return NoDiag();
5322 // Rare case where the diagnostics depend on which side is evaluated
5323 // Note that if we get here, CondResult is 0, and at least one of
5324 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005325 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005326 return FalseResult;
5327 }
5328 return TrueResult;
5329 }
5330 case Expr::CXXDefaultArgExprClass:
5331 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5332 case Expr::ChooseExprClass: {
5333 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5334 }
5335 }
5336
5337 // Silence a GCC warning
5338 return ICEDiag(2, E->getLocStart());
5339}
5340
Richard Smithf57d8cb2011-12-09 22:58:01 +00005341/// Evaluate an expression as a C++11 integral constant expression.
5342static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5343 const Expr *E,
5344 llvm::APSInt *Value,
5345 SourceLocation *Loc) {
5346 if (!E->getType()->isIntegralOrEnumerationType()) {
5347 if (Loc) *Loc = E->getExprLoc();
5348 return false;
5349 }
5350
5351 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005352 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5353 Result.Diag = &Diags;
5354 EvalInfo Info(Ctx, Result);
5355
5356 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5357 if (!Diags.empty()) {
5358 IsICE = false;
5359 if (Loc) *Loc = Diags[0].first;
5360 } else if (!IsICE && Loc) {
5361 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005362 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005363
5364 if (!IsICE)
5365 return false;
5366
5367 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5368 if (Value) *Value = Result.Val.getInt();
5369 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005370}
5371
Richard Smith92b1ce02011-12-12 09:28:41 +00005372bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005373 if (Ctx.getLangOptions().CPlusPlus0x)
5374 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5375
John McCall864e3962010-05-07 05:32:02 +00005376 ICEDiag d = CheckICE(this, Ctx);
5377 if (d.Val != 0) {
5378 if (Loc) *Loc = d.Loc;
5379 return false;
5380 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005381 return true;
5382}
5383
5384bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5385 SourceLocation *Loc, bool isEvaluated) const {
5386 if (Ctx.getLangOptions().CPlusPlus0x)
5387 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5388
5389 if (!isIntegerConstantExpr(Ctx, Loc))
5390 return false;
5391 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005392 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005393 return true;
5394}