blob: 5fd710d90ec659a95da8bb9f4c1ba7054e938f6e [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 Smitha8105bc2012-01-06 16:39:00 +000079 /// Find the path length and type of the most-derived subobject in the given
80 /// path, and find the size of the containing array, if any.
81 static
82 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
83 ArrayRef<APValue::LValuePathEntry> Path,
84 uint64_t &ArraySize, QualType &Type) {
85 unsigned MostDerivedLength = 0;
86 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +000087 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +000088 if (Type->isArrayType()) {
89 const ConstantArrayType *CAT =
90 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
91 Type = CAT->getElementType();
92 ArraySize = CAT->getSize().getZExtValue();
93 MostDerivedLength = I + 1;
94 } else if (const FieldDecl *FD = getAsField(Path[I])) {
95 Type = FD->getType();
96 ArraySize = 0;
97 MostDerivedLength = I + 1;
98 } else {
Richard Smith80815602011-11-07 05:07:52 +000099 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000100 ArraySize = 0;
101 }
Richard Smith80815602011-11-07 05:07:52 +0000102 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000104 }
105
Richard Smitha8105bc2012-01-06 16:39:00 +0000106 // The order of this enum is important for diagnostics.
107 enum CheckSubobjectKind {
108 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
109 };
110
Richard Smith96e0c102011-11-04 02:25:55 +0000111 /// A path from a glvalue to a subobject of that glvalue.
112 struct SubobjectDesignator {
113 /// True if the subobject was named in a manner not supported by C++11. Such
114 /// lvalues can still be folded, but they are not core constant expressions
115 /// and we cannot perform lvalue-to-rvalue conversions on them.
116 bool Invalid : 1;
117
Richard Smitha8105bc2012-01-06 16:39:00 +0000118 /// Is this a pointer one past the end of an object?
119 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000120
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 /// The length of the path to the most-derived object of which this is a
122 /// subobject.
123 unsigned MostDerivedPathLength : 30;
124
125 /// The size of the array of which the most-derived object is an element, or
126 /// 0 if the most-derived object is not an array element.
127 uint64_t MostDerivedArraySize;
128
129 /// The type of the most derived object referred to by this address.
130 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000131
Richard Smith80815602011-11-07 05:07:52 +0000132 typedef APValue::LValuePathEntry PathEntry;
133
Richard Smith96e0c102011-11-04 02:25:55 +0000134 /// The entries on the path from the glvalue to the designated subobject.
135 SmallVector<PathEntry, 8> Entries;
136
Richard Smitha8105bc2012-01-06 16:39:00 +0000137 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 explicit SubobjectDesignator(QualType T)
140 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
141 MostDerivedArraySize(0), MostDerivedType(T) {}
142
143 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
144 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
145 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000146 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000147 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000148 ArrayRef<PathEntry> VEntries = V.getLValuePath();
149 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
150 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000151 MostDerivedPathLength =
152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
153 V.getLValuePath(), MostDerivedArraySize,
154 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000155 }
156 }
157
Richard Smith96e0c102011-11-04 02:25:55 +0000158 void setInvalid() {
159 Invalid = true;
160 Entries.clear();
161 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000162
163 /// Determine whether this is a one-past-the-end pointer.
164 bool isOnePastTheEnd() const {
165 if (IsOnePastTheEnd)
166 return true;
167 if (MostDerivedArraySize &&
168 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
169 return true;
170 return false;
171 }
172
173 /// Check that this refers to a valid subobject.
174 bool isValidSubobject() const {
175 if (Invalid)
176 return false;
177 return !isOnePastTheEnd();
178 }
179 /// Check that this refers to a valid subobject, and if not, produce a
180 /// relevant diagnostic and set the designator as invalid.
181 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
182
183 /// Update this designator to refer to the first element within this array.
184 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000185 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000187 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000188
189 // This is a most-derived object.
190 MostDerivedType = CAT->getElementType();
191 MostDerivedArraySize = CAT->getSize().getZExtValue();
192 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000193 }
194 /// Update this designator to refer to the given base or member of this
195 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000196 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000197 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000198 APValue::BaseOrMemberType Value(D, Virtual);
199 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000200 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 // If this isn't a base class, it's a new most-derived object.
203 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
204 MostDerivedType = FD->getType();
205 MostDerivedArraySize = 0;
206 MostDerivedPathLength = Entries.size();
207 }
Richard Smith96e0c102011-11-04 02:25:55 +0000208 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000210 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000212 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000214 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
217 setInvalid();
218 }
Richard Smith96e0c102011-11-04 02:25:55 +0000219 return;
220 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 // [expr.add]p4: For the purposes of these operators, a pointer to a
222 // nonarray object behaves the same as a pointer to the first element of
223 // an array of length one with the type of the object as its element type.
224 if (IsOnePastTheEnd && N == (uint64_t)-1)
225 IsOnePastTheEnd = false;
226 else if (!IsOnePastTheEnd && N == 1)
227 IsOnePastTheEnd = true;
228 else if (N != 0) {
229 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000230 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000231 }
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 };
234
Richard Smith0b0a0b62011-10-29 20:57:55 +0000235 /// A core constant value. This can be the value of any constant expression,
236 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000237 ///
238 /// For an LValue, the base and offset are stored in the APValue subobject,
239 /// but the other information is stored in the SubobjectDesignator. For all
240 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000241 class CCValue : public APValue {
242 typedef llvm::APSInt APSInt;
243 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000244 /// If the value is a reference or pointer into a parameter or temporary,
245 /// this is the corresponding call stack frame.
246 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000247 /// If the value is a reference or pointer, this is a description of how the
248 /// subobject was specified.
249 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000250 public:
Richard Smithfec09922011-11-01 16:57:24 +0000251 struct GlobalValue {};
252
Richard Smith0b0a0b62011-10-29 20:57:55 +0000253 CCValue() {}
254 explicit CCValue(const APSInt &I) : APValue(I) {}
255 explicit CCValue(const APFloat &F) : APValue(F) {}
256 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
257 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
258 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000261 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
264 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000265 CCValue(const ValueDecl *D, bool IsDerivedMember,
266 ArrayRef<const CXXRecordDecl*> Path) :
267 APValue(D, IsDerivedMember, Path) {}
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
269 APValue(LHSExpr, RHSExpr) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000270
Richard Smithfec09922011-11-01 16:57:24 +0000271 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000272 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000273 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000274 }
Richard Smith96e0c102011-11-04 02:25:55 +0000275 SubobjectDesignator &getLValueDesignator() {
276 assert(getKind() == LValue);
277 return Designator;
278 }
279 const SubobjectDesignator &getLValueDesignator() const {
280 return const_cast<CCValue*>(this)->getLValueDesignator();
281 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000282 };
283
Richard Smith254a73d2011-10-28 22:34:42 +0000284 /// A stack frame in the constexpr call stack.
285 struct CallStackFrame {
286 EvalInfo &Info;
287
288 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000289 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Richard Smithf6f003a2011-12-16 19:06:07 +0000291 /// CallLoc - The location of the call expression for this call.
292 SourceLocation CallLoc;
293
294 /// Callee - The function which was called.
295 const FunctionDecl *Callee;
296
Richard Smithd62306a2011-11-10 06:34:14 +0000297 /// This - The binding for the this pointer in this call, if any.
298 const LValue *This;
299
Richard Smith254a73d2011-10-28 22:34:42 +0000300 /// ParmBindings - Parameter bindings for this function call, indexed by
301 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000302 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000303
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000304 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
305 typedef MapTy::const_iterator temp_iterator;
306 /// Temporaries - Temporary lvalues materialized within this stack frame.
307 MapTy Temporaries;
308
Richard Smithf6f003a2011-12-16 19:06:07 +0000309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
310 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000311 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000313 };
314
Richard Smith92b1ce02011-12-12 09:28:41 +0000315 /// A partial diagnostic which we might know in advance that we are not going
316 /// to emit.
317 class OptionalDiagnostic {
318 PartialDiagnostic *Diag;
319
320 public:
321 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
322
323 template<typename T>
324 OptionalDiagnostic &operator<<(const T &v) {
325 if (Diag)
326 *Diag << v;
327 return *this;
328 }
329 };
330
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000331 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000332 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333
334 /// EvalStatus - Contains information about the evaluation.
335 Expr::EvalStatus &EvalStatus;
336
337 /// CurrentCall - The top of the constexpr call stack.
338 CallStackFrame *CurrentCall;
339
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000340 /// CallStackDepth - The number of calls in the call stack right now.
341 unsigned CallStackDepth;
342
343 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
344 /// OpaqueValues - Values used as the common expression in a
345 /// BinaryConditionalOperator.
346 MapTy OpaqueValues;
347
348 /// BottomFrame - The frame in which evaluation started. This must be
349 /// initialized last.
350 CallStackFrame BottomFrame;
351
Richard Smithd62306a2011-11-10 06:34:14 +0000352 /// EvaluatingDecl - This is the declaration whose initializer is being
353 /// evaluated, if any.
354 const VarDecl *EvaluatingDecl;
355
356 /// EvaluatingDeclValue - This is the value being constructed for the
357 /// declaration whose initializer is being evaluated, if any.
358 APValue *EvaluatingDeclValue;
359
Richard Smith357362d2011-12-13 06:39:58 +0000360 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
361 /// notes attached to it will also be stored, otherwise they will not be.
362 bool HasActiveDiagnostic;
363
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000364
365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000369
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000370 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
371 MapTy::const_iterator i = OpaqueValues.find(e);
372 if (i == OpaqueValues.end()) return 0;
373 return &i->second;
374 }
375
Richard Smithd62306a2011-11-10 06:34:14 +0000376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
377 EvaluatingDecl = VD;
378 EvaluatingDeclValue = &Value;
379 }
380
Richard Smith9a568822011-11-21 19:36:32 +0000381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
382
Richard Smith357362d2011-12-13 06:39:58 +0000383 bool CheckCallLimit(SourceLocation Loc) {
384 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
385 return true;
386 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
387 << getLangOpts().ConstexprCallDepth;
388 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000389 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000390
Richard Smith357362d2011-12-13 06:39:58 +0000391 private:
392 /// Add a diagnostic to the diagnostics list.
393 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
394 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
395 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
396 return EvalStatus.Diag->back().second;
397 }
398
Richard Smithf6f003a2011-12-16 19:06:07 +0000399 /// Add notes containing a call stack to the current point of evaluation.
400 void addCallStack(unsigned Limit);
401
Richard Smith357362d2011-12-13 06:39:58 +0000402 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000403 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
405 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000406 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000407 // If we have a prior diagnostic, it will be noting that the expression
408 // isn't a constant expression. This diagnostic is more important.
409 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000410 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000411 unsigned CallStackNotes = CallStackDepth - 1;
412 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
413 if (Limit)
414 CallStackNotes = std::min(CallStackNotes, Limit + 1);
415
Richard Smith357362d2011-12-13 06:39:58 +0000416 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000417 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000418 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
419 addDiag(Loc, DiagId);
420 addCallStack(Limit);
421 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000422 }
Richard Smith357362d2011-12-13 06:39:58 +0000423 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000424 return OptionalDiagnostic();
425 }
426
427 /// Diagnose that the evaluation does not produce a C++11 core constant
428 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
430 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000431 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000432 // Don't override a previous diagnostic.
433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
434 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000435 return Diag(Loc, DiagId, ExtraNotes);
436 }
437
438 /// Add a note to a prior diagnostic.
439 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
440 if (!HasActiveDiagnostic)
441 return OptionalDiagnostic();
442 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000443 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000444
445 /// Add a stack of notes to a prior diagnostic.
446 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
447 if (HasActiveDiagnostic) {
448 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
449 Diags.begin(), Diags.end());
450 }
451 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000452 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000453}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000454
Richard Smitha8105bc2012-01-06 16:39:00 +0000455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
456 CheckSubobjectKind CSK) {
457 if (Invalid)
458 return false;
459 if (isOnePastTheEnd()) {
460 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
461 << CSK;
462 setInvalid();
463 return false;
464 }
465 return true;
466}
467
468void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
469 const Expr *E, uint64_t N) {
470 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
471 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
472 << static_cast<int>(N) << /*array*/ 0
473 << static_cast<unsigned>(MostDerivedArraySize);
474 else
475 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
476 << static_cast<int>(N) << /*non-array*/ 1;
477 setInvalid();
478}
479
Richard Smithf6f003a2011-12-16 19:06:07 +0000480CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
481 const FunctionDecl *Callee, const LValue *This,
482 const CCValue *Arguments)
483 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
484 This(This), Arguments(Arguments) {
485 Info.CurrentCall = this;
486 ++Info.CallStackDepth;
487}
488
489CallStackFrame::~CallStackFrame() {
490 assert(Info.CurrentCall == this && "calls retired out of order");
491 --Info.CallStackDepth;
492 Info.CurrentCall = Caller;
493}
494
495/// Produce a string describing the given constexpr call.
496static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
497 unsigned ArgIndex = 0;
498 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
499 !isa<CXXConstructorDecl>(Frame->Callee);
500
501 if (!IsMemberCall)
502 Out << *Frame->Callee << '(';
503
504 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
505 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
506 if (ArgIndex > IsMemberCall)
507 Out << ", ";
508
509 const ParmVarDecl *Param = *I;
510 const CCValue &Arg = Frame->Arguments[ArgIndex];
511 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
512 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
513 else {
514 // Deliberately slice off the frame to form an APValue we can print.
515 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
516 Arg.getLValueDesignator().Entries,
Richard Smitha8105bc2012-01-06 16:39:00 +0000517 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smithf6f003a2011-12-16 19:06:07 +0000518 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
519 }
520
521 if (ArgIndex == 0 && IsMemberCall)
522 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 }
524
Richard Smithf6f003a2011-12-16 19:06:07 +0000525 Out << ')';
526}
527
528void EvalInfo::addCallStack(unsigned Limit) {
529 // Determine which calls to skip, if any.
530 unsigned ActiveCalls = CallStackDepth - 1;
531 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
532 if (Limit && Limit < ActiveCalls) {
533 SkipStart = Limit / 2 + Limit % 2;
534 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000535 }
536
Richard Smithf6f003a2011-12-16 19:06:07 +0000537 // Walk the call stack and add the diagnostics.
538 unsigned CallIdx = 0;
539 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
540 Frame = Frame->Caller, ++CallIdx) {
541 // Skip this call?
542 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
543 if (CallIdx == SkipStart) {
544 // Note that we're skipping calls.
545 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
546 << unsigned(ActiveCalls - Limit);
547 }
548 continue;
549 }
550
551 llvm::SmallVector<char, 128> Buffer;
552 llvm::raw_svector_ostream Out(Buffer);
553 describeCall(Frame, Out);
554 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
555 }
556}
557
558namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000559 struct ComplexValue {
560 private:
561 bool IsInt;
562
563 public:
564 APSInt IntReal, IntImag;
565 APFloat FloatReal, FloatImag;
566
567 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
568
569 void makeComplexFloat() { IsInt = false; }
570 bool isComplexFloat() const { return !IsInt; }
571 APFloat &getComplexFloatReal() { return FloatReal; }
572 APFloat &getComplexFloatImag() { return FloatImag; }
573
574 void makeComplexInt() { IsInt = true; }
575 bool isComplexInt() const { return IsInt; }
576 APSInt &getComplexIntReal() { return IntReal; }
577 APSInt &getComplexIntImag() { return IntImag; }
578
Richard Smith0b0a0b62011-10-29 20:57:55 +0000579 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000580 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000581 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000582 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000583 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000584 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000585 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000586 assert(v.isComplexFloat() || v.isComplexInt());
587 if (v.isComplexFloat()) {
588 makeComplexFloat();
589 FloatReal = v.getComplexFloatReal();
590 FloatImag = v.getComplexFloatImag();
591 } else {
592 makeComplexInt();
593 IntReal = v.getComplexIntReal();
594 IntImag = v.getComplexIntImag();
595 }
596 }
John McCall93d91dc2010-05-07 17:22:02 +0000597 };
John McCall45d55e42010-05-07 21:00:08 +0000598
599 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000600 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000601 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000602 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000603 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000604
Richard Smithce40ad62011-11-12 22:28:03 +0000605 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000606 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000607 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000608 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000609 SubobjectDesignator &getLValueDesignator() { return Designator; }
610 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000611
Richard Smith0b0a0b62011-10-29 20:57:55 +0000612 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000613 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000614 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000615 void setFrom(const CCValue &V) {
616 assert(V.isLValue());
617 Base = V.getLValueBase();
618 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000619 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000620 Designator = V.getLValueDesignator();
621 }
622
Richard Smithce40ad62011-11-12 22:28:03 +0000623 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
624 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000625 Offset = CharUnits::Zero();
626 Frame = F;
Richard Smitha8105bc2012-01-06 16:39:00 +0000627 Designator = SubobjectDesignator(getType(B));
628 }
629
630 // Check that this LValue is not based on a null pointer. If it is, produce
631 // a diagnostic and mark the designator as invalid.
632 bool checkNullPointer(EvalInfo &Info, const Expr *E,
633 CheckSubobjectKind CSK) {
634 if (Designator.Invalid)
635 return false;
636 if (!Base) {
637 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
638 << CSK;
639 Designator.setInvalid();
640 return false;
641 }
642 return true;
643 }
644
645 // Check this LValue refers to an object. If not, set the designator to be
646 // invalid and emit a diagnostic.
647 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
648 return checkNullPointer(Info, E, CSK) &&
649 Designator.checkSubobject(Info, E, CSK);
650 }
651
652 void addDecl(EvalInfo &Info, const Expr *E,
653 const Decl *D, bool Virtual = false) {
654 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
655 Designator.addDeclUnchecked(D, Virtual);
656 }
657 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
658 checkSubobject(Info, E, CSK_ArrayToPointer);
659 Designator.addArrayUnchecked(CAT);
660 }
661 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
662 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
663 return;
664 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000665 }
John McCall45d55e42010-05-07 21:00:08 +0000666 };
Richard Smith027bf112011-11-17 22:56:20 +0000667
668 struct MemberPtr {
669 MemberPtr() {}
670 explicit MemberPtr(const ValueDecl *Decl) :
671 DeclAndIsDerivedMember(Decl, false), Path() {}
672
673 /// The member or (direct or indirect) field referred to by this member
674 /// pointer, or 0 if this is a null member pointer.
675 const ValueDecl *getDecl() const {
676 return DeclAndIsDerivedMember.getPointer();
677 }
678 /// Is this actually a member of some type derived from the relevant class?
679 bool isDerivedMember() const {
680 return DeclAndIsDerivedMember.getInt();
681 }
682 /// Get the class which the declaration actually lives in.
683 const CXXRecordDecl *getContainingRecord() const {
684 return cast<CXXRecordDecl>(
685 DeclAndIsDerivedMember.getPointer()->getDeclContext());
686 }
687
688 void moveInto(CCValue &V) const {
689 V = CCValue(getDecl(), isDerivedMember(), Path);
690 }
691 void setFrom(const CCValue &V) {
692 assert(V.isMemberPointer());
693 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
694 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
695 Path.clear();
696 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
697 Path.insert(Path.end(), P.begin(), P.end());
698 }
699
700 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
701 /// whether the member is a member of some class derived from the class type
702 /// of the member pointer.
703 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
704 /// Path - The path of base/derived classes from the member declaration's
705 /// class (exclusive) to the class type of the member pointer (inclusive).
706 SmallVector<const CXXRecordDecl*, 4> Path;
707
708 /// Perform a cast towards the class of the Decl (either up or down the
709 /// hierarchy).
710 bool castBack(const CXXRecordDecl *Class) {
711 assert(!Path.empty());
712 const CXXRecordDecl *Expected;
713 if (Path.size() >= 2)
714 Expected = Path[Path.size() - 2];
715 else
716 Expected = getContainingRecord();
717 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
718 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
719 // if B does not contain the original member and is not a base or
720 // derived class of the class containing the original member, the result
721 // of the cast is undefined.
722 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
723 // (D::*). We consider that to be a language defect.
724 return false;
725 }
726 Path.pop_back();
727 return true;
728 }
729 /// Perform a base-to-derived member pointer cast.
730 bool castToDerived(const CXXRecordDecl *Derived) {
731 if (!getDecl())
732 return true;
733 if (!isDerivedMember()) {
734 Path.push_back(Derived);
735 return true;
736 }
737 if (!castBack(Derived))
738 return false;
739 if (Path.empty())
740 DeclAndIsDerivedMember.setInt(false);
741 return true;
742 }
743 /// Perform a derived-to-base member pointer cast.
744 bool castToBase(const CXXRecordDecl *Base) {
745 if (!getDecl())
746 return true;
747 if (Path.empty())
748 DeclAndIsDerivedMember.setInt(true);
749 if (isDerivedMember()) {
750 Path.push_back(Base);
751 return true;
752 }
753 return castBack(Base);
754 }
755 };
Richard Smith357362d2011-12-13 06:39:58 +0000756
757 /// Kinds of constant expression checking, for diagnostics.
758 enum CheckConstantExpressionKind {
759 CCEK_Constant, ///< A normal constant.
760 CCEK_ReturnValue, ///< A constexpr function return value.
761 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
762 };
John McCall93d91dc2010-05-07 17:22:02 +0000763}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000764
Richard Smith0b0a0b62011-10-29 20:57:55 +0000765static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000766static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000767 const LValue &This, const Expr *E,
768 CheckConstantExpressionKind CCEK
769 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000770static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
771static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000772static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
773 EvalInfo &Info);
774static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000776static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000777 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000778static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000779static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000780
781//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000782// Misc utilities
783//===----------------------------------------------------------------------===//
784
Richard Smithd62306a2011-11-10 06:34:14 +0000785/// Should this call expression be treated as a string literal?
786static bool IsStringLiteralCall(const CallExpr *E) {
787 unsigned Builtin = E->isBuiltinCall();
788 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
789 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
790}
791
Richard Smithce40ad62011-11-12 22:28:03 +0000792static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000793 // C++11 [expr.const]p3 An address constant expression is a prvalue core
794 // constant expression of pointer type that evaluates to...
795
796 // ... a null pointer value, or a prvalue core constant expression of type
797 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000798 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000799
Richard Smithce40ad62011-11-12 22:28:03 +0000800 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
801 // ... the address of an object with static storage duration,
802 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
803 return VD->hasGlobalStorage();
804 // ... the address of a function,
805 return isa<FunctionDecl>(D);
806 }
807
808 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000809 switch (E->getStmtClass()) {
810 default:
811 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000812 case Expr::CompoundLiteralExprClass:
813 return cast<CompoundLiteralExpr>(E)->isFileScope();
814 // A string literal has static storage duration.
815 case Expr::StringLiteralClass:
816 case Expr::PredefinedExprClass:
817 case Expr::ObjCStringLiteralClass:
818 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000819 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000820 return true;
821 case Expr::CallExprClass:
822 return IsStringLiteralCall(cast<CallExpr>(E));
823 // For GCC compatibility, &&label has static storage duration.
824 case Expr::AddrLabelExprClass:
825 return true;
826 // A Block literal expression may be used as the initialization value for
827 // Block variables at global or local static scope.
828 case Expr::BlockExprClass:
829 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
830 }
John McCall95007602010-05-10 23:27:23 +0000831}
832
Richard Smith80815602011-11-07 05:07:52 +0000833/// Check that this reference or pointer core constant expression is a valid
Richard Smitha8105bc2012-01-06 16:39:00 +0000834/// value for an address or reference constant expression. Type T should be
835/// either LValue or CCValue.
Richard Smith80815602011-11-07 05:07:52 +0000836template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000837static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000838 const T &LVal, APValue &Value,
839 CheckConstantExpressionKind CCEK) {
840 APValue::LValueBase Base = LVal.getLValueBase();
841 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
842
843 if (!IsGlobalLValue(Base)) {
844 if (Info.getLangOpts().CPlusPlus0x) {
845 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
846 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
847 << E->isGLValue() << !Designator.Entries.empty()
848 << !!VD << CCEK << VD;
849 if (VD)
850 Info.Note(VD->getLocation(), diag::note_declared_at);
851 else
852 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
853 diag::note_constexpr_temporary_here);
854 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000855 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000856 }
Richard Smith80815602011-11-07 05:07:52 +0000857 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000858 }
Richard Smith80815602011-11-07 05:07:52 +0000859
Richard Smitha8105bc2012-01-06 16:39:00 +0000860 bool IsReferenceType = E->isGLValue();
861
862 if (Designator.Invalid) {
863 // This is not a core constant expression. A diagnostic will have already
864 // been produced.
865 if (IsReferenceType)
866 return false;
867
868 // Allow this for pointers, so we can fold things like integers cast to
869 // pointers.
Richard Smith80815602011-11-07 05:07:52 +0000870 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
871 APValue::NoLValuePath());
872 return true;
873 }
874
Richard Smitha8105bc2012-01-06 16:39:00 +0000875 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
876 Designator.Entries, Designator.IsOnePastTheEnd);
877
878 // Allow address constant expressions to be past-the-end pointers. This is
879 // an extension: the standard requires them to point to an object.
880 if (!IsReferenceType)
881 return true;
882
883 // A reference constant expression must refer to an object.
884 if (!Base) {
885 // FIXME: diagnostic
886 Info.CCEDiag(E->getExprLoc());
887 return false;
888 }
889
Richard Smith357362d2011-12-13 06:39:58 +0000890 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +0000891 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +0000892 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
893 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
894 << !Designator.Entries.empty() << !!VD << VD;
895 if (VD)
896 Info.Note(VD->getLocation(), diag::note_declared_at);
897 else
898 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
899 diag::note_constexpr_temporary_here);
900 return false;
901 }
902
Richard Smith80815602011-11-07 05:07:52 +0000903 return true;
904}
905
Richard Smithfddd3842011-12-30 21:15:51 +0000906/// Check that this core constant expression is of literal type, and if not,
907/// produce an appropriate diagnostic.
908static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
909 if (!E->isRValue() || E->getType()->isLiteralType())
910 return true;
911
912 // Prvalue constant expressions must be of literal types.
913 if (Info.getLangOpts().CPlusPlus0x)
914 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
915 << E->getType();
916 else
917 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
918 return false;
919}
920
Richard Smith0b0a0b62011-10-29 20:57:55 +0000921/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000922/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000923/// If not, report an appropriate diagnostic. Does not check that the expression
924/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000925static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000926 const CCValue &CCValue, APValue &Value,
927 CheckConstantExpressionKind CCEK
928 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000929 if (!CCValue.isLValue()) {
930 Value = CCValue;
931 return true;
932 }
Richard Smith357362d2011-12-13 06:39:58 +0000933 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000934}
935
Richard Smith83c68212011-10-31 05:11:32 +0000936const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000937 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000938}
939
940static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000941 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000942}
943
Richard Smithcecf1842011-11-01 21:06:14 +0000944static bool IsWeakLValue(const LValue &Value) {
945 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000946 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000947}
948
Richard Smith027bf112011-11-17 22:56:20 +0000949static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000950 // A null base expression indicates a null pointer. These are always
951 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000952 if (!Value.getLValueBase()) {
953 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000954 return true;
955 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000956
John McCall95007602010-05-10 23:27:23 +0000957 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000958 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000959 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000960
Richard Smith027bf112011-11-17 22:56:20 +0000961 // We have a non-null base. These are generally known to be true, but if it's
962 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000963 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000964 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000965 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000966}
967
Richard Smith0b0a0b62011-10-29 20:57:55 +0000968static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000969 switch (Val.getKind()) {
970 case APValue::Uninitialized:
971 return false;
972 case APValue::Int:
973 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000974 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000975 case APValue::Float:
976 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000977 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000978 case APValue::ComplexInt:
979 Result = Val.getComplexIntReal().getBoolValue() ||
980 Val.getComplexIntImag().getBoolValue();
981 return true;
982 case APValue::ComplexFloat:
983 Result = !Val.getComplexFloatReal().isZero() ||
984 !Val.getComplexFloatImag().isZero();
985 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000986 case APValue::LValue:
987 return EvalPointerValueAsBool(Val, Result);
988 case APValue::MemberPointer:
989 Result = Val.getMemberPointerDecl();
990 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000991 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000992 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000993 case APValue::Struct:
994 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000995 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +0000996 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000997 }
998
Richard Smith11562c52011-10-28 17:51:58 +0000999 llvm_unreachable("unknown APValue kind");
1000}
1001
1002static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1003 EvalInfo &Info) {
1004 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001005 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00001006 if (!Evaluate(Val, Info, E))
1007 return false;
1008 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001009}
1010
Richard Smith357362d2011-12-13 06:39:58 +00001011template<typename T>
1012static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1013 const T &SrcValue, QualType DestType) {
1014 llvm::SmallVector<char, 32> Buffer;
1015 SrcValue.toString(Buffer);
1016 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1017 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1018 return false;
1019}
1020
1021static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1022 QualType SrcType, const APFloat &Value,
1023 QualType DestType, APSInt &Result) {
1024 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001025 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001026 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Richard Smith357362d2011-12-13 06:39:58 +00001028 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001029 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001030 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1031 & APFloat::opInvalidOp)
1032 return HandleOverflow(Info, E, Value, DestType);
1033 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001034}
1035
Richard Smith357362d2011-12-13 06:39:58 +00001036static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1037 QualType SrcType, QualType DestType,
1038 APFloat &Result) {
1039 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001040 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001041 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1042 APFloat::rmNearestTiesToEven, &ignored)
1043 & APFloat::opOverflow)
1044 return HandleOverflow(Info, E, Value, DestType);
1045 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001046}
1047
Mike Stump11289f42009-09-09 15:08:12 +00001048static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +00001049 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001050 unsigned DestWidth = Ctx.getIntWidth(DestType);
1051 APSInt Result = Value;
1052 // Figure out if this is a truncate, extend or noop cast.
1053 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001054 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001055 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001056 return Result;
1057}
1058
Richard Smith357362d2011-12-13 06:39:58 +00001059static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1060 QualType SrcType, const APSInt &Value,
1061 QualType DestType, APFloat &Result) {
1062 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1063 if (Result.convertFromAPInt(Value, Value.isSigned(),
1064 APFloat::rmNearestTiesToEven)
1065 & APFloat::opOverflow)
1066 return HandleOverflow(Info, E, Value, DestType);
1067 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001068}
1069
Eli Friedman803acb32011-12-22 03:51:45 +00001070static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1071 llvm::APInt &Res) {
1072 CCValue SVal;
1073 if (!Evaluate(SVal, Info, E))
1074 return false;
1075 if (SVal.isInt()) {
1076 Res = SVal.getInt();
1077 return true;
1078 }
1079 if (SVal.isFloat()) {
1080 Res = SVal.getFloat().bitcastToAPInt();
1081 return true;
1082 }
1083 if (SVal.isVector()) {
1084 QualType VecTy = E->getType();
1085 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1086 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1087 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1088 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1089 Res = llvm::APInt::getNullValue(VecSize);
1090 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1091 APValue &Elt = SVal.getVectorElt(i);
1092 llvm::APInt EltAsInt;
1093 if (Elt.isInt()) {
1094 EltAsInt = Elt.getInt();
1095 } else if (Elt.isFloat()) {
1096 EltAsInt = Elt.getFloat().bitcastToAPInt();
1097 } else {
1098 // Don't try to handle vectors of anything other than int or float
1099 // (not sure if it's possible to hit this case).
1100 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1101 return false;
1102 }
1103 unsigned BaseEltSize = EltAsInt.getBitWidth();
1104 if (BigEndian)
1105 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1106 else
1107 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1108 }
1109 return true;
1110 }
1111 // Give up if the input isn't an int, float, or vector. For example, we
1112 // reject "(v4i16)(intptr_t)&a".
1113 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1114 return false;
1115}
1116
Richard Smitha8105bc2012-01-06 16:39:00 +00001117/// Cast an lvalue referring to a base subobject to a derived class, by
1118/// truncating the lvalue's path to the given length.
1119static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1120 const RecordDecl *TruncatedType,
1121 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001122 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001123
1124 // Check we actually point to a derived class object.
1125 if (TruncatedElements == D.Entries.size())
1126 return true;
1127 assert(TruncatedElements >= D.MostDerivedPathLength &&
1128 "not casting to a derived class");
1129 if (!Result.checkSubobject(Info, E, CSK_Derived))
1130 return false;
1131
1132 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001133 const RecordDecl *RD = TruncatedType;
1134 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1136 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001137 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001138 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001139 else
Richard Smithd62306a2011-11-10 06:34:14 +00001140 Result.Offset -= Layout.getBaseClassOffset(Base);
1141 RD = Base;
1142 }
Richard Smith027bf112011-11-17 22:56:20 +00001143 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001144 return true;
1145}
1146
Richard Smitha8105bc2012-01-06 16:39:00 +00001147static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001148 const CXXRecordDecl *Derived,
1149 const CXXRecordDecl *Base,
1150 const ASTRecordLayout *RL = 0) {
1151 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1152 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001153 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smithd62306a2011-11-10 06:34:14 +00001154}
1155
Richard Smitha8105bc2012-01-06 16:39:00 +00001156static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001157 const CXXRecordDecl *DerivedDecl,
1158 const CXXBaseSpecifier *Base) {
1159 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1160
1161 if (!Base->isVirtual()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001162 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001163 return true;
1164 }
1165
Richard Smitha8105bc2012-01-06 16:39:00 +00001166 SubobjectDesignator &D = Obj.Designator;
1167 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001168 return false;
1169
Richard Smitha8105bc2012-01-06 16:39:00 +00001170 // Extract most-derived object and corresponding type.
1171 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1172 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1173 return false;
1174
1175 // Find the virtual base class.
Richard Smithd62306a2011-11-10 06:34:14 +00001176 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1177 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001178 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001179 return true;
1180}
1181
1182/// Update LVal to refer to the given field, which must be a member of the type
1183/// currently described by LVal.
Richard Smitha8105bc2012-01-06 16:39:00 +00001184static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001185 const FieldDecl *FD,
1186 const ASTRecordLayout *RL = 0) {
1187 if (!RL)
1188 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1189
1190 unsigned I = FD->getFieldIndex();
1191 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001192 LVal.addDecl(Info, E, FD);
Richard Smithd62306a2011-11-10 06:34:14 +00001193}
1194
1195/// Get the size of the given type in char units.
1196static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1197 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1198 // extension.
1199 if (Type->isVoidType() || Type->isFunctionType()) {
1200 Size = CharUnits::One();
1201 return true;
1202 }
1203
1204 if (!Type->isConstantSizeType()) {
1205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smitha8105bc2012-01-06 16:39:00 +00001206 // FIXME: Diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +00001207 return false;
1208 }
1209
1210 Size = Info.Ctx.getTypeSizeInChars(Type);
1211 return true;
1212}
1213
1214/// Update a pointer value to model pointer arithmetic.
1215/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001216/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001217/// \param LVal - The pointer value to be updated.
1218/// \param EltTy - The pointee type represented by LVal.
1219/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001220static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1221 LValue &LVal, QualType EltTy,
1222 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001223 CharUnits SizeOfPointee;
1224 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1225 return false;
1226
1227 // Compute the new offset in the appropriate width.
1228 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001229 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001230 return true;
1231}
1232
Richard Smith27908702011-10-24 17:54:18 +00001233/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001234static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1235 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001236 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001237 // If this is a parameter to an active constexpr function call, perform
1238 // argument substitution.
1239 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001241 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001243 }
Richard Smithfec09922011-11-01 16:57:24 +00001244 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1245 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001246 }
Richard Smith27908702011-10-24 17:54:18 +00001247
Richard Smithd0b4dd62011-12-19 06:19:21 +00001248 // Dig out the initializer, and use the declaration which it's attached to.
1249 const Expr *Init = VD->getAnyInitializer(VD);
1250 if (!Init || Init->isValueDependent()) {
1251 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1252 return false;
1253 }
1254
Richard Smithd62306a2011-11-10 06:34:14 +00001255 // If we're currently evaluating the initializer of this declaration, use that
1256 // in-flight value.
1257 if (Info.EvaluatingDecl == VD) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001258 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1259 CCValue::GlobalValue());
Richard Smithd62306a2011-11-10 06:34:14 +00001260 return !Result.isUninit();
1261 }
1262
Richard Smithcecf1842011-11-01 21:06:14 +00001263 // Never evaluate the initializer of a weak variable. We can't be sure that
1264 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001265 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001266 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001268 }
Richard Smithcecf1842011-11-01 21:06:14 +00001269
Richard Smithd0b4dd62011-12-19 06:19:21 +00001270 // Check that we can fold the initializer. In C++, we will have already done
1271 // this in the cases where it matters for conformance.
1272 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1273 if (!VD->evaluateValue(Notes)) {
1274 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1275 Notes.size() + 1) << VD;
1276 Info.Note(VD->getLocation(), diag::note_declared_at);
1277 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001278 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001279 } else if (!VD->checkInitIsICE()) {
1280 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1281 Notes.size() + 1) << VD;
1282 Info.Note(VD->getLocation(), diag::note_declared_at);
1283 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001284 }
Richard Smith27908702011-10-24 17:54:18 +00001285
Richard Smitha8105bc2012-01-06 16:39:00 +00001286 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001287 return true;
Richard Smith27908702011-10-24 17:54:18 +00001288}
1289
Richard Smith11562c52011-10-28 17:51:58 +00001290static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001291 Qualifiers Quals = T.getQualifiers();
1292 return Quals.hasConst() && !Quals.hasVolatile();
1293}
1294
Richard Smithe97cbd72011-11-11 04:05:33 +00001295/// Get the base index of the given base class within an APValue representing
1296/// the given derived class.
1297static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base) {
1299 Base = Base->getCanonicalDecl();
1300 unsigned Index = 0;
1301 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1302 E = Derived->bases_end(); I != E; ++I, ++Index) {
1303 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1304 return Index;
1305 }
1306
1307 llvm_unreachable("base class missing from derived class's bases list");
1308}
1309
Richard Smithf3e9e432011-11-07 09:22:26 +00001310/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001311static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1312 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001313 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001314 if (Sub.Invalid)
1315 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001316 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001317 if (Sub.isOnePastTheEnd()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001318 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001319 (unsigned)diag::note_constexpr_read_past_end :
1320 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001321 return false;
1322 }
Richard Smith6804be52011-11-11 08:28:03 +00001323 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001324 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001325
1326 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1327 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001328 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001329 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001330 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001331 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001332 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001333 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001334 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001335 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001336 // Note, it should not be possible to form a pointer with a valid
1337 // designator which points more than one past the end of the array.
1338 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001339 (unsigned)diag::note_constexpr_read_past_end :
1340 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001341 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001342 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001343 if (O->getArrayInitializedElts() > Index)
1344 O = &O->getArrayInitializedElt(Index);
1345 else
1346 O = &O->getArrayFiller();
1347 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001348 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1349 // Next subobject is a class, struct or union field.
1350 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1351 if (RD->isUnion()) {
1352 const FieldDecl *UnionField = O->getUnionField();
1353 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001354 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001355 Info.Diag(E->getExprLoc(),
1356 diag::note_constexpr_read_inactive_union_member)
1357 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001358 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001359 }
Richard Smithd62306a2011-11-10 06:34:14 +00001360 O = &O->getUnionValue();
1361 } else
1362 O = &O->getStructField(Field->getFieldIndex());
1363 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001364
1365 if (ObjType.isVolatileQualified()) {
1366 if (Info.getLangOpts().CPlusPlus) {
1367 // FIXME: Include a description of the path to the volatile subobject.
1368 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1369 << 2 << Field;
1370 Info.Note(Field->getLocation(), diag::note_declared_at);
1371 } else {
1372 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1373 }
1374 return false;
1375 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001376 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001377 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001378 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1379 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1380 O = &O->getStructBase(getBaseIndex(Derived, Base));
1381 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001382 }
Richard Smithd62306a2011-11-10 06:34:14 +00001383
Richard Smithf57d8cb2011-12-09 22:58:01 +00001384 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001385 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001386 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001387 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001388 }
1389
Richard Smitha8105bc2012-01-06 16:39:00 +00001390 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithf3e9e432011-11-07 09:22:26 +00001391 return true;
1392}
1393
Richard Smithd62306a2011-11-10 06:34:14 +00001394/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1395/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1396/// for looking up the glvalue referred to by an entity of reference type.
1397///
1398/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001399/// \param Conv - The expression for which we are performing the conversion.
1400/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001401/// \param Type - The type we expect this conversion to produce.
1402/// \param LVal - The glvalue on which we are attempting to perform this action.
1403/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001404static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1405 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001406 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001407 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1408 if (!Info.getLangOpts().CPlusPlus)
1409 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1410
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 if (LVal.Designator.Invalid)
1412 // A diagnostic will have already been produced.
1413 return false;
1414
Richard Smithce40ad62011-11-12 22:28:03 +00001415 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001416 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001417 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001418
Richard Smithf57d8cb2011-12-09 22:58:01 +00001419 if (!LVal.Base) {
1420 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001421 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1422 return false;
1423 }
1424
1425 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1426 // is not a constant expression (even if the object is non-volatile). We also
1427 // apply this rule to C++98, in order to conform to the expected 'volatile'
1428 // semantics.
1429 if (Type.isVolatileQualified()) {
1430 if (Info.getLangOpts().CPlusPlus)
1431 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1432 else
1433 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001434 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001435 }
Richard Smith11562c52011-10-28 17:51:58 +00001436
Richard Smithce40ad62011-11-12 22:28:03 +00001437 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001438 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1439 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001440 // expressions are constant expressions too. Inside constexpr functions,
1441 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001442 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001443 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001444 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001445 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001446 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001447 }
1448
Richard Smithf2b681b2011-12-21 05:04:46 +00001449 // DR1313: If the object is volatile-qualified but the glvalue was not,
1450 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001451 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001452 if (VT.isVolatileQualified()) {
1453 if (Info.getLangOpts().CPlusPlus) {
1454 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1455 Info.Note(VD->getLocation(), diag::note_declared_at);
1456 } else {
1457 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001458 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001459 return false;
1460 }
1461
1462 if (!isa<ParmVarDecl>(VD)) {
1463 if (VD->isConstexpr()) {
1464 // OK, we can read this variable.
1465 } else if (VT->isIntegralOrEnumerationType()) {
1466 if (!VT.isConstQualified()) {
1467 if (Info.getLangOpts().CPlusPlus) {
1468 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 } else {
1471 Info.Diag(Loc);
1472 }
1473 return false;
1474 }
1475 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1476 // We support folding of const floating-point types, in order to make
1477 // static const data members of such types (supported as an extension)
1478 // more useful.
1479 if (Info.getLangOpts().CPlusPlus0x) {
1480 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1481 Info.Note(VD->getLocation(), diag::note_declared_at);
1482 } else {
1483 Info.CCEDiag(Loc);
1484 }
1485 } else {
1486 // FIXME: Allow folding of values of any literal type in all languages.
1487 if (Info.getLangOpts().CPlusPlus0x) {
1488 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1489 Info.Note(VD->getLocation(), diag::note_declared_at);
1490 } else {
1491 Info.Diag(Loc);
1492 }
Richard Smith96e0c102011-11-04 02:25:55 +00001493 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001494 }
Richard Smith96e0c102011-11-04 02:25:55 +00001495 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001496
Richard Smithf57d8cb2011-12-09 22:58:01 +00001497 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001498 return false;
1499
Richard Smith0b0a0b62011-10-29 20:57:55 +00001500 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001501 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001502
1503 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1504 // conversion. This happens when the declaration and the lvalue should be
1505 // considered synonymous, for instance when initializing an array of char
1506 // from a string literal. Continue as if the initializer lvalue was the
1507 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001508 assert(RVal.getLValueOffset().isZero() &&
1509 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001510 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001511 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001512 }
1513
Richard Smithf2b681b2011-12-21 05:04:46 +00001514 // Volatile temporary objects cannot be read in constant expressions.
1515 if (Base->getType().isVolatileQualified()) {
1516 if (Info.getLangOpts().CPlusPlus) {
1517 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1518 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1519 } else {
1520 Info.Diag(Loc);
1521 }
1522 return false;
1523 }
1524
Richard Smith96e0c102011-11-04 02:25:55 +00001525 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1526 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1527 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001528 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001529 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001530 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001531 }
Richard Smith96e0c102011-11-04 02:25:55 +00001532
1533 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001534 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001535 const ConstantArrayType *CAT =
1536 Info.Ctx.getAsConstantArrayType(S->getType());
1537 if (Index >= CAT->getSize().getZExtValue()) {
1538 // Note, it should not be possible to form a pointer which points more
1539 // than one past the end of the array without producing a prior const expr
1540 // diagnostic.
1541 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001542 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001543 }
Richard Smith96e0c102011-11-04 02:25:55 +00001544 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1545 Type->isUnsignedIntegerType());
1546 if (Index < S->getLength())
1547 Value = S->getCodeUnit(Index);
1548 RVal = CCValue(Value);
1549 return true;
1550 }
1551
Richard Smithf3e9e432011-11-07 09:22:26 +00001552 if (Frame) {
1553 // If this is a temporary expression with a nontrivial initializer, grab the
1554 // value from the relevant stack frame.
1555 RVal = Frame->Temporaries[Base];
1556 } else if (const CompoundLiteralExpr *CLE
1557 = dyn_cast<CompoundLiteralExpr>(Base)) {
1558 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1559 // initializer until now for such expressions. Such an expression can't be
1560 // an ICE in C, so this only matters for fold.
1561 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1562 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1563 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001564 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001565 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001566 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001567 }
Richard Smith96e0c102011-11-04 02:25:55 +00001568
Richard Smithf57d8cb2011-12-09 22:58:01 +00001569 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1570 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001571}
1572
Richard Smithe97cbd72011-11-11 04:05:33 +00001573/// Build an lvalue for the object argument of a member function call.
1574static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1575 LValue &This) {
1576 if (Object->getType()->isPointerType())
1577 return EvaluatePointer(Object, This, Info);
1578
1579 if (Object->isGLValue())
1580 return EvaluateLValue(Object, This, Info);
1581
Richard Smith027bf112011-11-17 22:56:20 +00001582 if (Object->getType()->isLiteralType())
1583 return EvaluateTemporary(Object, This, Info);
1584
1585 return false;
1586}
1587
1588/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1589/// lvalue referring to the result.
1590///
1591/// \param Info - Information about the ongoing evaluation.
1592/// \param BO - The member pointer access operation.
1593/// \param LV - Filled in with a reference to the resulting object.
1594/// \param IncludeMember - Specifies whether the member itself is included in
1595/// the resulting LValue subobject designator. This is not possible when
1596/// creating a bound member function.
1597/// \return The field or method declaration to which the member pointer refers,
1598/// or 0 if evaluation fails.
1599static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1600 const BinaryOperator *BO,
1601 LValue &LV,
1602 bool IncludeMember = true) {
1603 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1604
1605 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1606 return 0;
1607
1608 MemberPtr MemPtr;
1609 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1610 return 0;
1611
1612 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1613 // member value, the behavior is undefined.
1614 if (!MemPtr.getDecl())
1615 return 0;
1616
1617 if (MemPtr.isDerivedMember()) {
1618 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001619 // The end of the derived-to-base path for the base object must match the
1620 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001621 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001622 LV.Designator.Entries.size())
1623 return 0;
1624 unsigned PathLengthToMember =
1625 LV.Designator.Entries.size() - MemPtr.Path.size();
1626 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1627 const CXXRecordDecl *LVDecl = getAsBaseClass(
1628 LV.Designator.Entries[PathLengthToMember + I]);
1629 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1630 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1631 return 0;
1632 }
1633
1634 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001635 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1636 PathLengthToMember))
1637 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001638 } else if (!MemPtr.Path.empty()) {
1639 // Extend the LValue path with the member pointer's path.
1640 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1641 MemPtr.Path.size() + IncludeMember);
1642
1643 // Walk down to the appropriate base class.
1644 QualType LVType = BO->getLHS()->getType();
1645 if (const PointerType *PT = LVType->getAs<PointerType>())
1646 LVType = PT->getPointeeType();
1647 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1648 assert(RD && "member pointer access on non-class-type expression");
1649 // The first class in the path is that of the lvalue.
1650 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1651 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smitha8105bc2012-01-06 16:39:00 +00001652 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smith027bf112011-11-17 22:56:20 +00001653 RD = Base;
1654 }
1655 // Finally cast to the class containing the member.
Richard Smitha8105bc2012-01-06 16:39:00 +00001656 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smith027bf112011-11-17 22:56:20 +00001657 }
1658
1659 // Add the member. Note that we cannot build bound member functions here.
1660 if (IncludeMember) {
1661 // FIXME: Deal with IndirectFieldDecls.
1662 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1663 if (!FD) return 0;
Richard Smitha8105bc2012-01-06 16:39:00 +00001664 HandleLValueMember(Info, BO, LV, FD);
Richard Smith027bf112011-11-17 22:56:20 +00001665 }
1666
1667 return MemPtr.getDecl();
1668}
1669
1670/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1671/// the provided lvalue, which currently refers to the base object.
1672static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1673 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00001674 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001675 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00001676 return false;
1677
Richard Smitha8105bc2012-01-06 16:39:00 +00001678 QualType TargetQT = E->getType();
1679 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1680 TargetQT = PT->getPointeeType();
1681
1682 // Check this cast lands within the final derived-to-base subobject path.
1683 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1684 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1685 << D.MostDerivedType << TargetQT;
1686 return false;
1687 }
1688
Richard Smith027bf112011-11-17 22:56:20 +00001689 // Check the type of the final cast. We don't need to check the path,
1690 // since a cast can only be formed if the path is unique.
1691 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00001692 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1693 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00001694 if (NewEntriesSize == D.MostDerivedPathLength)
1695 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1696 else
Richard Smith027bf112011-11-17 22:56:20 +00001697 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00001698 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1699 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1700 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00001701 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001702 }
Richard Smith027bf112011-11-17 22:56:20 +00001703
1704 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001705 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00001706}
1707
Mike Stump876387b2009-10-27 22:09:17 +00001708namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001709enum EvalStmtResult {
1710 /// Evaluation failed.
1711 ESR_Failed,
1712 /// Hit a 'return' statement.
1713 ESR_Returned,
1714 /// Evaluation succeeded.
1715 ESR_Succeeded
1716};
1717}
1718
1719// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001720static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001721 const Stmt *S) {
1722 switch (S->getStmtClass()) {
1723 default:
1724 return ESR_Failed;
1725
1726 case Stmt::NullStmtClass:
1727 case Stmt::DeclStmtClass:
1728 return ESR_Succeeded;
1729
Richard Smith357362d2011-12-13 06:39:58 +00001730 case Stmt::ReturnStmtClass: {
1731 CCValue CCResult;
1732 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1733 if (!Evaluate(CCResult, Info, RetExpr) ||
1734 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1735 CCEK_ReturnValue))
1736 return ESR_Failed;
1737 return ESR_Returned;
1738 }
Richard Smith254a73d2011-10-28 22:34:42 +00001739
1740 case Stmt::CompoundStmtClass: {
1741 const CompoundStmt *CS = cast<CompoundStmt>(S);
1742 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1743 BE = CS->body_end(); BI != BE; ++BI) {
1744 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1745 if (ESR != ESR_Succeeded)
1746 return ESR;
1747 }
1748 return ESR_Succeeded;
1749 }
1750 }
1751}
1752
Richard Smithcc36f692011-12-22 02:22:31 +00001753/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1754/// default constructor. If so, we'll fold it whether or not it's marked as
1755/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1756/// so we need special handling.
1757static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001758 const CXXConstructorDecl *CD,
1759 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001760 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1761 return false;
1762
1763 if (!CD->isConstexpr()) {
1764 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001765 // Value-initialization does not call a trivial default constructor, so
1766 // such a call is a core constant expression whether or not the
1767 // constructor is constexpr.
1768 if (!IsValueInitialization) {
1769 // FIXME: If DiagDecl is an implicitly-declared special member function,
1770 // we should be much more explicit about why it's not constexpr.
1771 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1772 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1773 Info.Note(CD->getLocation(), diag::note_declared_at);
1774 }
Richard Smithcc36f692011-12-22 02:22:31 +00001775 } else {
1776 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1777 }
1778 }
1779 return true;
1780}
1781
Richard Smith357362d2011-12-13 06:39:58 +00001782/// CheckConstexprFunction - Check that a function can be called in a constant
1783/// expression.
1784static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1785 const FunctionDecl *Declaration,
1786 const FunctionDecl *Definition) {
1787 // Can we evaluate this function call?
1788 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1789 return true;
1790
1791 if (Info.getLangOpts().CPlusPlus0x) {
1792 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001793 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1794 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001795 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1796 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1797 << DiagDecl;
1798 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1799 } else {
1800 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1801 }
1802 return false;
1803}
1804
Richard Smithd62306a2011-11-10 06:34:14 +00001805namespace {
Richard Smith60494462011-11-11 05:48:57 +00001806typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001807}
1808
1809/// EvaluateArgs - Evaluate the arguments to a function call.
1810static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1811 EvalInfo &Info) {
1812 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1813 I != E; ++I)
1814 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1815 return false;
1816 return true;
1817}
1818
Richard Smith254a73d2011-10-28 22:34:42 +00001819/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001820static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1821 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001822 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001823 EvalInfo &Info, APValue &Result) {
1824 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001825 return false;
1826
Richard Smithd62306a2011-11-10 06:34:14 +00001827 ArgVector ArgValues(Args.size());
1828 if (!EvaluateArgs(Args, ArgValues, Info))
1829 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001830
Richard Smithf6f003a2011-12-16 19:06:07 +00001831 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1832 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001833 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1834}
1835
Richard Smithd62306a2011-11-10 06:34:14 +00001836/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001837static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001838 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001839 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001840 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001841 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001842 return false;
1843
1844 ArgVector ArgValues(Args.size());
1845 if (!EvaluateArgs(Args, ArgValues, Info))
1846 return false;
1847
Richard Smithf6f003a2011-12-16 19:06:07 +00001848 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1849 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001850
1851 // If it's a delegating constructor, just delegate.
1852 if (Definition->isDelegatingConstructor()) {
1853 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1854 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1855 }
1856
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001857 // For a trivial copy or move constructor, perform an APValue copy. This is
1858 // essential for unions, where the operations performed by the constructor
1859 // cannot be represented by ctor-initializers.
Richard Smithd62306a2011-11-10 06:34:14 +00001860 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith1bc5c2c2012-01-10 04:32:03 +00001861 if (Definition->isDefaulted() &&
1862 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1863 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1864 LValue RHS;
1865 RHS.setFrom(ArgValues[0]);
1866 CCValue Value;
1867 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1868 RHS, Value) &&
1869 CheckConstantExpression(Info, CallExpr, Value, Result);
1870 }
1871
1872 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00001873 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001874 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1875 std::distance(RD->field_begin(), RD->field_end()));
1876
1877 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1878
1879 unsigned BasesSeen = 0;
1880#ifndef NDEBUG
1881 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1882#endif
1883 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1884 E = Definition->init_end(); I != E; ++I) {
1885 if ((*I)->isBaseInitializer()) {
1886 QualType BaseType((*I)->getBaseClass(), 0);
1887#ifndef NDEBUG
1888 // Non-virtual base classes are initialized in the order in the class
1889 // definition. We cannot have a virtual base class for a literal type.
1890 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1891 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1892 "base class initializers not in expected order");
1893 ++BaseIt;
1894#endif
1895 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001896 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smithd62306a2011-11-10 06:34:14 +00001897 BaseType->getAsCXXRecordDecl(), &Layout);
1898 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1899 Subobject, (*I)->getInit()))
1900 return false;
1901 } else if (FieldDecl *FD = (*I)->getMember()) {
1902 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00001903 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00001904 if (RD->isUnion()) {
1905 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001906 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1907 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001908 return false;
1909 } else if (!EvaluateConstantExpression(
1910 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001911 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001912 return false;
1913 } else {
1914 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001915 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001916 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001917 return false;
1918 }
1919 }
1920
1921 return true;
1922}
1923
Richard Smith254a73d2011-10-28 22:34:42 +00001924namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001925class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001926 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001927 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001928public:
1929
Richard Smith725810a2011-10-16 21:26:27 +00001930 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001931
1932 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001933 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001934 return true;
1935 }
1936
Peter Collingbournee9200682011-05-13 03:29:01 +00001937 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1938 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001939 return Visit(E->getResultExpr());
1940 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001941 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001942 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001943 return true;
1944 return false;
1945 }
John McCall31168b02011-06-15 23:02:42 +00001946 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001947 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001948 return true;
1949 return false;
1950 }
1951 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001952 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001953 return true;
1954 return false;
1955 }
1956
Mike Stump876387b2009-10-27 22:09:17 +00001957 // We don't want to evaluate BlockExprs multiple times, as they generate
1958 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001959 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1960 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1961 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001962 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001963 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1964 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1965 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1966 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1967 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1968 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001969 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001970 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001971 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001972 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001973 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001974 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1975 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1976 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1977 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001978 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001979 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1980 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1981 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1982 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1983 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001984 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001985 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001986 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001987 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001988 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001989
1990 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001991 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001992 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1993 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001994 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001995 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001996 return false;
1997 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001998
Peter Collingbournee9200682011-05-13 03:29:01 +00001999 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00002000};
2001
John McCallc07a0c72011-02-17 10:25:35 +00002002class OpaqueValueEvaluation {
2003 EvalInfo &info;
2004 OpaqueValueExpr *opaqueValue;
2005
2006public:
2007 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2008 Expr *value)
2009 : info(info), opaqueValue(opaqueValue) {
2010
2011 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00002012 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00002013 this->opaqueValue = 0;
2014 return;
2015 }
John McCallc07a0c72011-02-17 10:25:35 +00002016 }
2017
2018 bool hasError() const { return opaqueValue == 0; }
2019
2020 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00002021 // FIXME: This will not work for recursive constexpr functions using opaque
2022 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00002023 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2024 }
2025};
2026
Mike Stump876387b2009-10-27 22:09:17 +00002027} // end anonymous namespace
2028
Eli Friedman9a156e52008-11-12 09:44:48 +00002029//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002030// Generic Evaluation
2031//===----------------------------------------------------------------------===//
2032namespace {
2033
Richard Smithf57d8cb2011-12-09 22:58:01 +00002034// FIXME: RetTy is always bool. Remove it.
2035template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002036class ExprEvaluatorBase
2037 : public ConstStmtVisitor<Derived, RetTy> {
2038private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002039 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002040 return static_cast<Derived*>(this)->Success(V, E);
2041 }
Richard Smithfddd3842011-12-30 21:15:51 +00002042 RetTy DerivedZeroInitialization(const Expr *E) {
2043 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002044 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002045
2046protected:
2047 EvalInfo &Info;
2048 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2049 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2050
Richard Smith92b1ce02011-12-12 09:28:41 +00002051 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00002052 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002053 }
2054
2055 /// Report an evaluation error. This should only be called when an error is
2056 /// first discovered. When propagating an error, just return false.
2057 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00002058 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002059 return false;
2060 }
2061 bool Error(const Expr *E) {
2062 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2063 }
2064
Richard Smithfddd3842011-12-30 21:15:51 +00002065 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00002066
Peter Collingbournee9200682011-05-13 03:29:01 +00002067public:
2068 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2069
2070 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002071 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002072 }
2073 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002074 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002075 }
2076
2077 RetTy VisitParenExpr(const ParenExpr *E)
2078 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2079 RetTy VisitUnaryExtension(const UnaryOperator *E)
2080 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2081 RetTy VisitUnaryPlus(const UnaryOperator *E)
2082 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2083 RetTy VisitChooseExpr(const ChooseExpr *E)
2084 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2085 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2086 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002087 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2088 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002089 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2090 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002091 // We cannot create any objects for which cleanups are required, so there is
2092 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2093 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2094 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002095
Richard Smith6d6ecc32011-12-12 12:46:16 +00002096 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2098 return static_cast<Derived*>(this)->VisitCastExpr(E);
2099 }
2100 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2101 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2102 return static_cast<Derived*>(this)->VisitCastExpr(E);
2103 }
2104
Richard Smith027bf112011-11-17 22:56:20 +00002105 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2106 switch (E->getOpcode()) {
2107 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002108 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002109
2110 case BO_Comma:
2111 VisitIgnoredValue(E->getLHS());
2112 return StmtVisitorTy::Visit(E->getRHS());
2113
2114 case BO_PtrMemD:
2115 case BO_PtrMemI: {
2116 LValue Obj;
2117 if (!HandleMemberPointerAccess(Info, E, Obj))
2118 return false;
2119 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002120 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002121 return false;
2122 return DerivedSuccess(Result, E);
2123 }
2124 }
2125 }
2126
Peter Collingbournee9200682011-05-13 03:29:01 +00002127 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2128 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2129 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002130 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002131
2132 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002133 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002134 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002135
2136 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2137 }
2138
2139 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2140 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002141 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002142 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002143
Richard Smith11562c52011-10-28 17:51:58 +00002144 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002145 return StmtVisitorTy::Visit(EvalExpr);
2146 }
2147
2148 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002149 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002150 if (!Value) {
2151 const Expr *Source = E->getSourceExpr();
2152 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002153 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002154 if (Source == E) { // sanity checking.
2155 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002156 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002157 }
2158 return StmtVisitorTy::Visit(Source);
2159 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002160 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002161 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002162
Richard Smith254a73d2011-10-28 22:34:42 +00002163 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002164 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002165 QualType CalleeType = Callee->getType();
2166
Richard Smith254a73d2011-10-28 22:34:42 +00002167 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002168 LValue *This = 0, ThisVal;
2169 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002170
Richard Smithe97cbd72011-11-11 04:05:33 +00002171 // Extract function decl and 'this' pointer from the callee.
2172 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002173 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002174 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2175 // Explicit bound member calls, such as x.f() or p->g();
2176 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002177 return false;
2178 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002179 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002180 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2181 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002182 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2183 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002184 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002185 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002186 return Error(Callee);
2187
2188 FD = dyn_cast<FunctionDecl>(Member);
2189 if (!FD)
2190 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002191 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002192 LValue Call;
2193 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002194 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002195
Richard Smitha8105bc2012-01-06 16:39:00 +00002196 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002197 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002198 FD = dyn_cast_or_null<FunctionDecl>(
2199 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002200 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002201 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002202
2203 // Overloaded operator calls to member functions are represented as normal
2204 // calls with '*this' as the first argument.
2205 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2206 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002207 // FIXME: When selecting an implicit conversion for an overloaded
2208 // operator delete, we sometimes try to evaluate calls to conversion
2209 // operators without a 'this' parameter!
2210 if (Args.empty())
2211 return Error(E);
2212
Richard Smithe97cbd72011-11-11 04:05:33 +00002213 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2214 return false;
2215 This = &ThisVal;
2216 Args = Args.slice(1);
2217 }
2218
2219 // Don't call function pointers which have been cast to some other type.
2220 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002221 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002222 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002223 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002224
Richard Smith357362d2011-12-13 06:39:58 +00002225 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002226 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002227 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002228
Richard Smith357362d2011-12-13 06:39:58 +00002229 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002230 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002231 return false;
2232
Richard Smitha8105bc2012-01-06 16:39:00 +00002233 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002234 }
2235
Richard Smith11562c52011-10-28 17:51:58 +00002236 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2237 return StmtVisitorTy::Visit(E->getInitializer());
2238 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002239 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002240 if (E->getNumInits() == 0)
2241 return DerivedZeroInitialization(E);
2242 if (E->getNumInits() == 1)
2243 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002244 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002245 }
2246 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002247 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002248 }
2249 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002250 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002251 }
Richard Smith027bf112011-11-17 22:56:20 +00002252 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002253 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002254 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002255
Richard Smithd62306a2011-11-10 06:34:14 +00002256 /// A member expression where the object is a prvalue is itself a prvalue.
2257 RetTy VisitMemberExpr(const MemberExpr *E) {
2258 assert(!E->isArrow() && "missing call to bound member function?");
2259
2260 CCValue Val;
2261 if (!Evaluate(Val, Info, E->getBase()))
2262 return false;
2263
2264 QualType BaseTy = E->getBase()->getType();
2265
2266 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002267 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002268 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2269 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2270 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2271
Richard Smitha8105bc2012-01-06 16:39:00 +00002272 SubobjectDesignator Designator(BaseTy);
2273 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002274
Richard Smithf57d8cb2011-12-09 22:58:01 +00002275 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002276 DerivedSuccess(Val, E);
2277 }
2278
Richard Smith11562c52011-10-28 17:51:58 +00002279 RetTy VisitCastExpr(const CastExpr *E) {
2280 switch (E->getCastKind()) {
2281 default:
2282 break;
2283
2284 case CK_NoOp:
2285 return StmtVisitorTy::Visit(E->getSubExpr());
2286
2287 case CK_LValueToRValue: {
2288 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002289 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2290 return false;
2291 CCValue RVal;
2292 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2293 return false;
2294 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002295 }
2296 }
2297
Richard Smithf57d8cb2011-12-09 22:58:01 +00002298 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002299 }
2300
Richard Smith4a678122011-10-24 18:44:57 +00002301 /// Visit a value which is evaluated, but whose value is ignored.
2302 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002303 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002304 if (!Evaluate(Scratch, Info, E))
2305 Info.EvalStatus.HasSideEffects = true;
2306 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002307};
2308
2309}
2310
2311//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002312// Common base class for lvalue and temporary evaluation.
2313//===----------------------------------------------------------------------===//
2314namespace {
2315template<class Derived>
2316class LValueExprEvaluatorBase
2317 : public ExprEvaluatorBase<Derived, bool> {
2318protected:
2319 LValue &Result;
2320 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2321 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2322
2323 bool Success(APValue::LValueBase B) {
2324 Result.set(B);
2325 return true;
2326 }
2327
2328public:
2329 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2330 ExprEvaluatorBaseTy(Info), Result(Result) {}
2331
2332 bool Success(const CCValue &V, const Expr *E) {
2333 Result.setFrom(V);
2334 return true;
2335 }
Richard Smith027bf112011-11-17 22:56:20 +00002336
Richard Smith027bf112011-11-17 22:56:20 +00002337 bool VisitMemberExpr(const MemberExpr *E) {
2338 // Handle non-static data members.
2339 QualType BaseTy;
2340 if (E->isArrow()) {
2341 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2342 return false;
2343 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002344 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002345 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002346 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2347 return false;
2348 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002349 } else {
2350 if (!this->Visit(E->getBase()))
2351 return false;
2352 BaseTy = E->getBase()->getType();
2353 }
Richard Smith027bf112011-11-17 22:56:20 +00002354
2355 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2356 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002357 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002358 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2359 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2360 (void)BaseTy;
2361
Richard Smitha8105bc2012-01-06 16:39:00 +00002362 HandleLValueMember(this->Info, E, Result, FD);
Richard Smith027bf112011-11-17 22:56:20 +00002363
2364 if (FD->getType()->isReferenceType()) {
2365 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002366 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002367 RefValue))
2368 return false;
2369 return Success(RefValue, E);
2370 }
2371 return true;
2372 }
2373
2374 bool VisitBinaryOperator(const BinaryOperator *E) {
2375 switch (E->getOpcode()) {
2376 default:
2377 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2378
2379 case BO_PtrMemD:
2380 case BO_PtrMemI:
2381 return HandleMemberPointerAccess(this->Info, E, Result);
2382 }
2383 }
2384
2385 bool VisitCastExpr(const CastExpr *E) {
2386 switch (E->getCastKind()) {
2387 default:
2388 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2389
2390 case CK_DerivedToBase:
2391 case CK_UncheckedDerivedToBase: {
2392 if (!this->Visit(E->getSubExpr()))
2393 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002394
2395 // Now figure out the necessary offset to add to the base LV to get from
2396 // the derived class to the base class.
2397 QualType Type = E->getSubExpr()->getType();
2398
2399 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2400 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002401 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002402 *PathI))
2403 return false;
2404 Type = (*PathI)->getType();
2405 }
2406
2407 return true;
2408 }
2409 }
2410 }
2411};
2412}
2413
2414//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002415// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002416//
2417// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2418// function designators (in C), decl references to void objects (in C), and
2419// temporaries (if building with -Wno-address-of-temporary).
2420//
2421// LValue evaluation produces values comprising a base expression of one of the
2422// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002423// - Declarations
2424// * VarDecl
2425// * FunctionDecl
2426// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002427// * CompoundLiteralExpr in C
2428// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002429// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002430// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002431// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002432// * ObjCEncodeExpr
2433// * AddrLabelExpr
2434// * BlockExpr
2435// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002436// - Locals and temporaries
2437// * Any Expr, with a Frame indicating the function in which the temporary was
2438// evaluated.
2439// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002440//===----------------------------------------------------------------------===//
2441namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002442class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002443 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002444public:
Richard Smith027bf112011-11-17 22:56:20 +00002445 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2446 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002447
Richard Smith11562c52011-10-28 17:51:58 +00002448 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2449
Peter Collingbournee9200682011-05-13 03:29:01 +00002450 bool VisitDeclRefExpr(const DeclRefExpr *E);
2451 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002452 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002453 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2454 bool VisitMemberExpr(const MemberExpr *E);
2455 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2456 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002457 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002458 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2459 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002460
Peter Collingbournee9200682011-05-13 03:29:01 +00002461 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002462 switch (E->getCastKind()) {
2463 default:
Richard Smith027bf112011-11-17 22:56:20 +00002464 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002465
Eli Friedmance3e02a2011-10-11 00:13:24 +00002466 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002467 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002468 if (!Visit(E->getSubExpr()))
2469 return false;
2470 Result.Designator.setInvalid();
2471 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002472
Richard Smith027bf112011-11-17 22:56:20 +00002473 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002474 if (!Visit(E->getSubExpr()))
2475 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002476 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002477 }
2478 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002479
Eli Friedman449fe542009-03-23 04:56:01 +00002480 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002481
Eli Friedman9a156e52008-11-12 09:44:48 +00002482};
2483} // end anonymous namespace
2484
Richard Smith11562c52011-10-28 17:51:58 +00002485/// Evaluate an expression as an lvalue. This can be legitimately called on
2486/// expressions which are not glvalues, in a few cases:
2487/// * function designators in C,
2488/// * "extern void" objects,
2489/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002490static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002491 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2492 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2493 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002494 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002495}
2496
Peter Collingbournee9200682011-05-13 03:29:01 +00002497bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002498 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2499 return Success(FD);
2500 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002501 return VisitVarDecl(E, VD);
2502 return Error(E);
2503}
Richard Smith733237d2011-10-24 23:14:33 +00002504
Richard Smith11562c52011-10-28 17:51:58 +00002505bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002506 if (!VD->getType()->isReferenceType()) {
2507 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002508 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002509 return true;
2510 }
Richard Smithce40ad62011-11-12 22:28:03 +00002511 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002512 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002513
Richard Smith0b0a0b62011-10-29 20:57:55 +00002514 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002515 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2516 return false;
2517 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002518}
2519
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002520bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2521 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002522 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002523 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002524 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2525
2526 Result.set(E, Info.CurrentCall);
2527 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2528 Result, E->GetTemporaryExpr());
2529 }
2530
2531 // Materialization of an lvalue temporary occurs when we need to force a copy
2532 // (for instance, if it's a bitfield).
2533 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2534 if (!Visit(E->GetTemporaryExpr()))
2535 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002536 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002537 Info.CurrentCall->Temporaries[E]))
2538 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002539 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002540 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002541}
2542
Peter Collingbournee9200682011-05-13 03:29:01 +00002543bool
2544LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002545 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2546 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2547 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002548 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002549}
2550
Richard Smith6e525142011-12-27 12:18:28 +00002551bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2552 if (E->isTypeOperand())
2553 return Success(E);
2554 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2555 if (RD && RD->isPolymorphic()) {
2556 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2557 << E->getExprOperand()->getType()
2558 << E->getExprOperand()->getSourceRange();
2559 return false;
2560 }
2561 return Success(E);
2562}
2563
Peter Collingbournee9200682011-05-13 03:29:01 +00002564bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002565 // Handle static data members.
2566 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2567 VisitIgnoredValue(E->getBase());
2568 return VisitVarDecl(E, VD);
2569 }
2570
Richard Smith254a73d2011-10-28 22:34:42 +00002571 // Handle static member functions.
2572 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2573 if (MD->isStatic()) {
2574 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002575 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002576 }
2577 }
2578
Richard Smithd62306a2011-11-10 06:34:14 +00002579 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002580 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002581}
2582
Peter Collingbournee9200682011-05-13 03:29:01 +00002583bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002584 // FIXME: Deal with vectors as array subscript bases.
2585 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002586 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002587
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002588 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002589 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002591 APSInt Index;
2592 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002593 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002594 int64_t IndexValue
2595 = Index.isSigned() ? Index.getSExtValue()
2596 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002597
Richard Smitha8105bc2012-01-06 16:39:00 +00002598 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002599}
Eli Friedman9a156e52008-11-12 09:44:48 +00002600
Peter Collingbournee9200682011-05-13 03:29:01 +00002601bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002602 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002603}
2604
Eli Friedman9a156e52008-11-12 09:44:48 +00002605//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002606// Pointer Evaluation
2607//===----------------------------------------------------------------------===//
2608
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002609namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002610class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002611 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002612 LValue &Result;
2613
Peter Collingbournee9200682011-05-13 03:29:01 +00002614 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002615 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002616 return true;
2617 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002618public:
Mike Stump11289f42009-09-09 15:08:12 +00002619
John McCall45d55e42010-05-07 21:00:08 +00002620 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002621 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002622
Richard Smith0b0a0b62011-10-29 20:57:55 +00002623 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002624 Result.setFrom(V);
2625 return true;
2626 }
Richard Smithfddd3842011-12-30 21:15:51 +00002627 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002628 return Success((Expr*)0);
2629 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002630
John McCall45d55e42010-05-07 21:00:08 +00002631 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002632 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002633 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002634 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002635 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002636 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002637 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002638 bool VisitCallExpr(const CallExpr *E);
2639 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002640 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002641 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002642 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002643 }
Richard Smithd62306a2011-11-10 06:34:14 +00002644 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2645 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002646 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002647 Result = *Info.CurrentCall->This;
2648 return true;
2649 }
John McCallc07a0c72011-02-17 10:25:35 +00002650
Eli Friedman449fe542009-03-23 04:56:01 +00002651 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002652};
Chris Lattner05706e882008-07-11 18:11:29 +00002653} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002654
John McCall45d55e42010-05-07 21:00:08 +00002655static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002656 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002657 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002658}
2659
John McCall45d55e42010-05-07 21:00:08 +00002660bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002661 if (E->getOpcode() != BO_Add &&
2662 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattner05706e882008-07-11 18:11:29 +00002665 const Expr *PExp = E->getLHS();
2666 const Expr *IExp = E->getRHS();
2667 if (IExp->getType()->isPointerType())
2668 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall45d55e42010-05-07 21:00:08 +00002670 if (!EvaluatePointer(PExp, Result, Info))
2671 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002672
John McCall45d55e42010-05-07 21:00:08 +00002673 llvm::APSInt Offset;
2674 if (!EvaluateInteger(IExp, Offset, Info))
2675 return false;
2676 int64_t AdditionalOffset
2677 = Offset.isSigned() ? Offset.getSExtValue()
2678 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002679 if (E->getOpcode() == BO_Sub)
2680 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002681
Richard Smithd62306a2011-11-10 06:34:14 +00002682 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00002683 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2684 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002685}
Eli Friedman9a156e52008-11-12 09:44:48 +00002686
John McCall45d55e42010-05-07 21:00:08 +00002687bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2688 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002689}
Mike Stump11289f42009-09-09 15:08:12 +00002690
Peter Collingbournee9200682011-05-13 03:29:01 +00002691bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2692 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002693
Eli Friedman847a2bc2009-12-27 05:43:15 +00002694 switch (E->getCastKind()) {
2695 default:
2696 break;
2697
John McCalle3027922010-08-25 11:45:40 +00002698 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002699 case CK_CPointerToObjCPointerCast:
2700 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002701 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002702 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2703 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2704 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002705 if (!E->getType()->isVoidPointerType()) {
2706 if (SubExpr->getType()->isVoidPointerType())
2707 CCEDiag(E, diag::note_constexpr_invalid_cast)
2708 << 3 << SubExpr->getType();
2709 else
2710 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2711 }
Richard Smith96e0c102011-11-04 02:25:55 +00002712 if (!Visit(SubExpr))
2713 return false;
2714 Result.Designator.setInvalid();
2715 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002716
Anders Carlsson18275092010-10-31 20:41:46 +00002717 case CK_DerivedToBase:
2718 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002719 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002720 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002721 if (!Result.Base && Result.Offset.isZero())
2722 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002723
Richard Smithd62306a2011-11-10 06:34:14 +00002724 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002725 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002726 QualType Type =
2727 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002728
Richard Smithd62306a2011-11-10 06:34:14 +00002729 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002730 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002731 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2732 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002733 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002734 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002735 }
2736
Anders Carlsson18275092010-10-31 20:41:46 +00002737 return true;
2738 }
2739
Richard Smith027bf112011-11-17 22:56:20 +00002740 case CK_BaseToDerived:
2741 if (!Visit(E->getSubExpr()))
2742 return false;
2743 if (!Result.Base && Result.Offset.isZero())
2744 return true;
2745 return HandleBaseToDerivedCast(Info, E, Result);
2746
Richard Smith0b0a0b62011-10-29 20:57:55 +00002747 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002748 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002749
John McCalle3027922010-08-25 11:45:40 +00002750 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002751 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2752
Richard Smith0b0a0b62011-10-29 20:57:55 +00002753 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002754 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002755 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002756
John McCall45d55e42010-05-07 21:00:08 +00002757 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002758 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2759 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002760 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002761 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002762 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002763 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002764 return true;
2765 } else {
2766 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002767 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002768 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002769 }
2770 }
John McCalle3027922010-08-25 11:45:40 +00002771 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002772 if (SubExpr->isGLValue()) {
2773 if (!EvaluateLValue(SubExpr, Result, Info))
2774 return false;
2775 } else {
2776 Result.set(SubExpr, Info.CurrentCall);
2777 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2778 Info, Result, SubExpr))
2779 return false;
2780 }
Richard Smith96e0c102011-11-04 02:25:55 +00002781 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00002782 if (const ConstantArrayType *CAT
2783 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2784 Result.addArray(Info, E, CAT);
2785 else
2786 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00002787 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002788
John McCalle3027922010-08-25 11:45:40 +00002789 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002790 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002791 }
2792
Richard Smith11562c52011-10-28 17:51:58 +00002793 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002794}
Chris Lattner05706e882008-07-11 18:11:29 +00002795
Peter Collingbournee9200682011-05-13 03:29:01 +00002796bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002797 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002798 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002799
Peter Collingbournee9200682011-05-13 03:29:01 +00002800 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002801}
Chris Lattner05706e882008-07-11 18:11:29 +00002802
2803//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002804// Member Pointer Evaluation
2805//===----------------------------------------------------------------------===//
2806
2807namespace {
2808class MemberPointerExprEvaluator
2809 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2810 MemberPtr &Result;
2811
2812 bool Success(const ValueDecl *D) {
2813 Result = MemberPtr(D);
2814 return true;
2815 }
2816public:
2817
2818 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2819 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2820
2821 bool Success(const CCValue &V, const Expr *E) {
2822 Result.setFrom(V);
2823 return true;
2824 }
Richard Smithfddd3842011-12-30 21:15:51 +00002825 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002826 return Success((const ValueDecl*)0);
2827 }
2828
2829 bool VisitCastExpr(const CastExpr *E);
2830 bool VisitUnaryAddrOf(const UnaryOperator *E);
2831};
2832} // end anonymous namespace
2833
2834static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2835 EvalInfo &Info) {
2836 assert(E->isRValue() && E->getType()->isMemberPointerType());
2837 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2838}
2839
2840bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2841 switch (E->getCastKind()) {
2842 default:
2843 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2844
2845 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002846 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002847
2848 case CK_BaseToDerivedMemberPointer: {
2849 if (!Visit(E->getSubExpr()))
2850 return false;
2851 if (E->path_empty())
2852 return true;
2853 // Base-to-derived member pointer casts store the path in derived-to-base
2854 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2855 // the wrong end of the derived->base arc, so stagger the path by one class.
2856 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2857 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2858 PathI != PathE; ++PathI) {
2859 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2860 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2861 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002862 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002863 }
2864 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2865 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002866 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002867 return true;
2868 }
2869
2870 case CK_DerivedToBaseMemberPointer:
2871 if (!Visit(E->getSubExpr()))
2872 return false;
2873 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2874 PathE = E->path_end(); PathI != PathE; ++PathI) {
2875 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2876 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2877 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002878 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002879 }
2880 return true;
2881 }
2882}
2883
2884bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2885 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2886 // member can be formed.
2887 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2888}
2889
2890//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002891// Record Evaluation
2892//===----------------------------------------------------------------------===//
2893
2894namespace {
2895 class RecordExprEvaluator
2896 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2897 const LValue &This;
2898 APValue &Result;
2899 public:
2900
2901 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2902 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2903
2904 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002905 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002906 }
Richard Smithfddd3842011-12-30 21:15:51 +00002907 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002908
Richard Smithe97cbd72011-11-11 04:05:33 +00002909 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002910 bool VisitInitListExpr(const InitListExpr *E);
2911 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2912 };
2913}
2914
Richard Smithfddd3842011-12-30 21:15:51 +00002915/// Perform zero-initialization on an object of non-union class type.
2916/// C++11 [dcl.init]p5:
2917/// To zero-initialize an object or reference of type T means:
2918/// [...]
2919/// -- if T is a (possibly cv-qualified) non-union class type,
2920/// each non-static data member and each base-class subobject is
2921/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00002922static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2923 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00002924 const LValue &This, APValue &Result) {
2925 assert(!RD->isUnion() && "Expected non-union class type");
2926 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2927 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2928 std::distance(RD->field_begin(), RD->field_end()));
2929
2930 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2931
2932 if (CD) {
2933 unsigned Index = 0;
2934 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002935 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00002936 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2937 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002938 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2939 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00002940 Result.getStructBase(Index)))
2941 return false;
2942 }
2943 }
2944
Richard Smitha8105bc2012-01-06 16:39:00 +00002945 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2946 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00002947 // -- if T is a reference type, no initialization is performed.
2948 if ((*I)->getType()->isReferenceType())
2949 continue;
2950
2951 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002952 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smithfddd3842011-12-30 21:15:51 +00002953
2954 ImplicitValueInitExpr VIE((*I)->getType());
2955 if (!EvaluateConstantExpression(
2956 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2957 return false;
2958 }
2959
2960 return true;
2961}
2962
2963bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2964 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2965 if (RD->isUnion()) {
2966 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2967 // object's first non-static named data member is zero-initialized
2968 RecordDecl::field_iterator I = RD->field_begin();
2969 if (I == RD->field_end()) {
2970 Result = APValue((const FieldDecl*)0);
2971 return true;
2972 }
2973
2974 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00002975 HandleLValueMember(Info, E, Subobject, *I);
Richard Smithfddd3842011-12-30 21:15:51 +00002976 Result = APValue(*I);
2977 ImplicitValueInitExpr VIE((*I)->getType());
2978 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2979 Subobject, &VIE);
2980 }
2981
Richard Smitha8105bc2012-01-06 16:39:00 +00002982 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00002983}
2984
Richard Smithe97cbd72011-11-11 04:05:33 +00002985bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2986 switch (E->getCastKind()) {
2987 default:
2988 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2989
2990 case CK_ConstructorConversion:
2991 return Visit(E->getSubExpr());
2992
2993 case CK_DerivedToBase:
2994 case CK_UncheckedDerivedToBase: {
2995 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002996 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002997 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002998 if (!DerivedObject.isStruct())
2999 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003000
3001 // Derived-to-base rvalue conversion: just slice off the derived part.
3002 APValue *Value = &DerivedObject;
3003 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3004 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3005 PathE = E->path_end(); PathI != PathE; ++PathI) {
3006 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3007 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3008 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3009 RD = Base;
3010 }
3011 Result = *Value;
3012 return true;
3013 }
3014 }
3015}
3016
Richard Smithd62306a2011-11-10 06:34:14 +00003017bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3018 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3019 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3020
3021 if (RD->isUnion()) {
3022 Result = APValue(E->getInitializedFieldInUnion());
3023 if (!E->getNumInits())
3024 return true;
3025 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003026 HandleLValueMember(Info, E->getInit(0), Subobject,
3027 E->getInitializedFieldInUnion(), &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003028 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3029 Subobject, E->getInit(0));
3030 }
3031
3032 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3033 "initializer list for class with base classes");
3034 Result = APValue(APValue::UninitStruct(), 0,
3035 std::distance(RD->field_begin(), RD->field_end()));
3036 unsigned ElementNo = 0;
3037 for (RecordDecl::field_iterator Field = RD->field_begin(),
3038 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3039 // Anonymous bit-fields are not considered members of the class for
3040 // purposes of aggregate initialization.
3041 if (Field->isUnnamedBitfield())
3042 continue;
3043
3044 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003045
3046 if (ElementNo < E->getNumInits()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003047 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3048 &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003049 if (!EvaluateConstantExpression(
3050 Result.getStructField((*Field)->getFieldIndex()),
3051 Info, Subobject, E->getInit(ElementNo++)))
3052 return false;
3053 } else {
3054 // Perform an implicit value-initialization for members beyond the end of
3055 // the initializer list.
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smithd62306a2011-11-10 06:34:14 +00003057 ImplicitValueInitExpr VIE(Field->getType());
3058 if (!EvaluateConstantExpression(
3059 Result.getStructField((*Field)->getFieldIndex()),
3060 Info, Subobject, &VIE))
3061 return false;
3062 }
3063 }
3064
3065 return true;
3066}
3067
3068bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3069 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00003070 bool ZeroInit = E->requiresZeroInitialization();
3071 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3072 if (ZeroInit)
3073 return ZeroInitialization(E);
3074
Richard Smithcc36f692011-12-22 02:22:31 +00003075 const CXXRecordDecl *RD = FD->getParent();
3076 if (RD->isUnion())
3077 Result = APValue((FieldDecl*)0);
3078 else
3079 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3080 std::distance(RD->field_begin(), RD->field_end()));
3081 return true;
3082 }
3083
Richard Smithd62306a2011-11-10 06:34:14 +00003084 const FunctionDecl *Definition = 0;
3085 FD->getBody(Definition);
3086
Richard Smith357362d2011-12-13 06:39:58 +00003087 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3088 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003089
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003090 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003091 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003092 if (const MaterializeTemporaryExpr *ME
3093 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3094 return Visit(ME->GetTemporaryExpr());
3095
Richard Smithfddd3842011-12-30 21:15:51 +00003096 if (ZeroInit && !ZeroInitialization(E))
3097 return false;
3098
Richard Smithd62306a2011-11-10 06:34:14 +00003099 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003100 return HandleConstructorCall(E, This, Args,
3101 cast<CXXConstructorDecl>(Definition), Info,
3102 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003103}
3104
3105static bool EvaluateRecord(const Expr *E, const LValue &This,
3106 APValue &Result, EvalInfo &Info) {
3107 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003108 "can't evaluate expression as a record rvalue");
3109 return RecordExprEvaluator(Info, This, Result).Visit(E);
3110}
3111
3112//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003113// Temporary Evaluation
3114//
3115// Temporaries are represented in the AST as rvalues, but generally behave like
3116// lvalues. The full-object of which the temporary is a subobject is implicitly
3117// materialized so that a reference can bind to it.
3118//===----------------------------------------------------------------------===//
3119namespace {
3120class TemporaryExprEvaluator
3121 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3122public:
3123 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3124 LValueExprEvaluatorBaseTy(Info, Result) {}
3125
3126 /// Visit an expression which constructs the value of this temporary.
3127 bool VisitConstructExpr(const Expr *E) {
3128 Result.set(E, Info.CurrentCall);
3129 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3130 Result, E);
3131 }
3132
3133 bool VisitCastExpr(const CastExpr *E) {
3134 switch (E->getCastKind()) {
3135 default:
3136 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3137
3138 case CK_ConstructorConversion:
3139 return VisitConstructExpr(E->getSubExpr());
3140 }
3141 }
3142 bool VisitInitListExpr(const InitListExpr *E) {
3143 return VisitConstructExpr(E);
3144 }
3145 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3146 return VisitConstructExpr(E);
3147 }
3148 bool VisitCallExpr(const CallExpr *E) {
3149 return VisitConstructExpr(E);
3150 }
3151};
3152} // end anonymous namespace
3153
3154/// Evaluate an expression of record type as a temporary.
3155static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003156 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003157 return TemporaryExprEvaluator(Info, Result).Visit(E);
3158}
3159
3160//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003161// Vector Evaluation
3162//===----------------------------------------------------------------------===//
3163
3164namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003165 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003166 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3167 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003168 public:
Mike Stump11289f42009-09-09 15:08:12 +00003169
Richard Smith2d406342011-10-22 21:10:00 +00003170 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3171 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003172
Richard Smith2d406342011-10-22 21:10:00 +00003173 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3174 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3175 // FIXME: remove this APValue copy.
3176 Result = APValue(V.data(), V.size());
3177 return true;
3178 }
Richard Smithed5165f2011-11-04 05:33:44 +00003179 bool Success(const CCValue &V, const Expr *E) {
3180 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003181 Result = V;
3182 return true;
3183 }
Richard Smithfddd3842011-12-30 21:15:51 +00003184 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Richard Smith2d406342011-10-22 21:10:00 +00003186 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003187 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003188 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003189 bool VisitInitListExpr(const InitListExpr *E);
3190 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003191 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003192 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003193 // shufflevector, ExtVectorElementExpr
3194 // (Note that these require implementing conversions
3195 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003196 };
3197} // end anonymous namespace
3198
3199static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003200 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003201 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003202}
3203
Richard Smith2d406342011-10-22 21:10:00 +00003204bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3205 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003206 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003207
Richard Smith161f09a2011-12-06 22:44:34 +00003208 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003209 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003210
Eli Friedmanc757de22011-03-25 00:43:55 +00003211 switch (E->getCastKind()) {
3212 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003213 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003214 if (SETy->isIntegerType()) {
3215 APSInt IntResult;
3216 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003217 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003218 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003219 } else if (SETy->isRealFloatingType()) {
3220 APFloat F(0.0);
3221 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003222 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003223 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003224 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003225 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003226 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003227
3228 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003229 SmallVector<APValue, 4> Elts(NElts, Val);
3230 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003231 }
Eli Friedman803acb32011-12-22 03:51:45 +00003232 case CK_BitCast: {
3233 // Evaluate the operand into an APInt we can extract from.
3234 llvm::APInt SValInt;
3235 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3236 return false;
3237 // Extract the elements
3238 QualType EltTy = VTy->getElementType();
3239 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3240 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3241 SmallVector<APValue, 4> Elts;
3242 if (EltTy->isRealFloatingType()) {
3243 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3244 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3245 unsigned FloatEltSize = EltSize;
3246 if (&Sem == &APFloat::x87DoubleExtended)
3247 FloatEltSize = 80;
3248 for (unsigned i = 0; i < NElts; i++) {
3249 llvm::APInt Elt;
3250 if (BigEndian)
3251 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3252 else
3253 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3254 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3255 }
3256 } else if (EltTy->isIntegerType()) {
3257 for (unsigned i = 0; i < NElts; i++) {
3258 llvm::APInt Elt;
3259 if (BigEndian)
3260 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3261 else
3262 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3263 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3264 }
3265 } else {
3266 return Error(E);
3267 }
3268 return Success(Elts, E);
3269 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003270 default:
Richard Smith11562c52011-10-28 17:51:58 +00003271 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003272 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003273}
3274
Richard Smith2d406342011-10-22 21:10:00 +00003275bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003276VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003277 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003278 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003279 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003280
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003281 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003282 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003283
Eli Friedmanb9c71292012-01-03 23:24:20 +00003284 // The number of initializers can be less than the number of
3285 // vector elements. For OpenCL, this can be due to nested vector
3286 // initialization. For GCC compatibility, missing trailing elements
3287 // should be initialized with zeroes.
3288 unsigned CountInits = 0, CountElts = 0;
3289 while (CountElts < NumElements) {
3290 // Handle nested vector initialization.
3291 if (CountInits < NumInits
3292 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3293 APValue v;
3294 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3295 return Error(E);
3296 unsigned vlen = v.getVectorLength();
3297 for (unsigned j = 0; j < vlen; j++)
3298 Elements.push_back(v.getVectorElt(j));
3299 CountElts += vlen;
3300 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003301 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003302 if (CountInits < NumInits) {
3303 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3304 return Error(E);
3305 } else // trailing integer zero.
3306 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3307 Elements.push_back(APValue(sInt));
3308 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003309 } else {
3310 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003311 if (CountInits < NumInits) {
3312 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3313 return Error(E);
3314 } else // trailing float zero.
3315 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3316 Elements.push_back(APValue(f));
3317 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003318 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003319 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003320 }
Richard Smith2d406342011-10-22 21:10:00 +00003321 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003322}
3323
Richard Smith2d406342011-10-22 21:10:00 +00003324bool
Richard Smithfddd3842011-12-30 21:15:51 +00003325VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003326 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003327 QualType EltTy = VT->getElementType();
3328 APValue ZeroElement;
3329 if (EltTy->isIntegerType())
3330 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3331 else
3332 ZeroElement =
3333 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3334
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003335 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003336 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003337}
3338
Richard Smith2d406342011-10-22 21:10:00 +00003339bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003340 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003341 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003342}
3343
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003344//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003345// Array Evaluation
3346//===----------------------------------------------------------------------===//
3347
3348namespace {
3349 class ArrayExprEvaluator
3350 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003351 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003352 APValue &Result;
3353 public:
3354
Richard Smithd62306a2011-11-10 06:34:14 +00003355 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3356 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003357
3358 bool Success(const APValue &V, const Expr *E) {
3359 assert(V.isArray() && "Expected array type");
3360 Result = V;
3361 return true;
3362 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003363
Richard Smithfddd3842011-12-30 21:15:51 +00003364 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003365 const ConstantArrayType *CAT =
3366 Info.Ctx.getAsConstantArrayType(E->getType());
3367 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003368 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003369
3370 Result = APValue(APValue::UninitArray(), 0,
3371 CAT->getSize().getZExtValue());
3372 if (!Result.hasArrayFiller()) return true;
3373
Richard Smithfddd3842011-12-30 21:15:51 +00003374 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003375 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003376 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003377 ImplicitValueInitExpr VIE(CAT->getElementType());
3378 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3379 Subobject, &VIE);
3380 }
3381
Richard Smithf3e9e432011-11-07 09:22:26 +00003382 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003383 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003384 };
3385} // end anonymous namespace
3386
Richard Smithd62306a2011-11-10 06:34:14 +00003387static bool EvaluateArray(const Expr *E, const LValue &This,
3388 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003389 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003390 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003391}
3392
3393bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3394 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3395 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003396 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003397
Richard Smithca2cfbf2011-12-22 01:07:19 +00003398 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3399 // an appropriately-typed string literal enclosed in braces.
3400 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3401 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3402 LValue LV;
3403 if (!EvaluateLValue(E->getInit(0), LV, Info))
3404 return false;
3405 uint64_t NumElements = CAT->getSize().getZExtValue();
3406 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3407
3408 // Copy the string literal into the array. FIXME: Do this better.
Richard Smitha8105bc2012-01-06 16:39:00 +00003409 LV.addArray(Info, E, CAT);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003410 for (uint64_t I = 0; I < NumElements; ++I) {
3411 CCValue Char;
3412 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3413 CAT->getElementType(), LV, Char))
3414 return false;
3415 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3416 Result.getArrayInitializedElt(I)))
3417 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003418 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3419 CAT->getElementType(), 1))
Richard Smithca2cfbf2011-12-22 01:07:19 +00003420 return false;
3421 }
3422 return true;
3423 }
3424
Richard Smithf3e9e432011-11-07 09:22:26 +00003425 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3426 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003427 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003428 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003429 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003430 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003431 I != End; ++I, ++Index) {
3432 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3433 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003434 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003435 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3436 CAT->getElementType(), 1))
Richard Smithd62306a2011-11-10 06:34:14 +00003437 return false;
3438 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003439
3440 if (!Result.hasArrayFiller()) return true;
3441 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003442 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3443 // but sometimes does:
3444 // struct S { constexpr S() : p(&p) {} void *p; };
3445 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003446 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003447 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003448}
3449
Richard Smith027bf112011-11-17 22:56:20 +00003450bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3451 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3452 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003453 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003454
3455 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3456 if (!Result.hasArrayFiller())
3457 return true;
3458
3459 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003460
Richard Smithfddd3842011-12-30 21:15:51 +00003461 bool ZeroInit = E->requiresZeroInitialization();
3462 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3463 if (ZeroInit) {
3464 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003465 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003466 ImplicitValueInitExpr VIE(CAT->getElementType());
3467 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3468 Subobject, &VIE);
3469 }
3470
Richard Smithcc36f692011-12-22 02:22:31 +00003471 const CXXRecordDecl *RD = FD->getParent();
3472 if (RD->isUnion())
3473 Result.getArrayFiller() = APValue((FieldDecl*)0);
3474 else
3475 Result.getArrayFiller() =
3476 APValue(APValue::UninitStruct(), RD->getNumBases(),
3477 std::distance(RD->field_begin(), RD->field_end()));
3478 return true;
3479 }
3480
Richard Smith027bf112011-11-17 22:56:20 +00003481 const FunctionDecl *Definition = 0;
3482 FD->getBody(Definition);
3483
Richard Smith357362d2011-12-13 06:39:58 +00003484 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3485 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003486
3487 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3488 // but sometimes does:
3489 // struct S { constexpr S() : p(&p) {} void *p; };
3490 // S s[10];
3491 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003492 Subobject.addArray(Info, E, CAT);
Richard Smithfddd3842011-12-30 21:15:51 +00003493
3494 if (ZeroInit) {
3495 ImplicitValueInitExpr VIE(CAT->getElementType());
3496 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3497 &VIE))
3498 return false;
3499 }
3500
Richard Smith027bf112011-11-17 22:56:20 +00003501 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003502 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003503 cast<CXXConstructorDecl>(Definition),
3504 Info, Result.getArrayFiller());
3505}
3506
Richard Smithf3e9e432011-11-07 09:22:26 +00003507//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003508// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003509//
3510// As a GNU extension, we support casting pointers to sufficiently-wide integer
3511// types and back in constant folding. Integer values are thus represented
3512// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003513//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003514
3515namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003516class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003517 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003518 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003519public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003520 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003521 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003522
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003523 bool Success(const llvm::APSInt &SI, const Expr *E) {
3524 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003525 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003526 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003527 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003528 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003529 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003530 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003531 return true;
3532 }
3533
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003534 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003535 assert(E->getType()->isIntegralOrEnumerationType() &&
3536 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003537 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003538 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003539 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003540 Result.getInt().setIsUnsigned(
3541 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003542 return true;
3543 }
3544
3545 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003546 assert(E->getType()->isIntegralOrEnumerationType() &&
3547 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003548 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003549 return true;
3550 }
3551
Ken Dyckdbc01912011-03-11 02:13:43 +00003552 bool Success(CharUnits Size, const Expr *E) {
3553 return Success(Size.getQuantity(), E);
3554 }
3555
Richard Smith0b0a0b62011-10-29 20:57:55 +00003556 bool Success(const CCValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003557 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003558 Result = V;
3559 return true;
3560 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003561 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003562 }
Mike Stump11289f42009-09-09 15:08:12 +00003563
Richard Smithfddd3842011-12-30 21:15:51 +00003564 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003565
Peter Collingbournee9200682011-05-13 03:29:01 +00003566 //===--------------------------------------------------------------------===//
3567 // Visitor Methods
3568 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003569
Chris Lattner7174bf32008-07-12 00:38:25 +00003570 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003571 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003572 }
3573 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003574 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003575 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003576
3577 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3578 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003579 if (CheckReferencedDecl(E, E->getDecl()))
3580 return true;
3581
3582 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003583 }
3584 bool VisitMemberExpr(const MemberExpr *E) {
3585 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003586 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003587 return true;
3588 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003589
3590 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003591 }
3592
Peter Collingbournee9200682011-05-13 03:29:01 +00003593 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003594 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003595 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003596 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003597
Peter Collingbournee9200682011-05-13 03:29:01 +00003598 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003599 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003600
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003601 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003602 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003603 }
Mike Stump11289f42009-09-09 15:08:12 +00003604
Richard Smith4ce706a2011-10-11 21:43:33 +00003605 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003606 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003607 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003608 }
3609
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003610 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003611 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003612 }
3613
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003614 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3615 return Success(E->getValue(), E);
3616 }
3617
John Wiegley6242b6a2011-04-28 00:16:57 +00003618 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3619 return Success(E->getValue(), E);
3620 }
3621
John Wiegleyf9f65842011-04-25 06:54:41 +00003622 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3623 return Success(E->getValue(), E);
3624 }
3625
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003626 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003627 bool VisitUnaryImag(const UnaryOperator *E);
3628
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003629 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003630 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003631
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003632private:
Ken Dyck160146e2010-01-27 17:10:57 +00003633 CharUnits GetAlignOfExpr(const Expr *E);
3634 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003635 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003636 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003637 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003638};
Chris Lattner05706e882008-07-11 18:11:29 +00003639} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003640
Richard Smith11562c52011-10-28 17:51:58 +00003641/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3642/// produce either the integer value or a pointer.
3643///
3644/// GCC has a heinous extension which folds casts between pointer types and
3645/// pointer-sized integral types. We support this by allowing the evaluation of
3646/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3647/// Some simple arithmetic on such values is supported (they are treated much
3648/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003649static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003650 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003651 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003652 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003653}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003654
Richard Smithf57d8cb2011-12-09 22:58:01 +00003655static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003656 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003657 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003658 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003659 if (!Val.isInt()) {
3660 // FIXME: It would be better to produce the diagnostic for casting
3661 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003662 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003663 return false;
3664 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003665 Result = Val.getInt();
3666 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003667}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003668
Richard Smithf57d8cb2011-12-09 22:58:01 +00003669/// Check whether the given declaration can be directly converted to an integral
3670/// rvalue. If not, no diagnostic is produced; there are other things we can
3671/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003672bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003673 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003674 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003675 // Check for signedness/width mismatches between E type and ECD value.
3676 bool SameSign = (ECD->getInitVal().isSigned()
3677 == E->getType()->isSignedIntegerOrEnumerationType());
3678 bool SameWidth = (ECD->getInitVal().getBitWidth()
3679 == Info.Ctx.getIntWidth(E->getType()));
3680 if (SameSign && SameWidth)
3681 return Success(ECD->getInitVal(), E);
3682 else {
3683 // Get rid of mismatch (otherwise Success assertions will fail)
3684 // by computing a new value matching the type of E.
3685 llvm::APSInt Val = ECD->getInitVal();
3686 if (!SameSign)
3687 Val.setIsSigned(!ECD->getInitVal().isSigned());
3688 if (!SameWidth)
3689 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3690 return Success(Val, E);
3691 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003692 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003693 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003694}
3695
Chris Lattner86ee2862008-10-06 06:40:35 +00003696/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3697/// as GCC.
3698static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3699 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003700 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003701 enum gcc_type_class {
3702 no_type_class = -1,
3703 void_type_class, integer_type_class, char_type_class,
3704 enumeral_type_class, boolean_type_class,
3705 pointer_type_class, reference_type_class, offset_type_class,
3706 real_type_class, complex_type_class,
3707 function_type_class, method_type_class,
3708 record_type_class, union_type_class,
3709 array_type_class, string_type_class,
3710 lang_type_class
3711 };
Mike Stump11289f42009-09-09 15:08:12 +00003712
3713 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003714 // ideal, however it is what gcc does.
3715 if (E->getNumArgs() == 0)
3716 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003717
Chris Lattner86ee2862008-10-06 06:40:35 +00003718 QualType ArgTy = E->getArg(0)->getType();
3719 if (ArgTy->isVoidType())
3720 return void_type_class;
3721 else if (ArgTy->isEnumeralType())
3722 return enumeral_type_class;
3723 else if (ArgTy->isBooleanType())
3724 return boolean_type_class;
3725 else if (ArgTy->isCharType())
3726 return string_type_class; // gcc doesn't appear to use char_type_class
3727 else if (ArgTy->isIntegerType())
3728 return integer_type_class;
3729 else if (ArgTy->isPointerType())
3730 return pointer_type_class;
3731 else if (ArgTy->isReferenceType())
3732 return reference_type_class;
3733 else if (ArgTy->isRealType())
3734 return real_type_class;
3735 else if (ArgTy->isComplexType())
3736 return complex_type_class;
3737 else if (ArgTy->isFunctionType())
3738 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003739 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003740 return record_type_class;
3741 else if (ArgTy->isUnionType())
3742 return union_type_class;
3743 else if (ArgTy->isArrayType())
3744 return array_type_class;
3745 else if (ArgTy->isUnionType())
3746 return union_type_class;
3747 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003748 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003749 return -1;
3750}
3751
Richard Smith5fab0c92011-12-28 19:48:30 +00003752/// EvaluateBuiltinConstantPForLValue - Determine the result of
3753/// __builtin_constant_p when applied to the given lvalue.
3754///
3755/// An lvalue is only "constant" if it is a pointer or reference to the first
3756/// character of a string literal.
3757template<typename LValue>
3758static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3759 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3760 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3761}
3762
3763/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3764/// GCC as we can manage.
3765static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3766 QualType ArgType = Arg->getType();
3767
3768 // __builtin_constant_p always has one operand. The rules which gcc follows
3769 // are not precisely documented, but are as follows:
3770 //
3771 // - If the operand is of integral, floating, complex or enumeration type,
3772 // and can be folded to a known value of that type, it returns 1.
3773 // - If the operand and can be folded to a pointer to the first character
3774 // of a string literal (or such a pointer cast to an integral type), it
3775 // returns 1.
3776 //
3777 // Otherwise, it returns 0.
3778 //
3779 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3780 // its support for this does not currently work.
3781 if (ArgType->isIntegralOrEnumerationType()) {
3782 Expr::EvalResult Result;
3783 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3784 return false;
3785
3786 APValue &V = Result.Val;
3787 if (V.getKind() == APValue::Int)
3788 return true;
3789
3790 return EvaluateBuiltinConstantPForLValue(V);
3791 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3792 return Arg->isEvaluatable(Ctx);
3793 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3794 LValue LV;
3795 Expr::EvalStatus Status;
3796 EvalInfo Info(Ctx, Status);
3797 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3798 : EvaluatePointer(Arg, LV, Info)) &&
3799 !Status.HasSideEffects)
3800 return EvaluateBuiltinConstantPForLValue(LV);
3801 }
3802
3803 // Anything else isn't considered to be sufficiently constant.
3804 return false;
3805}
3806
John McCall95007602010-05-10 23:27:23 +00003807/// Retrieves the "underlying object type" of the given expression,
3808/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003809QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3810 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3811 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003812 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003813 } else if (const Expr *E = B.get<const Expr*>()) {
3814 if (isa<CompoundLiteralExpr>(E))
3815 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003816 }
3817
3818 return QualType();
3819}
3820
Peter Collingbournee9200682011-05-13 03:29:01 +00003821bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003822 // TODO: Perhaps we should let LLVM lower this?
3823 LValue Base;
3824 if (!EvaluatePointer(E->getArg(0), Base, Info))
3825 return false;
3826
3827 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003828 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003829
Richard Smithce40ad62011-11-12 22:28:03 +00003830 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003831 if (T.isNull() ||
3832 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003833 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003834 T->isVariablyModifiedType() ||
3835 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003836 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003837
3838 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3839 CharUnits Offset = Base.getLValueOffset();
3840
3841 if (!Offset.isNegative() && Offset <= Size)
3842 Size -= Offset;
3843 else
3844 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003845 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003846}
3847
Peter Collingbournee9200682011-05-13 03:29:01 +00003848bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003849 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003850 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003851 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003852
3853 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003854 if (TryEvaluateBuiltinObjectSize(E))
3855 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003856
Eric Christopher99469702010-01-19 22:58:35 +00003857 // If evaluating the argument has side-effects we can't determine
3858 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003859 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003860 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003861 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003862 return Success(0, E);
3863 }
Mike Stump876387b2009-10-27 22:09:17 +00003864
Richard Smithf57d8cb2011-12-09 22:58:01 +00003865 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003866 }
3867
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003868 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003869 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003870
Richard Smith5fab0c92011-12-28 19:48:30 +00003871 case Builtin::BI__builtin_constant_p:
3872 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003873
Chris Lattnerd545ad12009-09-23 06:06:36 +00003874 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003875 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003876 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003877 return Success(Operand, E);
3878 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003879
3880 case Builtin::BI__builtin_expect:
3881 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003882
3883 case Builtin::BIstrlen:
3884 case Builtin::BI__builtin_strlen:
3885 // As an extension, we support strlen() and __builtin_strlen() as constant
3886 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003887 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003888 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3889 // The string literal may have embedded null characters. Find the first
3890 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003891 StringRef Str = S->getString();
3892 StringRef::size_type Pos = Str.find(0);
3893 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003894 Str = Str.substr(0, Pos);
3895
3896 return Success(Str.size(), E);
3897 }
3898
Richard Smithf57d8cb2011-12-09 22:58:01 +00003899 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003900
3901 case Builtin::BI__atomic_is_lock_free: {
3902 APSInt SizeVal;
3903 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3904 return false;
3905
3906 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3907 // of two less than the maximum inline atomic width, we know it is
3908 // lock-free. If the size isn't a power of two, or greater than the
3909 // maximum alignment where we promote atomics, we know it is not lock-free
3910 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3911 // the answer can only be determined at runtime; for example, 16-byte
3912 // atomics have lock-free implementations on some, but not all,
3913 // x86-64 processors.
3914
3915 // Check power-of-two.
3916 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3917 if (!Size.isPowerOfTwo())
3918#if 0
3919 // FIXME: Suppress this folding until the ABI for the promotion width
3920 // settles.
3921 return Success(0, E);
3922#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003923 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003924#endif
3925
3926#if 0
3927 // Check against promotion width.
3928 // FIXME: Suppress this folding until the ABI for the promotion width
3929 // settles.
3930 unsigned PromoteWidthBits =
3931 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3932 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3933 return Success(0, E);
3934#endif
3935
3936 // Check against inlining width.
3937 unsigned InlineWidthBits =
3938 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3939 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3940 return Success(1, E);
3941
Richard Smithf57d8cb2011-12-09 22:58:01 +00003942 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003943 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003944 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003945}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003946
Richard Smith8b3497e2011-10-31 01:37:14 +00003947static bool HasSameBase(const LValue &A, const LValue &B) {
3948 if (!A.getLValueBase())
3949 return !B.getLValueBase();
3950 if (!B.getLValueBase())
3951 return false;
3952
Richard Smithce40ad62011-11-12 22:28:03 +00003953 if (A.getLValueBase().getOpaqueValue() !=
3954 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003955 const Decl *ADecl = GetLValueBaseDecl(A);
3956 if (!ADecl)
3957 return false;
3958 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003959 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003960 return false;
3961 }
3962
3963 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003964 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003965}
3966
Chris Lattnere13042c2008-07-11 19:10:17 +00003967bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003968 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003969 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003970
John McCalle3027922010-08-25 11:45:40 +00003971 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003972 VisitIgnoredValue(E->getLHS());
3973 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003974 }
3975
3976 if (E->isLogicalOp()) {
3977 // These need to be handled specially because the operands aren't
3978 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003979 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003980
Richard Smith11562c52011-10-28 17:51:58 +00003981 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003982 // We were able to evaluate the LHS, see if we can get away with not
3983 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003984 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003985 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003986
Richard Smith11562c52011-10-28 17:51:58 +00003987 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003988 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003989 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003990 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003991 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003992 }
3993 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003994 // FIXME: If both evaluations fail, we should produce the diagnostic from
3995 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3996 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003997 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003998 // We can't evaluate the LHS; however, sometimes the result
3999 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004000 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004001 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00004002 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00004003 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004004
4005 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00004006 }
4007 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00004008 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00004009
Eli Friedman5a332ea2008-11-13 06:09:17 +00004010 return false;
4011 }
4012
Anders Carlssonacc79812008-11-16 07:17:21 +00004013 QualType LHSTy = E->getLHS()->getType();
4014 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004015
4016 if (LHSTy->isAnyComplexType()) {
4017 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004018 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004019
4020 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4021 return false;
4022
4023 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4024 return false;
4025
4026 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004027 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004028 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004029 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004030 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4031
John McCalle3027922010-08-25 11:45:40 +00004032 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004033 return Success((CR_r == APFloat::cmpEqual &&
4034 CR_i == APFloat::cmpEqual), E);
4035 else {
John McCalle3027922010-08-25 11:45:40 +00004036 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004037 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004038 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004039 CR_r == APFloat::cmpLessThan ||
4040 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004041 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004042 CR_i == APFloat::cmpLessThan ||
4043 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004044 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004045 } else {
John McCalle3027922010-08-25 11:45:40 +00004046 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004047 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4048 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4049 else {
John McCalle3027922010-08-25 11:45:40 +00004050 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004051 "Invalid compex comparison.");
4052 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4053 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4054 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004055 }
4056 }
Mike Stump11289f42009-09-09 15:08:12 +00004057
Anders Carlssonacc79812008-11-16 07:17:21 +00004058 if (LHSTy->isRealFloatingType() &&
4059 RHSTy->isRealFloatingType()) {
4060 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004061
Anders Carlssonacc79812008-11-16 07:17:21 +00004062 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4063 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004064
Anders Carlssonacc79812008-11-16 07:17:21 +00004065 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4066 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004067
Anders Carlssonacc79812008-11-16 07:17:21 +00004068 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004069
Anders Carlssonacc79812008-11-16 07:17:21 +00004070 switch (E->getOpcode()) {
4071 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004072 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004073 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004074 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004075 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004076 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004077 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004078 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004079 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004080 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004081 E);
John McCalle3027922010-08-25 11:45:40 +00004082 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004083 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004084 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004085 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004086 || CR == APFloat::cmpLessThan
4087 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004088 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004089 }
Mike Stump11289f42009-09-09 15:08:12 +00004090
Eli Friedmana38da572009-04-28 19:17:36 +00004091 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004092 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00004093 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004094 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4095 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004096
John McCall45d55e42010-05-07 21:00:08 +00004097 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004098 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4099 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004100
Richard Smith8b3497e2011-10-31 01:37:14 +00004101 // Reject differing bases from the normal codepath; we special-case
4102 // comparisons to null.
4103 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004104 if (E->getOpcode() == BO_Sub) {
4105 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004106 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4107 return false;
4108 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4109 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4110 if (!LHSExpr || !RHSExpr)
4111 return false;
4112 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4113 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4114 if (!LHSAddrExpr || !RHSAddrExpr)
4115 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004116 // Make sure both labels come from the same function.
4117 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4118 RHSAddrExpr->getLabel()->getDeclContext())
4119 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004120 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4121 return true;
4122 }
Richard Smith83c68212011-10-31 05:11:32 +00004123 // Inequalities and subtractions between unrelated pointers have
4124 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004125 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004126 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004127 // A constant address may compare equal to the address of a symbol.
4128 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004129 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004130 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4131 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004132 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004133 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004134 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004135 // distinct. However, we do know that the address of a literal will be
4136 // non-null.
4137 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4138 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004139 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004140 // We can't tell whether weak symbols will end up pointing to the same
4141 // object.
4142 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004143 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004144 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004145 // (Note that clang defaults to -fmerge-all-constants, which can
4146 // lead to inconsistent results for comparisons involving the address
4147 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004148 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004149 }
Eli Friedman64004332009-03-23 04:38:34 +00004150
Richard Smithf3e9e432011-11-07 09:22:26 +00004151 // FIXME: Implement the C++11 restrictions:
4152 // - Pointer subtractions must be on elements of the same array.
4153 // - Pointer comparisons must be between members with the same access.
4154
John McCalle3027922010-08-25 11:45:40 +00004155 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004156 QualType Type = E->getLHS()->getType();
4157 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004158
Richard Smithd62306a2011-11-10 06:34:14 +00004159 CharUnits ElementSize;
4160 if (!HandleSizeof(Info, ElementType, ElementSize))
4161 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004162
Richard Smithd62306a2011-11-10 06:34:14 +00004163 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004164 RHSValue.getLValueOffset();
4165 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004166 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004167
4168 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4169 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4170 switch (E->getOpcode()) {
4171 default: llvm_unreachable("missing comparison operator");
4172 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4173 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4174 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4175 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4176 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4177 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004178 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004179 }
4180 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004181 if (!LHSTy->isIntegralOrEnumerationType() ||
4182 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004183 // We can't continue from here for non-integral types.
4184 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004185 }
4186
Anders Carlsson9c181652008-07-08 14:35:21 +00004187 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004188 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004189 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004190 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004191
Richard Smith11562c52011-10-28 17:51:58 +00004192 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004193 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004194 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004195
4196 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004197 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004198 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4199 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004200 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004201 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004202 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004203 LHSVal.getLValueOffset() -= AdditionalOffset;
4204 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004205 return true;
4206 }
4207
4208 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004209 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004210 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004211 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4212 LHSVal.getInt().getZExtValue());
4213 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004214 return true;
4215 }
4216
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004217 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4218 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004219 if (!LHSVal.getLValueOffset().isZero() ||
4220 !RHSVal.getLValueOffset().isZero())
4221 return false;
4222 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4223 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4224 if (!LHSExpr || !RHSExpr)
4225 return false;
4226 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4227 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4228 if (!LHSAddrExpr || !RHSAddrExpr)
4229 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004230 // Make sure both labels come from the same function.
4231 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4232 RHSAddrExpr->getLabel()->getDeclContext())
4233 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004234 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4235 return true;
4236 }
4237
Eli Friedman94c25c62009-03-24 01:14:50 +00004238 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004239 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004240 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004241
Richard Smith11562c52011-10-28 17:51:58 +00004242 APSInt &LHS = LHSVal.getInt();
4243 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004244
Anders Carlsson9c181652008-07-08 14:35:21 +00004245 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004246 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004247 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004248 case BO_Mul: return Success(LHS * RHS, E);
4249 case BO_Add: return Success(LHS + RHS, E);
4250 case BO_Sub: return Success(LHS - RHS, E);
4251 case BO_And: return Success(LHS & RHS, E);
4252 case BO_Xor: return Success(LHS ^ RHS, E);
4253 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004254 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004255 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004257 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004258 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004259 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004260 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004261 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004262 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004263 // During constant-folding, a negative shift is an opposite shift.
4264 if (RHS.isSigned() && RHS.isNegative()) {
4265 RHS = -RHS;
4266 goto shift_right;
4267 }
4268
4269 shift_left:
4270 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004271 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4272 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004273 }
John McCalle3027922010-08-25 11:45:40 +00004274 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004275 // During constant-folding, a negative shift is an opposite shift.
4276 if (RHS.isSigned() && RHS.isNegative()) {
4277 RHS = -RHS;
4278 goto shift_left;
4279 }
4280
4281 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004282 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004283 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4284 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Richard Smith11562c52011-10-28 17:51:58 +00004287 case BO_LT: return Success(LHS < RHS, E);
4288 case BO_GT: return Success(LHS > RHS, E);
4289 case BO_LE: return Success(LHS <= RHS, E);
4290 case BO_GE: return Success(LHS >= RHS, E);
4291 case BO_EQ: return Success(LHS == RHS, E);
4292 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004293 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004294}
4295
Ken Dyck160146e2010-01-27 17:10:57 +00004296CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004297 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4298 // the result is the size of the referenced type."
4299 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4300 // result shall be the alignment of the referenced type."
4301 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4302 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004303
4304 // __alignof is defined to return the preferred alignment.
4305 return Info.Ctx.toCharUnitsFromBits(
4306 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004307}
4308
Ken Dyck160146e2010-01-27 17:10:57 +00004309CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004310 E = E->IgnoreParens();
4311
4312 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004313 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004314 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004315 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4316 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004317
Chris Lattner68061312009-01-24 21:53:27 +00004318 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004319 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4320 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004321
Chris Lattner24aeeab2009-01-24 21:09:06 +00004322 return GetAlignOfType(E->getType());
4323}
4324
4325
Peter Collingbournee190dee2011-03-11 19:24:49 +00004326/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4327/// a result as the expression's type.
4328bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4329 const UnaryExprOrTypeTraitExpr *E) {
4330 switch(E->getKind()) {
4331 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004332 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004333 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004334 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004335 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004336 }
Eli Friedman64004332009-03-23 04:38:34 +00004337
Peter Collingbournee190dee2011-03-11 19:24:49 +00004338 case UETT_VecStep: {
4339 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004340
Peter Collingbournee190dee2011-03-11 19:24:49 +00004341 if (Ty->isVectorType()) {
4342 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004343
Peter Collingbournee190dee2011-03-11 19:24:49 +00004344 // The vec_step built-in functions that take a 3-component
4345 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4346 if (n == 3)
4347 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004348
Peter Collingbournee190dee2011-03-11 19:24:49 +00004349 return Success(n, E);
4350 } else
4351 return Success(1, E);
4352 }
4353
4354 case UETT_SizeOf: {
4355 QualType SrcTy = E->getTypeOfArgument();
4356 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4357 // the result is the size of the referenced type."
4358 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4359 // result shall be the alignment of the referenced type."
4360 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4361 SrcTy = Ref->getPointeeType();
4362
Richard Smithd62306a2011-11-10 06:34:14 +00004363 CharUnits Sizeof;
4364 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004365 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004366 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004367 }
4368 }
4369
4370 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004371 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004372}
4373
Peter Collingbournee9200682011-05-13 03:29:01 +00004374bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004375 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004376 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004377 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004378 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004379 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004380 for (unsigned i = 0; i != n; ++i) {
4381 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4382 switch (ON.getKind()) {
4383 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004384 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004385 APSInt IdxResult;
4386 if (!EvaluateInteger(Idx, IdxResult, Info))
4387 return false;
4388 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4389 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004390 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004391 CurrentType = AT->getElementType();
4392 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4393 Result += IdxResult.getSExtValue() * ElementSize;
4394 break;
4395 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004396
Douglas Gregor882211c2010-04-28 22:16:22 +00004397 case OffsetOfExpr::OffsetOfNode::Field: {
4398 FieldDecl *MemberDecl = ON.getField();
4399 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004400 if (!RT)
4401 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004402 RecordDecl *RD = RT->getDecl();
4403 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004404 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004405 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004406 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004407 CurrentType = MemberDecl->getType().getNonReferenceType();
4408 break;
4409 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004410
Douglas Gregor882211c2010-04-28 22:16:22 +00004411 case OffsetOfExpr::OffsetOfNode::Identifier:
4412 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004413 return Error(OOE);
4414
Douglas Gregord1702062010-04-29 00:18:15 +00004415 case OffsetOfExpr::OffsetOfNode::Base: {
4416 CXXBaseSpecifier *BaseSpec = ON.getBase();
4417 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004418 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004419
4420 // Find the layout of the class whose base we are looking into.
4421 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004422 if (!RT)
4423 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004424 RecordDecl *RD = RT->getDecl();
4425 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4426
4427 // Find the base class itself.
4428 CurrentType = BaseSpec->getType();
4429 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4430 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004431 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004432
4433 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004434 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004435 break;
4436 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004437 }
4438 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004439 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004440}
4441
Chris Lattnere13042c2008-07-11 19:10:17 +00004442bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004443 switch (E->getOpcode()) {
4444 default:
4445 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4446 // See C99 6.6p3.
4447 return Error(E);
4448 case UO_Extension:
4449 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4450 // If so, we could clear the diagnostic ID.
4451 return Visit(E->getSubExpr());
4452 case UO_Plus:
4453 // The result is just the value.
4454 return Visit(E->getSubExpr());
4455 case UO_Minus: {
4456 if (!Visit(E->getSubExpr()))
4457 return false;
4458 if (!Result.isInt()) return Error(E);
4459 return Success(-Result.getInt(), E);
4460 }
4461 case UO_Not: {
4462 if (!Visit(E->getSubExpr()))
4463 return false;
4464 if (!Result.isInt()) return Error(E);
4465 return Success(~Result.getInt(), E);
4466 }
4467 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004468 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004469 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004470 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004471 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004472 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004473 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004474}
Mike Stump11289f42009-09-09 15:08:12 +00004475
Chris Lattner477c4be2008-07-12 01:15:53 +00004476/// HandleCast - This is used to evaluate implicit or explicit casts where the
4477/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004478bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4479 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004480 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004481 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004482
Eli Friedmanc757de22011-03-25 00:43:55 +00004483 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004484 case CK_BaseToDerived:
4485 case CK_DerivedToBase:
4486 case CK_UncheckedDerivedToBase:
4487 case CK_Dynamic:
4488 case CK_ToUnion:
4489 case CK_ArrayToPointerDecay:
4490 case CK_FunctionToPointerDecay:
4491 case CK_NullToPointer:
4492 case CK_NullToMemberPointer:
4493 case CK_BaseToDerivedMemberPointer:
4494 case CK_DerivedToBaseMemberPointer:
4495 case CK_ConstructorConversion:
4496 case CK_IntegralToPointer:
4497 case CK_ToVoid:
4498 case CK_VectorSplat:
4499 case CK_IntegralToFloating:
4500 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004501 case CK_CPointerToObjCPointerCast:
4502 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004503 case CK_AnyPointerToBlockPointerCast:
4504 case CK_ObjCObjectLValueCast:
4505 case CK_FloatingRealToComplex:
4506 case CK_FloatingComplexToReal:
4507 case CK_FloatingComplexCast:
4508 case CK_FloatingComplexToIntegralComplex:
4509 case CK_IntegralRealToComplex:
4510 case CK_IntegralComplexCast:
4511 case CK_IntegralComplexToFloatingComplex:
4512 llvm_unreachable("invalid cast kind for integral value");
4513
Eli Friedman9faf2f92011-03-25 19:07:11 +00004514 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004515 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004516 case CK_LValueBitCast:
4517 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004518 case CK_ARCProduceObject:
4519 case CK_ARCConsumeObject:
4520 case CK_ARCReclaimReturnedObject:
4521 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004522 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004523
4524 case CK_LValueToRValue:
4525 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004526 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004527
4528 case CK_MemberPointerToBoolean:
4529 case CK_PointerToBoolean:
4530 case CK_IntegralToBoolean:
4531 case CK_FloatingToBoolean:
4532 case CK_FloatingComplexToBoolean:
4533 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004534 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004535 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004536 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004537 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004538 }
4539
Eli Friedmanc757de22011-03-25 00:43:55 +00004540 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004541 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004542 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004543
Eli Friedman742421e2009-02-20 01:15:07 +00004544 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004545 // Allow casts of address-of-label differences if they are no-ops
4546 // or narrowing. (The narrowing case isn't actually guaranteed to
4547 // be constant-evaluatable except in some narrow cases which are hard
4548 // to detect here. We let it through on the assumption the user knows
4549 // what they are doing.)
4550 if (Result.isAddrLabelDiff())
4551 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004552 // Only allow casts of lvalues if they are lossless.
4553 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4554 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004555
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004556 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004557 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004558 }
Mike Stump11289f42009-09-09 15:08:12 +00004559
Eli Friedmanc757de22011-03-25 00:43:55 +00004560 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004561 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4562
John McCall45d55e42010-05-07 21:00:08 +00004563 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004564 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004565 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004566
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004567 if (LV.getLValueBase()) {
4568 // Only allow based lvalue casts if they are lossless.
4569 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004570 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004571
Richard Smithcf74da72011-11-16 07:18:12 +00004572 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004573 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004574 return true;
4575 }
4576
Ken Dyck02990832010-01-15 12:37:54 +00004577 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4578 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004579 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004580 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004581
Eli Friedmanc757de22011-03-25 00:43:55 +00004582 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004583 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004584 if (!EvaluateComplex(SubExpr, C, Info))
4585 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004586 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004587 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004588
Eli Friedmanc757de22011-03-25 00:43:55 +00004589 case CK_FloatingToIntegral: {
4590 APFloat F(0.0);
4591 if (!EvaluateFloat(SubExpr, F, Info))
4592 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004593
Richard Smith357362d2011-12-13 06:39:58 +00004594 APSInt Value;
4595 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4596 return false;
4597 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004598 }
4599 }
Mike Stump11289f42009-09-09 15:08:12 +00004600
Eli Friedmanc757de22011-03-25 00:43:55 +00004601 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004602 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004603}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004604
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004605bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4606 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004607 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004608 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4609 return false;
4610 if (!LV.isComplexInt())
4611 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004612 return Success(LV.getComplexIntReal(), E);
4613 }
4614
4615 return Visit(E->getSubExpr());
4616}
4617
Eli Friedman4e7a2412009-02-27 04:45:43 +00004618bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004619 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004620 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004621 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4622 return false;
4623 if (!LV.isComplexInt())
4624 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004625 return Success(LV.getComplexIntImag(), E);
4626 }
4627
Richard Smith4a678122011-10-24 18:44:57 +00004628 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004629 return Success(0, E);
4630}
4631
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004632bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4633 return Success(E->getPackLength(), E);
4634}
4635
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004636bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4637 return Success(E->getValue(), E);
4638}
4639
Chris Lattner05706e882008-07-11 18:11:29 +00004640//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004641// Float Evaluation
4642//===----------------------------------------------------------------------===//
4643
4644namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004645class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004646 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004647 APFloat &Result;
4648public:
4649 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004650 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004651
Richard Smith0b0a0b62011-10-29 20:57:55 +00004652 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004653 Result = V.getFloat();
4654 return true;
4655 }
Eli Friedman24c01542008-08-22 00:06:13 +00004656
Richard Smithfddd3842011-12-30 21:15:51 +00004657 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004658 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4659 return true;
4660 }
4661
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004662 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004663
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004664 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004665 bool VisitBinaryOperator(const BinaryOperator *E);
4666 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004667 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004668
John McCallb1fb0d32010-05-07 22:08:54 +00004669 bool VisitUnaryReal(const UnaryOperator *E);
4670 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004671
Richard Smithfddd3842011-12-30 21:15:51 +00004672 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004673};
4674} // end anonymous namespace
4675
4676static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004677 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004678 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004679}
4680
Jay Foad39c79802011-01-12 09:06:06 +00004681static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004682 QualType ResultTy,
4683 const Expr *Arg,
4684 bool SNaN,
4685 llvm::APFloat &Result) {
4686 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4687 if (!S) return false;
4688
4689 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4690
4691 llvm::APInt fill;
4692
4693 // Treat empty strings as if they were zero.
4694 if (S->getString().empty())
4695 fill = llvm::APInt(32, 0);
4696 else if (S->getString().getAsInteger(0, fill))
4697 return false;
4698
4699 if (SNaN)
4700 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4701 else
4702 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4703 return true;
4704}
4705
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004706bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004707 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004708 default:
4709 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4710
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004711 case Builtin::BI__builtin_huge_val:
4712 case Builtin::BI__builtin_huge_valf:
4713 case Builtin::BI__builtin_huge_vall:
4714 case Builtin::BI__builtin_inf:
4715 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004716 case Builtin::BI__builtin_infl: {
4717 const llvm::fltSemantics &Sem =
4718 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004719 Result = llvm::APFloat::getInf(Sem);
4720 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722
John McCall16291492010-02-28 13:00:19 +00004723 case Builtin::BI__builtin_nans:
4724 case Builtin::BI__builtin_nansf:
4725 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4727 true, Result))
4728 return Error(E);
4729 return true;
John McCall16291492010-02-28 13:00:19 +00004730
Chris Lattner0b7282e2008-10-06 06:31:58 +00004731 case Builtin::BI__builtin_nan:
4732 case Builtin::BI__builtin_nanf:
4733 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004734 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004735 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004736 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4737 false, Result))
4738 return Error(E);
4739 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004740
4741 case Builtin::BI__builtin_fabs:
4742 case Builtin::BI__builtin_fabsf:
4743 case Builtin::BI__builtin_fabsl:
4744 if (!EvaluateFloat(E->getArg(0), Result, Info))
4745 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004746
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004747 if (Result.isNegative())
4748 Result.changeSign();
4749 return true;
4750
Mike Stump11289f42009-09-09 15:08:12 +00004751 case Builtin::BI__builtin_copysign:
4752 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004753 case Builtin::BI__builtin_copysignl: {
4754 APFloat RHS(0.);
4755 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4756 !EvaluateFloat(E->getArg(1), RHS, Info))
4757 return false;
4758 Result.copySign(RHS);
4759 return true;
4760 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004761 }
4762}
4763
John McCallb1fb0d32010-05-07 22:08:54 +00004764bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004765 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4766 ComplexValue CV;
4767 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4768 return false;
4769 Result = CV.FloatReal;
4770 return true;
4771 }
4772
4773 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004774}
4775
4776bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004777 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4778 ComplexValue CV;
4779 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4780 return false;
4781 Result = CV.FloatImag;
4782 return true;
4783 }
4784
Richard Smith4a678122011-10-24 18:44:57 +00004785 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004786 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4787 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004788 return true;
4789}
4790
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004791bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004792 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004793 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004794 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004795 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004796 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004797 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4798 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004799 Result.changeSign();
4800 return true;
4801 }
4802}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004803
Eli Friedman24c01542008-08-22 00:06:13 +00004804bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004805 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4806 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004807
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004808 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004809 if (!EvaluateFloat(E->getLHS(), Result, Info))
4810 return false;
4811 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4812 return false;
4813
4814 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004815 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004816 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004817 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4818 return true;
John McCalle3027922010-08-25 11:45:40 +00004819 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004820 Result.add(RHS, APFloat::rmNearestTiesToEven);
4821 return true;
John McCalle3027922010-08-25 11:45:40 +00004822 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004823 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4824 return true;
John McCalle3027922010-08-25 11:45:40 +00004825 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004826 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4827 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004828 }
4829}
4830
4831bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4832 Result = E->getValue();
4833 return true;
4834}
4835
Peter Collingbournee9200682011-05-13 03:29:01 +00004836bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4837 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004838
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004839 switch (E->getCastKind()) {
4840 default:
Richard Smith11562c52011-10-28 17:51:58 +00004841 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004842
4843 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004844 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004845 return EvaluateInteger(SubExpr, IntResult, Info) &&
4846 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4847 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004848 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004849
4850 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004851 if (!Visit(SubExpr))
4852 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004853 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4854 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004855 }
John McCalld7646252010-11-14 08:17:51 +00004856
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004857 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004858 ComplexValue V;
4859 if (!EvaluateComplex(SubExpr, V, Info))
4860 return false;
4861 Result = V.getComplexFloatReal();
4862 return true;
4863 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004864 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004865
Richard Smithf57d8cb2011-12-09 22:58:01 +00004866 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004867}
4868
Eli Friedman24c01542008-08-22 00:06:13 +00004869//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004870// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004871//===----------------------------------------------------------------------===//
4872
4873namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004874class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004875 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004876 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004877
Anders Carlsson537969c2008-11-16 20:27:53 +00004878public:
John McCall93d91dc2010-05-07 17:22:02 +00004879 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004880 : ExprEvaluatorBaseTy(info), Result(Result) {}
4881
Richard Smith0b0a0b62011-10-29 20:57:55 +00004882 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004883 Result.setFrom(V);
4884 return true;
4885 }
Mike Stump11289f42009-09-09 15:08:12 +00004886
Anders Carlsson537969c2008-11-16 20:27:53 +00004887 //===--------------------------------------------------------------------===//
4888 // Visitor Methods
4889 //===--------------------------------------------------------------------===//
4890
Peter Collingbournee9200682011-05-13 03:29:01 +00004891 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004892
Peter Collingbournee9200682011-05-13 03:29:01 +00004893 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004894
John McCall93d91dc2010-05-07 17:22:02 +00004895 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004896 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004897 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004898};
4899} // end anonymous namespace
4900
John McCall93d91dc2010-05-07 17:22:02 +00004901static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4902 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004903 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004904 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004905}
4906
Peter Collingbournee9200682011-05-13 03:29:01 +00004907bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4908 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004909
4910 if (SubExpr->getType()->isRealFloatingType()) {
4911 Result.makeComplexFloat();
4912 APFloat &Imag = Result.FloatImag;
4913 if (!EvaluateFloat(SubExpr, Imag, Info))
4914 return false;
4915
4916 Result.FloatReal = APFloat(Imag.getSemantics());
4917 return true;
4918 } else {
4919 assert(SubExpr->getType()->isIntegerType() &&
4920 "Unexpected imaginary literal.");
4921
4922 Result.makeComplexInt();
4923 APSInt &Imag = Result.IntImag;
4924 if (!EvaluateInteger(SubExpr, Imag, Info))
4925 return false;
4926
4927 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4928 return true;
4929 }
4930}
4931
Peter Collingbournee9200682011-05-13 03:29:01 +00004932bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004933
John McCallfcef3cf2010-12-14 17:51:41 +00004934 switch (E->getCastKind()) {
4935 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004936 case CK_BaseToDerived:
4937 case CK_DerivedToBase:
4938 case CK_UncheckedDerivedToBase:
4939 case CK_Dynamic:
4940 case CK_ToUnion:
4941 case CK_ArrayToPointerDecay:
4942 case CK_FunctionToPointerDecay:
4943 case CK_NullToPointer:
4944 case CK_NullToMemberPointer:
4945 case CK_BaseToDerivedMemberPointer:
4946 case CK_DerivedToBaseMemberPointer:
4947 case CK_MemberPointerToBoolean:
4948 case CK_ConstructorConversion:
4949 case CK_IntegralToPointer:
4950 case CK_PointerToIntegral:
4951 case CK_PointerToBoolean:
4952 case CK_ToVoid:
4953 case CK_VectorSplat:
4954 case CK_IntegralCast:
4955 case CK_IntegralToBoolean:
4956 case CK_IntegralToFloating:
4957 case CK_FloatingToIntegral:
4958 case CK_FloatingToBoolean:
4959 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004960 case CK_CPointerToObjCPointerCast:
4961 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004962 case CK_AnyPointerToBlockPointerCast:
4963 case CK_ObjCObjectLValueCast:
4964 case CK_FloatingComplexToReal:
4965 case CK_FloatingComplexToBoolean:
4966 case CK_IntegralComplexToReal:
4967 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004968 case CK_ARCProduceObject:
4969 case CK_ARCConsumeObject:
4970 case CK_ARCReclaimReturnedObject:
4971 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004972 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004973
John McCallfcef3cf2010-12-14 17:51:41 +00004974 case CK_LValueToRValue:
4975 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004976 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004977
4978 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004979 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004980 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004981 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004982
4983 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004984 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004985 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004986 return false;
4987
John McCallfcef3cf2010-12-14 17:51:41 +00004988 Result.makeComplexFloat();
4989 Result.FloatImag = APFloat(Real.getSemantics());
4990 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004991 }
4992
John McCallfcef3cf2010-12-14 17:51:41 +00004993 case CK_FloatingComplexCast: {
4994 if (!Visit(E->getSubExpr()))
4995 return false;
4996
4997 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4998 QualType From
4999 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5000
Richard Smith357362d2011-12-13 06:39:58 +00005001 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5002 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005003 }
5004
5005 case CK_FloatingComplexToIntegralComplex: {
5006 if (!Visit(E->getSubExpr()))
5007 return false;
5008
5009 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5010 QualType From
5011 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5012 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005013 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5014 To, Result.IntReal) &&
5015 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5016 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005017 }
5018
5019 case CK_IntegralRealToComplex: {
5020 APSInt &Real = Result.IntReal;
5021 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5022 return false;
5023
5024 Result.makeComplexInt();
5025 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5026 return true;
5027 }
5028
5029 case CK_IntegralComplexCast: {
5030 if (!Visit(E->getSubExpr()))
5031 return false;
5032
5033 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5034 QualType From
5035 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5036
5037 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5038 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5039 return true;
5040 }
5041
5042 case CK_IntegralComplexToFloatingComplex: {
5043 if (!Visit(E->getSubExpr()))
5044 return false;
5045
5046 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5047 QualType From
5048 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5049 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005050 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5051 To, Result.FloatReal) &&
5052 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5053 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005054 }
5055 }
5056
5057 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005058 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005059}
5060
John McCall93d91dc2010-05-07 17:22:02 +00005061bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005062 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005063 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5064
John McCall93d91dc2010-05-07 17:22:02 +00005065 if (!Visit(E->getLHS()))
5066 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005067
John McCall93d91dc2010-05-07 17:22:02 +00005068 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005069 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00005070 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005071
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005072 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5073 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005074 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005075 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005076 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005077 if (Result.isComplexFloat()) {
5078 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5079 APFloat::rmNearestTiesToEven);
5080 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5081 APFloat::rmNearestTiesToEven);
5082 } else {
5083 Result.getComplexIntReal() += RHS.getComplexIntReal();
5084 Result.getComplexIntImag() += RHS.getComplexIntImag();
5085 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005086 break;
John McCalle3027922010-08-25 11:45:40 +00005087 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005088 if (Result.isComplexFloat()) {
5089 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5090 APFloat::rmNearestTiesToEven);
5091 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5092 APFloat::rmNearestTiesToEven);
5093 } else {
5094 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5095 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5096 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005097 break;
John McCalle3027922010-08-25 11:45:40 +00005098 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005099 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00005100 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005101 APFloat &LHS_r = LHS.getComplexFloatReal();
5102 APFloat &LHS_i = LHS.getComplexFloatImag();
5103 APFloat &RHS_r = RHS.getComplexFloatReal();
5104 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005105
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005106 APFloat Tmp = LHS_r;
5107 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5108 Result.getComplexFloatReal() = Tmp;
5109 Tmp = LHS_i;
5110 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5111 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5112
5113 Tmp = LHS_r;
5114 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5115 Result.getComplexFloatImag() = Tmp;
5116 Tmp = LHS_i;
5117 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5118 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5119 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005120 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005121 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005122 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5123 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005124 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005125 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5126 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5127 }
5128 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005129 case BO_Div:
5130 if (Result.isComplexFloat()) {
5131 ComplexValue LHS = Result;
5132 APFloat &LHS_r = LHS.getComplexFloatReal();
5133 APFloat &LHS_i = LHS.getComplexFloatImag();
5134 APFloat &RHS_r = RHS.getComplexFloatReal();
5135 APFloat &RHS_i = RHS.getComplexFloatImag();
5136 APFloat &Res_r = Result.getComplexFloatReal();
5137 APFloat &Res_i = Result.getComplexFloatImag();
5138
5139 APFloat Den = RHS_r;
5140 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5141 APFloat Tmp = RHS_i;
5142 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5143 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5144
5145 Res_r = LHS_r;
5146 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5147 Tmp = LHS_i;
5148 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5149 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5150 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5151
5152 Res_i = LHS_i;
5153 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5154 Tmp = LHS_r;
5155 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5156 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5157 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5158 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005159 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5160 return Error(E, diag::note_expr_divide_by_zero);
5161
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005162 ComplexValue LHS = Result;
5163 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5164 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5165 Result.getComplexIntReal() =
5166 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5167 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5168 Result.getComplexIntImag() =
5169 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5170 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5171 }
5172 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005173 }
5174
John McCall93d91dc2010-05-07 17:22:02 +00005175 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005176}
5177
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005178bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5179 // Get the operand value into 'Result'.
5180 if (!Visit(E->getSubExpr()))
5181 return false;
5182
5183 switch (E->getOpcode()) {
5184 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005185 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005186 case UO_Extension:
5187 return true;
5188 case UO_Plus:
5189 // The result is always just the subexpr.
5190 return true;
5191 case UO_Minus:
5192 if (Result.isComplexFloat()) {
5193 Result.getComplexFloatReal().changeSign();
5194 Result.getComplexFloatImag().changeSign();
5195 }
5196 else {
5197 Result.getComplexIntReal() = -Result.getComplexIntReal();
5198 Result.getComplexIntImag() = -Result.getComplexIntImag();
5199 }
5200 return true;
5201 case UO_Not:
5202 if (Result.isComplexFloat())
5203 Result.getComplexFloatImag().changeSign();
5204 else
5205 Result.getComplexIntImag() = -Result.getComplexIntImag();
5206 return true;
5207 }
5208}
5209
Anders Carlsson537969c2008-11-16 20:27:53 +00005210//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005211// Void expression evaluation, primarily for a cast to void on the LHS of a
5212// comma operator
5213//===----------------------------------------------------------------------===//
5214
5215namespace {
5216class VoidExprEvaluator
5217 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5218public:
5219 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5220
5221 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005222
5223 bool VisitCastExpr(const CastExpr *E) {
5224 switch (E->getCastKind()) {
5225 default:
5226 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5227 case CK_ToVoid:
5228 VisitIgnoredValue(E->getSubExpr());
5229 return true;
5230 }
5231 }
5232};
5233} // end anonymous namespace
5234
5235static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5236 assert(E->isRValue() && E->getType()->isVoidType());
5237 return VoidExprEvaluator(Info).Visit(E);
5238}
5239
5240//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005241// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005242//===----------------------------------------------------------------------===//
5243
Richard Smith0b0a0b62011-10-29 20:57:55 +00005244static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005245 // In C, function designators are not lvalues, but we evaluate them as if they
5246 // are.
5247 if (E->isGLValue() || E->getType()->isFunctionType()) {
5248 LValue LV;
5249 if (!EvaluateLValue(E, LV, Info))
5250 return false;
5251 LV.moveInto(Result);
5252 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005253 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005254 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005255 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005256 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005257 return false;
John McCall45d55e42010-05-07 21:00:08 +00005258 } else if (E->getType()->hasPointerRepresentation()) {
5259 LValue LV;
5260 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005261 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005262 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005263 } else if (E->getType()->isRealFloatingType()) {
5264 llvm::APFloat F(0.0);
5265 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005266 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005267 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005268 } else if (E->getType()->isAnyComplexType()) {
5269 ComplexValue C;
5270 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005271 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005272 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005273 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005274 MemberPtr P;
5275 if (!EvaluateMemberPointer(E, P, Info))
5276 return false;
5277 P.moveInto(Result);
5278 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005279 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005280 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005281 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005282 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005283 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005284 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005285 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005286 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005287 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005288 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5289 return false;
5290 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005291 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005292 if (Info.getLangOpts().CPlusPlus0x)
5293 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5294 << E->getType();
5295 else
5296 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005297 if (!EvaluateVoid(E, Info))
5298 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005299 } else if (Info.getLangOpts().CPlusPlus0x) {
5300 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5301 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005302 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005303 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005304 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005305 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005306
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005307 return true;
5308}
5309
Richard Smithed5165f2011-11-04 05:33:44 +00005310/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5311/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5312/// since later initializers for an object can indirectly refer to subobjects
5313/// which were initialized earlier.
5314static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005315 const LValue &This, const Expr *E,
5316 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005317 if (!CheckLiteralType(Info, E))
5318 return false;
5319
5320 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005321 // Evaluate arrays and record types in-place, so that later initializers can
5322 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005323 if (E->getType()->isArrayType())
5324 return EvaluateArray(E, This, Result, Info);
5325 else if (E->getType()->isRecordType())
5326 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005327 }
5328
5329 // For any other type, in-place evaluation is unimportant.
5330 CCValue CoreConstResult;
5331 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005332 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005333}
5334
Richard Smithf57d8cb2011-12-09 22:58:01 +00005335/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5336/// lvalue-to-rvalue cast if it is an lvalue.
5337static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005338 if (!CheckLiteralType(Info, E))
5339 return false;
5340
Richard Smithf57d8cb2011-12-09 22:58:01 +00005341 CCValue Value;
5342 if (!::Evaluate(Value, Info, E))
5343 return false;
5344
5345 if (E->isGLValue()) {
5346 LValue LV;
5347 LV.setFrom(Value);
5348 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5349 return false;
5350 }
5351
5352 // Check this core constant expression is a constant expression, and if so,
5353 // convert it to one.
5354 return CheckConstantExpression(Info, E, Value, Result);
5355}
Richard Smith11562c52011-10-28 17:51:58 +00005356
Richard Smith7b553f12011-10-29 00:50:52 +00005357/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005358/// any crazy technique (that has nothing to do with language standards) that
5359/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005360/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5361/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005362bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005363 // Fast-path evaluations of integer literals, since we sometimes see files
5364 // containing vast quantities of these.
5365 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5366 Result.Val = APValue(APSInt(L->getValue(),
5367 L->getType()->isUnsignedIntegerType()));
5368 return true;
5369 }
5370
Richard Smith5686e752011-11-10 03:30:42 +00005371 // FIXME: Evaluating initializers for large arrays can cause performance
5372 // problems, and we don't use such values yet. Once we have a more efficient
5373 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005374 // The same problem affects large records.
5375 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5376 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005377 return false;
5378
Richard Smithd62306a2011-11-10 06:34:14 +00005379 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005380 EvalInfo Info(Ctx, Result);
5381 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005382}
5383
Jay Foad39c79802011-01-12 09:06:06 +00005384bool Expr::EvaluateAsBooleanCondition(bool &Result,
5385 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005386 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005387 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00005388 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5389 Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005390 Result);
John McCall1be1c632010-01-05 23:42:56 +00005391}
5392
Richard Smith5fab0c92011-12-28 19:48:30 +00005393bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5394 SideEffectsKind AllowSideEffects) const {
5395 if (!getType()->isIntegralOrEnumerationType())
5396 return false;
5397
Richard Smith11562c52011-10-28 17:51:58 +00005398 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005399 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5400 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005401 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005402
Richard Smith11562c52011-10-28 17:51:58 +00005403 Result = ExprResult.Val.getInt();
5404 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005405}
5406
Jay Foad39c79802011-01-12 09:06:06 +00005407bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005408 EvalInfo Info(Ctx, Result);
5409
John McCall45d55e42010-05-07 21:00:08 +00005410 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005411 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005412 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5413 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005414}
5415
Richard Smithd0b4dd62011-12-19 06:19:21 +00005416bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5417 const VarDecl *VD,
5418 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5419 Expr::EvalStatus EStatus;
5420 EStatus.Diag = &Notes;
5421
5422 EvalInfo InitInfo(Ctx, EStatus);
5423 InitInfo.setEvaluatingDecl(VD, Value);
5424
Richard Smithfddd3842011-12-30 21:15:51 +00005425 if (!CheckLiteralType(InitInfo, this))
5426 return false;
5427
Richard Smithd0b4dd62011-12-19 06:19:21 +00005428 LValue LVal;
5429 LVal.set(VD);
5430
Richard Smithfddd3842011-12-30 21:15:51 +00005431 // C++11 [basic.start.init]p2:
5432 // Variables with static storage duration or thread storage duration shall be
5433 // zero-initialized before any other initialization takes place.
5434 // This behavior is not present in C.
5435 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5436 !VD->getType()->isReferenceType()) {
5437 ImplicitValueInitExpr VIE(VD->getType());
5438 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5439 return false;
5440 }
5441
Richard Smithd0b4dd62011-12-19 06:19:21 +00005442 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5443 !EStatus.HasSideEffects;
5444}
5445
Richard Smith7b553f12011-10-29 00:50:52 +00005446/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5447/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005448bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005449 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005450 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005451}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005452
Jay Foad39c79802011-01-12 09:06:06 +00005453bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005454 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005455}
5456
Richard Smithcaf33902011-10-10 18:28:20 +00005457APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005458 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005459 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005460 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005461 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005462 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005463
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005464 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005465}
John McCall864e3962010-05-07 05:32:02 +00005466
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005467 bool Expr::EvalResult::isGlobalLValue() const {
5468 assert(Val.isLValue());
5469 return IsGlobalLValue(Val.getLValueBase());
5470 }
5471
5472
John McCall864e3962010-05-07 05:32:02 +00005473/// isIntegerConstantExpr - this recursive routine will test if an expression is
5474/// an integer constant expression.
5475
5476/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5477/// comma, etc
5478///
5479/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5480/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5481/// cast+dereference.
5482
5483// CheckICE - This function does the fundamental ICE checking: the returned
5484// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5485// Note that to reduce code duplication, this helper does no evaluation
5486// itself; the caller checks whether the expression is evaluatable, and
5487// in the rare cases where CheckICE actually cares about the evaluated
5488// value, it calls into Evalute.
5489//
5490// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005491// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005492// 1: This expression is not an ICE, but if it isn't evaluated, it's
5493// a legal subexpression for an ICE. This return value is used to handle
5494// the comma operator in C99 mode.
5495// 2: This expression is not an ICE, and is not a legal subexpression for one.
5496
Dan Gohman28ade552010-07-26 21:25:24 +00005497namespace {
5498
John McCall864e3962010-05-07 05:32:02 +00005499struct ICEDiag {
5500 unsigned Val;
5501 SourceLocation Loc;
5502
5503 public:
5504 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5505 ICEDiag() : Val(0) {}
5506};
5507
Dan Gohman28ade552010-07-26 21:25:24 +00005508}
5509
5510static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005511
5512static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5513 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005514 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005515 !EVResult.Val.isInt()) {
5516 return ICEDiag(2, E->getLocStart());
5517 }
5518 return NoDiag();
5519}
5520
5521static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5522 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005523 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005524 return ICEDiag(2, E->getLocStart());
5525 }
5526
5527 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005528#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005529#define STMT(Node, Base) case Expr::Node##Class:
5530#define EXPR(Node, Base)
5531#include "clang/AST/StmtNodes.inc"
5532 case Expr::PredefinedExprClass:
5533 case Expr::FloatingLiteralClass:
5534 case Expr::ImaginaryLiteralClass:
5535 case Expr::StringLiteralClass:
5536 case Expr::ArraySubscriptExprClass:
5537 case Expr::MemberExprClass:
5538 case Expr::CompoundAssignOperatorClass:
5539 case Expr::CompoundLiteralExprClass:
5540 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005541 case Expr::DesignatedInitExprClass:
5542 case Expr::ImplicitValueInitExprClass:
5543 case Expr::ParenListExprClass:
5544 case Expr::VAArgExprClass:
5545 case Expr::AddrLabelExprClass:
5546 case Expr::StmtExprClass:
5547 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005548 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005549 case Expr::CXXDynamicCastExprClass:
5550 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005551 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005552 case Expr::CXXNullPtrLiteralExprClass:
5553 case Expr::CXXThisExprClass:
5554 case Expr::CXXThrowExprClass:
5555 case Expr::CXXNewExprClass:
5556 case Expr::CXXDeleteExprClass:
5557 case Expr::CXXPseudoDestructorExprClass:
5558 case Expr::UnresolvedLookupExprClass:
5559 case Expr::DependentScopeDeclRefExprClass:
5560 case Expr::CXXConstructExprClass:
5561 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005562 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005563 case Expr::CXXTemporaryObjectExprClass:
5564 case Expr::CXXUnresolvedConstructExprClass:
5565 case Expr::CXXDependentScopeMemberExprClass:
5566 case Expr::UnresolvedMemberExprClass:
5567 case Expr::ObjCStringLiteralClass:
5568 case Expr::ObjCEncodeExprClass:
5569 case Expr::ObjCMessageExprClass:
5570 case Expr::ObjCSelectorExprClass:
5571 case Expr::ObjCProtocolExprClass:
5572 case Expr::ObjCIvarRefExprClass:
5573 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005574 case Expr::ObjCIsaExprClass:
5575 case Expr::ShuffleVectorExprClass:
5576 case Expr::BlockExprClass:
5577 case Expr::BlockDeclRefExprClass:
5578 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005579 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005580 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005581 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005582 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005583 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005584 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005585 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005586 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005587 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005588 return ICEDiag(2, E->getLocStart());
5589
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005590 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005591 case Expr::GNUNullExprClass:
5592 // GCC considers the GNU __null value to be an integral constant expression.
5593 return NoDiag();
5594
John McCall7c454bb2011-07-15 05:09:51 +00005595 case Expr::SubstNonTypeTemplateParmExprClass:
5596 return
5597 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5598
John McCall864e3962010-05-07 05:32:02 +00005599 case Expr::ParenExprClass:
5600 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005601 case Expr::GenericSelectionExprClass:
5602 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005603 case Expr::IntegerLiteralClass:
5604 case Expr::CharacterLiteralClass:
5605 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005606 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005607 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005608 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005609 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005610 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005611 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005612 return NoDiag();
5613 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005614 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005615 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5616 // constant expressions, but they can never be ICEs because an ICE cannot
5617 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005618 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005619 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005620 return CheckEvalInICE(E, Ctx);
5621 return ICEDiag(2, E->getLocStart());
5622 }
5623 case Expr::DeclRefExprClass:
5624 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5625 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005626 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005627 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5628
5629 // Parameter variables are never constants. Without this check,
5630 // getAnyInitializer() can find a default argument, which leads
5631 // to chaos.
5632 if (isa<ParmVarDecl>(D))
5633 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5634
5635 // C++ 7.1.5.1p2
5636 // A variable of non-volatile const-qualified integral or enumeration
5637 // type initialized by an ICE can be used in ICEs.
5638 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005639 if (!Dcl->getType()->isIntegralOrEnumerationType())
5640 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5641
Richard Smithd0b4dd62011-12-19 06:19:21 +00005642 const VarDecl *VD;
5643 // Look for a declaration of this variable that has an initializer, and
5644 // check whether it is an ICE.
5645 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5646 return NoDiag();
5647 else
5648 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005649 }
5650 }
5651 return ICEDiag(2, E->getLocStart());
5652 case Expr::UnaryOperatorClass: {
5653 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5654 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005655 case UO_PostInc:
5656 case UO_PostDec:
5657 case UO_PreInc:
5658 case UO_PreDec:
5659 case UO_AddrOf:
5660 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005661 // C99 6.6/3 allows increment and decrement within unevaluated
5662 // subexpressions of constant expressions, but they can never be ICEs
5663 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005664 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005665 case UO_Extension:
5666 case UO_LNot:
5667 case UO_Plus:
5668 case UO_Minus:
5669 case UO_Not:
5670 case UO_Real:
5671 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005672 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005673 }
5674
5675 // OffsetOf falls through here.
5676 }
5677 case Expr::OffsetOfExprClass: {
5678 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005679 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005680 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005681 // compliance: we should warn earlier for offsetof expressions with
5682 // array subscripts that aren't ICEs, and if the array subscripts
5683 // are ICEs, the value of the offsetof must be an integer constant.
5684 return CheckEvalInICE(E, Ctx);
5685 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005686 case Expr::UnaryExprOrTypeTraitExprClass: {
5687 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5688 if ((Exp->getKind() == UETT_SizeOf) &&
5689 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005690 return ICEDiag(2, E->getLocStart());
5691 return NoDiag();
5692 }
5693 case Expr::BinaryOperatorClass: {
5694 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5695 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005696 case BO_PtrMemD:
5697 case BO_PtrMemI:
5698 case BO_Assign:
5699 case BO_MulAssign:
5700 case BO_DivAssign:
5701 case BO_RemAssign:
5702 case BO_AddAssign:
5703 case BO_SubAssign:
5704 case BO_ShlAssign:
5705 case BO_ShrAssign:
5706 case BO_AndAssign:
5707 case BO_XorAssign:
5708 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005709 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5710 // constant expressions, but they can never be ICEs because an ICE cannot
5711 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005712 return ICEDiag(2, E->getLocStart());
5713
John McCalle3027922010-08-25 11:45:40 +00005714 case BO_Mul:
5715 case BO_Div:
5716 case BO_Rem:
5717 case BO_Add:
5718 case BO_Sub:
5719 case BO_Shl:
5720 case BO_Shr:
5721 case BO_LT:
5722 case BO_GT:
5723 case BO_LE:
5724 case BO_GE:
5725 case BO_EQ:
5726 case BO_NE:
5727 case BO_And:
5728 case BO_Xor:
5729 case BO_Or:
5730 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005731 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5732 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005733 if (Exp->getOpcode() == BO_Div ||
5734 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005735 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005736 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005737 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005738 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005739 if (REval == 0)
5740 return ICEDiag(1, E->getLocStart());
5741 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005742 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005743 if (LEval.isMinSignedValue())
5744 return ICEDiag(1, E->getLocStart());
5745 }
5746 }
5747 }
John McCalle3027922010-08-25 11:45:40 +00005748 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005749 if (Ctx.getLangOptions().C99) {
5750 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5751 // if it isn't evaluated.
5752 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5753 return ICEDiag(1, E->getLocStart());
5754 } else {
5755 // In both C89 and C++, commas in ICEs are illegal.
5756 return ICEDiag(2, E->getLocStart());
5757 }
5758 }
5759 if (LHSResult.Val >= RHSResult.Val)
5760 return LHSResult;
5761 return RHSResult;
5762 }
John McCalle3027922010-08-25 11:45:40 +00005763 case BO_LAnd:
5764 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005765 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5766 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5767 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5768 // Rare case where the RHS has a comma "side-effect"; we need
5769 // to actually check the condition to see whether the side
5770 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005771 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005772 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005773 return RHSResult;
5774 return NoDiag();
5775 }
5776
5777 if (LHSResult.Val >= RHSResult.Val)
5778 return LHSResult;
5779 return RHSResult;
5780 }
5781 }
5782 }
5783 case Expr::ImplicitCastExprClass:
5784 case Expr::CStyleCastExprClass:
5785 case Expr::CXXFunctionalCastExprClass:
5786 case Expr::CXXStaticCastExprClass:
5787 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005788 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005789 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005790 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005791 if (isa<ExplicitCastExpr>(E)) {
5792 if (const FloatingLiteral *FL
5793 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5794 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5795 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5796 APSInt IgnoredVal(DestWidth, !DestSigned);
5797 bool Ignored;
5798 // If the value does not fit in the destination type, the behavior is
5799 // undefined, so we are not required to treat it as a constant
5800 // expression.
5801 if (FL->getValue().convertToInteger(IgnoredVal,
5802 llvm::APFloat::rmTowardZero,
5803 &Ignored) & APFloat::opInvalidOp)
5804 return ICEDiag(2, E->getLocStart());
5805 return NoDiag();
5806 }
5807 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005808 switch (cast<CastExpr>(E)->getCastKind()) {
5809 case CK_LValueToRValue:
5810 case CK_NoOp:
5811 case CK_IntegralToBoolean:
5812 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005813 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005814 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005815 return ICEDiag(2, E->getLocStart());
5816 }
John McCall864e3962010-05-07 05:32:02 +00005817 }
John McCallc07a0c72011-02-17 10:25:35 +00005818 case Expr::BinaryConditionalOperatorClass: {
5819 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5820 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5821 if (CommonResult.Val == 2) return CommonResult;
5822 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5823 if (FalseResult.Val == 2) return FalseResult;
5824 if (CommonResult.Val == 1) return CommonResult;
5825 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005826 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005827 return FalseResult;
5828 }
John McCall864e3962010-05-07 05:32:02 +00005829 case Expr::ConditionalOperatorClass: {
5830 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5831 // If the condition (ignoring parens) is a __builtin_constant_p call,
5832 // then only the true side is actually considered in an integer constant
5833 // expression, and it is fully evaluated. This is an important GNU
5834 // extension. See GCC PR38377 for discussion.
5835 if (const CallExpr *CallCE
5836 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005837 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5838 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005839 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005840 if (CondResult.Val == 2)
5841 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005842
Richard Smithf57d8cb2011-12-09 22:58:01 +00005843 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5844 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005845
John McCall864e3962010-05-07 05:32:02 +00005846 if (TrueResult.Val == 2)
5847 return TrueResult;
5848 if (FalseResult.Val == 2)
5849 return FalseResult;
5850 if (CondResult.Val == 1)
5851 return CondResult;
5852 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5853 return NoDiag();
5854 // Rare case where the diagnostics depend on which side is evaluated
5855 // Note that if we get here, CondResult is 0, and at least one of
5856 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005857 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005858 return FalseResult;
5859 }
5860 return TrueResult;
5861 }
5862 case Expr::CXXDefaultArgExprClass:
5863 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5864 case Expr::ChooseExprClass: {
5865 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5866 }
5867 }
5868
5869 // Silence a GCC warning
5870 return ICEDiag(2, E->getLocStart());
5871}
5872
Richard Smithf57d8cb2011-12-09 22:58:01 +00005873/// Evaluate an expression as a C++11 integral constant expression.
5874static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5875 const Expr *E,
5876 llvm::APSInt *Value,
5877 SourceLocation *Loc) {
5878 if (!E->getType()->isIntegralOrEnumerationType()) {
5879 if (Loc) *Loc = E->getExprLoc();
5880 return false;
5881 }
5882
5883 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005884 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5885 Result.Diag = &Diags;
5886 EvalInfo Info(Ctx, Result);
5887
5888 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5889 if (!Diags.empty()) {
5890 IsICE = false;
5891 if (Loc) *Loc = Diags[0].first;
5892 } else if (!IsICE && Loc) {
5893 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005894 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005895
5896 if (!IsICE)
5897 return false;
5898
5899 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5900 if (Value) *Value = Result.Val.getInt();
5901 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005902}
5903
Richard Smith92b1ce02011-12-12 09:28:41 +00005904bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005905 if (Ctx.getLangOptions().CPlusPlus0x)
5906 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5907
John McCall864e3962010-05-07 05:32:02 +00005908 ICEDiag d = CheckICE(this, Ctx);
5909 if (d.Val != 0) {
5910 if (Loc) *Loc = d.Loc;
5911 return false;
5912 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005913 return true;
5914}
5915
5916bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5917 SourceLocation *Loc, bool isEvaluated) const {
5918 if (Ctx.getLangOptions().CPlusPlus0x)
5919 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5920
5921 if (!isIntegerConstantExpr(Ctx, Loc))
5922 return false;
5923 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005924 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005925 return true;
5926}