blob: f4c9a8336c789a970fe44b89ebc847bfe6af9eaa [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
Richard Smith0b0a0b62011-10-29 20:57:55 +000031static bool IsParamLValue(const Expr *E);
32
Chris Lattnercdf34e72008-07-11 22:52:41 +000033/// EvalInfo - This is a private struct used by the evaluator to capture
34/// information about a subexpression as it is folded. It retains information
35/// about the AST context, but also maintains information about the folded
36/// expression.
37///
38/// If an expression could be evaluated, it is still possible it is not a C
39/// "integer constant expression" or constant expression. If not, this struct
40/// captures information about how and why not.
41///
42/// One bit of information passed *into* the request for constant folding
43/// indicates whether the subexpression is "evaluated" or not according to C
44/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
45/// evaluate the expression regardless of what the RHS is, but C only allows
46/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000047namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000048 struct CallStackFrame;
49
Richard Smith0b0a0b62011-10-29 20:57:55 +000050 /// A core constant value. This can be the value of any constant expression,
51 /// or a pointer or reference to a non-static object or function parameter.
52 class CCValue : public APValue {
53 typedef llvm::APSInt APSInt;
54 typedef llvm::APFloat APFloat;
55 /// If the value is a DeclRefExpr lvalue referring to a ParmVarDecl, this is
56 /// the index of the corresponding function call.
57 unsigned CallIndex;
58 public:
59 CCValue() {}
60 explicit CCValue(const APSInt &I) : APValue(I) {}
61 explicit CCValue(const APFloat &F) : APValue(F) {}
62 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
63 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
64 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
65 CCValue(const CCValue &V) : APValue(V), CallIndex(V.CallIndex) {}
66 CCValue(const Expr *B, const CharUnits &O, unsigned I) :
67 APValue(B, O), CallIndex(I) {}
68 CCValue(const APValue &V, unsigned CallIndex) :
69 APValue(V), CallIndex(CallIndex) {}
70
71 enum { NoCallIndex = (unsigned)-1 };
72
73 unsigned getLValueCallIndex() const {
74 assert(getKind() == LValue);
75 return CallIndex;
76 }
77 };
78
Benjamin Kramer024e6192011-03-04 13:12:48 +000079 struct EvalInfo {
80 const ASTContext &Ctx;
81
Richard Smith725810a2011-10-16 21:26:27 +000082 /// EvalStatus - Contains information about the evaluation.
83 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000084
Richard Smith254a73d2011-10-28 22:34:42 +000085 /// CurrentCall - The top of the constexpr call stack.
86 const CallStackFrame *CurrentCall;
87
88 /// NumCalls - The number of calls we've evaluated so far.
89 unsigned NumCalls;
90
91 /// CallStackDepth - The number of calls in the call stack right now.
92 unsigned CallStackDepth;
93
Richard Smith0b0a0b62011-10-29 20:57:55 +000094 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
Benjamin Kramer024e6192011-03-04 13:12:48 +000095 MapTy OpaqueValues;
Richard Smith0b0a0b62011-10-29 20:57:55 +000096 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Benjamin Kramer024e6192011-03-04 13:12:48 +000097 MapTy::const_iterator i = OpaqueValues.find(e);
98 if (i == OpaqueValues.end()) return 0;
99 return &i->second;
100 }
101
Richard Smith0b0a0b62011-10-29 20:57:55 +0000102 unsigned getCurrentCallIndex() const;
103 const CCValue *getCallValue(unsigned CallIndex, unsigned ArgIndex) const;
104
Richard Smith725810a2011-10-16 21:26:27 +0000105 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith254a73d2011-10-28 22:34:42 +0000106 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0) {}
Richard Smith4ce706a2011-10-11 21:43:33 +0000107
108 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +0000109 };
110
Richard Smith254a73d2011-10-28 22:34:42 +0000111 /// A stack frame in the constexpr call stack.
112 struct CallStackFrame {
113 EvalInfo &Info;
114
115 /// Parent - The caller of this stack frame.
116 const CallStackFrame *Caller;
117
118 /// ParmBindings - Parameter bindings for this function call, indexed by
119 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000120 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000121
122 /// CallIndex - The index of the current call. This is used to match lvalues
123 /// referring to parameters up with the corresponding stack frame, and to
124 /// detect when the parameter is no longer in scope.
125 unsigned CallIndex;
126
Richard Smith0b0a0b62011-10-29 20:57:55 +0000127 CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smith254a73d2011-10-28 22:34:42 +0000128 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments),
129 CallIndex(Info.NumCalls++) {
130 Info.CurrentCall = this;
131 ++Info.CallStackDepth;
132 }
133 ~CallStackFrame() {
134 assert(Info.CurrentCall == this && "calls retired out of order");
135 --Info.CallStackDepth;
136 Info.CurrentCall = Caller;
137 }
138 };
139
Richard Smith0b0a0b62011-10-29 20:57:55 +0000140 unsigned EvalInfo::getCurrentCallIndex() const {
141 return CurrentCall ? CurrentCall->CallIndex : CCValue::NoCallIndex;
142 }
143
144 const CCValue *EvalInfo::getCallValue(unsigned CallIndex,
145 unsigned ArgIndex) const {
146 for (const CallStackFrame *Frame = CurrentCall;
147 Frame && Frame->CallIndex >= CallIndex; Frame = Frame->Caller)
148 if (Frame->CallIndex == CallIndex)
149 return Frame->Arguments + ArgIndex;
150 return 0;
151 }
152
John McCall93d91dc2010-05-07 17:22:02 +0000153 struct ComplexValue {
154 private:
155 bool IsInt;
156
157 public:
158 APSInt IntReal, IntImag;
159 APFloat FloatReal, FloatImag;
160
161 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
162
163 void makeComplexFloat() { IsInt = false; }
164 bool isComplexFloat() const { return !IsInt; }
165 APFloat &getComplexFloatReal() { return FloatReal; }
166 APFloat &getComplexFloatImag() { return FloatImag; }
167
168 void makeComplexInt() { IsInt = true; }
169 bool isComplexInt() const { return IsInt; }
170 APSInt &getComplexIntReal() { return IntReal; }
171 APSInt &getComplexIntImag() { return IntImag; }
172
Richard Smith0b0a0b62011-10-29 20:57:55 +0000173 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000174 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000175 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000176 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000177 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000178 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000179 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000180 assert(v.isComplexFloat() || v.isComplexInt());
181 if (v.isComplexFloat()) {
182 makeComplexFloat();
183 FloatReal = v.getComplexFloatReal();
184 FloatImag = v.getComplexFloatImag();
185 } else {
186 makeComplexInt();
187 IntReal = v.getComplexIntReal();
188 IntImag = v.getComplexIntImag();
189 }
190 }
John McCall93d91dc2010-05-07 17:22:02 +0000191 };
John McCall45d55e42010-05-07 21:00:08 +0000192
193 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000194 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000195 CharUnits Offset;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000196 unsigned CallIndex;
John McCall45d55e42010-05-07 21:00:08 +0000197
Richard Smith8b3497e2011-10-31 01:37:14 +0000198 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000199 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000200 const CharUnits &getLValueOffset() const { return Offset; }
201 unsigned getLValueCallIndex() const { return CallIndex; }
John McCall45d55e42010-05-07 21:00:08 +0000202
Richard Smith0b0a0b62011-10-29 20:57:55 +0000203 void moveInto(CCValue &V) const {
204 V = CCValue(Base, Offset, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000205 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000206 void setFrom(const CCValue &V) {
207 assert(V.isLValue());
208 Base = V.getLValueBase();
209 Offset = V.getLValueOffset();
210 CallIndex = V.getLValueCallIndex();
John McCallc07a0c72011-02-17 10:25:35 +0000211 }
John McCall45d55e42010-05-07 21:00:08 +0000212 };
John McCall93d91dc2010-05-07 17:22:02 +0000213}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000214
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000216static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
217static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000218static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000219static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000220 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000221static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000222static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000223
224//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000225// Misc utilities
226//===----------------------------------------------------------------------===//
227
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000228static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000229 if (!E) return true;
230
231 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
232 if (isa<FunctionDecl>(DRE->getDecl()))
233 return true;
234 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
235 return VD->hasGlobalStorage();
236 return false;
237 }
238
239 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
240 return CLE->isFileScope();
241
Richard Smith11562c52011-10-28 17:51:58 +0000242 if (isa<MemberExpr>(E))
243 return false;
244
John McCall95007602010-05-10 23:27:23 +0000245 return true;
246}
247
Richard Smith0b0a0b62011-10-29 20:57:55 +0000248static bool IsParamLValue(const Expr *E) {
249 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
250 return isa<ParmVarDecl>(DRE->getDecl());
251 return false;
252}
253
254/// Check that this core constant expression value is a valid value for a
255/// constant expression.
256static bool CheckConstantExpression(const CCValue &Value) {
257 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
258}
259
Richard Smith83c68212011-10-31 05:11:32 +0000260const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
261 if (!LVal.Base)
262 return 0;
263
264 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
265 return DRE->getDecl();
266
267 // FIXME: Static data members accessed via a MemberExpr are represented as
268 // that MemberExpr. We should use the Decl directly instead.
269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
270 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
271 return ME->getMemberDecl();
272 }
273
274 return 0;
275}
276
277static bool IsLiteralLValue(const LValue &Value) {
278 return Value.Base &&
279 !isa<DeclRefExpr>(Value.Base) &&
280 !isa<MemberExpr>(Value.Base);
281}
282
283static bool IsWeakLValue(const LValue &Value) {
284 const ValueDecl *Decl = GetLValueBaseDecl(Value);
285 if (!Decl)
286 return false;
287
288 return Decl->hasAttr<WeakAttr>() ||
289 Decl->hasAttr<WeakRefAttr>() ||
290 Decl->isWeakImported();
291}
292
Richard Smith11562c52011-10-28 17:51:58 +0000293static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000294 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000295
John McCalleb3e4f32010-05-07 21:34:32 +0000296 // A null base expression indicates a null pointer. These are always
297 // evaluatable, and they are false unless the offset is zero.
298 if (!Base) {
299 Result = !Value.Offset.isZero();
300 return true;
301 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000302
John McCall95007602010-05-10 23:27:23 +0000303 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000304 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000305 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000306
John McCalleb3e4f32010-05-07 21:34:32 +0000307 // We have a non-null base expression. These are generally known to
308 // be true, but if it'a decl-ref to a weak symbol it can be null at
309 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000310 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000311 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000312}
313
Richard Smith0b0a0b62011-10-29 20:57:55 +0000314static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000315 switch (Val.getKind()) {
316 case APValue::Uninitialized:
317 return false;
318 case APValue::Int:
319 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000320 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000321 case APValue::Float:
322 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000323 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000324 case APValue::ComplexInt:
325 Result = Val.getComplexIntReal().getBoolValue() ||
326 Val.getComplexIntImag().getBoolValue();
327 return true;
328 case APValue::ComplexFloat:
329 Result = !Val.getComplexFloatReal().isZero() ||
330 !Val.getComplexFloatImag().isZero();
331 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000332 case APValue::LValue: {
333 LValue PointerResult;
334 PointerResult.setFrom(Val);
335 return EvalPointerValueAsBool(PointerResult, Result);
336 }
Richard Smith11562c52011-10-28 17:51:58 +0000337 case APValue::Vector:
338 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000339 }
340
Richard Smith11562c52011-10-28 17:51:58 +0000341 llvm_unreachable("unknown APValue kind");
342}
343
344static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
345 EvalInfo &Info) {
346 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000347 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000348 if (!Evaluate(Val, Info, E))
349 return false;
350 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000351}
352
Mike Stump11289f42009-09-09 15:08:12 +0000353static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000354 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000355 unsigned DestWidth = Ctx.getIntWidth(DestType);
356 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000357 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000359 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000360 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000361 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000362 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
363 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000364}
365
Mike Stump11289f42009-09-09 15:08:12 +0000366static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000367 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000368 bool ignored;
369 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000370 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000371 APFloat::rmNearestTiesToEven, &ignored);
372 return Result;
373}
374
Mike Stump11289f42009-09-09 15:08:12 +0000375static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000376 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000377 unsigned DestWidth = Ctx.getIntWidth(DestType);
378 APSInt Result = Value;
379 // Figure out if this is a truncate, extend or noop cast.
380 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000381 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000382 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000383 return Result;
384}
385
Mike Stump11289f42009-09-09 15:08:12 +0000386static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000387 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000388
389 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
390 Result.convertFromAPInt(Value, Value.isSigned(),
391 APFloat::rmNearestTiesToEven);
392 return Result;
393}
394
Richard Smith27908702011-10-24 17:54:18 +0000395/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000396static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
397 unsigned CallIndex, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000398 // If this is a parameter to an active constexpr function call, perform
399 // argument substitution.
400 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000401 if (const CCValue *ArgValue =
402 Info.getCallValue(CallIndex, PVD->getFunctionScopeIndex())) {
403 Result = *ArgValue;
404 return true;
405 }
406 return false;
Richard Smith254a73d2011-10-28 22:34:42 +0000407 }
Richard Smith27908702011-10-24 17:54:18 +0000408
409 const Expr *Init = VD->getAnyInitializer();
410 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000411 return false;
Richard Smith27908702011-10-24 17:54:18 +0000412
Richard Smith0b0a0b62011-10-29 20:57:55 +0000413 if (APValue *V = VD->getEvaluatedValue()) {
414 Result = CCValue(*V, CCValue::NoCallIndex);
415 return !Result.isUninit();
416 }
Richard Smith27908702011-10-24 17:54:18 +0000417
418 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000419 return false;
Richard Smith27908702011-10-24 17:54:18 +0000420
421 VD->setEvaluatingValue();
422
Richard Smith0b0a0b62011-10-29 20:57:55 +0000423 Expr::EvalStatus EStatus;
424 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000425 // FIXME: The caller will need to know whether the value was a constant
426 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000427 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000428 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000429 return false;
430 }
Richard Smith27908702011-10-24 17:54:18 +0000431
Richard Smith0b0a0b62011-10-29 20:57:55 +0000432 VD->setEvaluatedValue(Result);
433 return true;
Richard Smith27908702011-10-24 17:54:18 +0000434}
435
Richard Smith11562c52011-10-28 17:51:58 +0000436static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000437 Qualifiers Quals = T.getQualifiers();
438 return Quals.hasConst() && !Quals.hasVolatile();
439}
440
Richard Smith11562c52011-10-28 17:51:58 +0000441bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000442 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000443 const Expr *Base = LVal.Base;
444
445 // FIXME: Indirection through a null pointer deserves a diagnostic.
446 if (!Base)
447 return false;
448
449 // FIXME: Support accessing subobjects of objects of literal types. A simple
450 // byte offset is insufficient for C++11 semantics: we need to know how the
451 // reference was formed (which union member was named, for instance).
452 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
453 if (!LVal.Offset.isZero())
454 return false;
455
Richard Smith8b3497e2011-10-31 01:37:14 +0000456 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000457 // If the lvalue has been cast to some other type, don't try to read it.
458 // FIXME: Could simulate a bitcast here.
Richard Smith8b3497e2011-10-31 01:37:14 +0000459 if (!Info.Ctx.hasSameUnqualifiedType(Type, D->getType()))
460 return 0;
Richard Smith11562c52011-10-28 17:51:58 +0000461
Richard Smith11562c52011-10-28 17:51:58 +0000462 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
463 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000464 // expressions are constant expressions too. Inside constexpr functions,
465 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000466 // In C, such things can also be folded, although they are not ICEs.
467 //
Richard Smith254a73d2011-10-28 22:34:42 +0000468 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
469 // interpretation of C++11 suggests that volatile parameters are OK if
470 // they're never read (there's no prohibition against constructing volatile
471 // objects in constant expressions), but lvalue-to-rvalue conversions on
472 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000473 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000474 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith35a1f852011-10-29 21:53:17 +0000475 !Type->isLiteralType() ||
Richard Smith0b0a0b62011-10-29 20:57:55 +0000476 !EvaluateVarDeclInit(Info, VD, LVal.CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000477 return false;
478
Richard Smith0b0a0b62011-10-29 20:57:55 +0000479 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000480 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000481
482 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
483 // conversion. This happens when the declaration and the lvalue should be
484 // considered synonymous, for instance when initializing an array of char
485 // from a string literal. Continue as if the initializer lvalue was the
486 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000487 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000488 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000489 Base = RVal.getLValueBase();
Richard Smith11562c52011-10-28 17:51:58 +0000490 }
491
492 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
493 // here.
494
495 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
496 // initializer until now for such expressions. Such an expression can't be
497 // an ICE in C, so this only matters for fold.
498 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
499 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
500 return Evaluate(RVal, Info, CLE->getInitializer());
501 }
502
503 return false;
504}
505
Mike Stump876387b2009-10-27 22:09:17 +0000506namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000507enum EvalStmtResult {
508 /// Evaluation failed.
509 ESR_Failed,
510 /// Hit a 'return' statement.
511 ESR_Returned,
512 /// Evaluation succeeded.
513 ESR_Succeeded
514};
515}
516
517// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000518static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000519 const Stmt *S) {
520 switch (S->getStmtClass()) {
521 default:
522 return ESR_Failed;
523
524 case Stmt::NullStmtClass:
525 case Stmt::DeclStmtClass:
526 return ESR_Succeeded;
527
528 case Stmt::ReturnStmtClass:
529 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
530 return ESR_Returned;
531 return ESR_Failed;
532
533 case Stmt::CompoundStmtClass: {
534 const CompoundStmt *CS = cast<CompoundStmt>(S);
535 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
536 BE = CS->body_end(); BI != BE; ++BI) {
537 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
538 if (ESR != ESR_Succeeded)
539 return ESR;
540 }
541 return ESR_Succeeded;
542 }
543 }
544}
545
546/// Evaluate a function call.
547static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000548 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000549 // FIXME: Implement a proper call limit, along with a command-line flag.
550 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
551 return false;
552
Richard Smith0b0a0b62011-10-29 20:57:55 +0000553 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000554 // FIXME: Deal with default arguments and 'this'.
555 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
556 I != E; ++I)
557 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
558 return false;
559
560 CallStackFrame Frame(Info, ArgValues.data());
561 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
562}
563
564namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000565class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000566 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000567 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000568public:
569
Richard Smith725810a2011-10-16 21:26:27 +0000570 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000571
572 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000574 return true;
575 }
576
Peter Collingbournee9200682011-05-13 03:29:01 +0000577 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
578 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000579 return Visit(E->getResultExpr());
580 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000581 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000582 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000583 return true;
584 return false;
585 }
John McCall31168b02011-06-15 23:02:42 +0000586 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000587 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000588 return true;
589 return false;
590 }
591 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000592 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000593 return true;
594 return false;
595 }
596
Mike Stump876387b2009-10-27 22:09:17 +0000597 // We don't want to evaluate BlockExprs multiple times, as they generate
598 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000599 bool VisitBlockExpr(const BlockExpr *E) { return true; }
600 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
601 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000602 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
604 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
605 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
606 bool VisitStringLiteral(const StringLiteral *E) { return false; }
607 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
608 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000609 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000610 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000611 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000612 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000613 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
615 bool VisitBinAssign(const BinaryOperator *E) { return true; }
616 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
617 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000618 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000619 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
620 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
621 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
622 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
623 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000624 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000625 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000626 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000627 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000628 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000629
630 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000632 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
633 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000635 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000636 return false;
637 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000638
Peter Collingbournee9200682011-05-13 03:29:01 +0000639 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000640};
641
John McCallc07a0c72011-02-17 10:25:35 +0000642class OpaqueValueEvaluation {
643 EvalInfo &info;
644 OpaqueValueExpr *opaqueValue;
645
646public:
647 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
648 Expr *value)
649 : info(info), opaqueValue(opaqueValue) {
650
651 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000652 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000653 this->opaqueValue = 0;
654 return;
655 }
John McCallc07a0c72011-02-17 10:25:35 +0000656 }
657
658 bool hasError() const { return opaqueValue == 0; }
659
660 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000661 // FIXME: This will not work for recursive constexpr functions using opaque
662 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000663 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
664 }
665};
666
Mike Stump876387b2009-10-27 22:09:17 +0000667} // end anonymous namespace
668
Eli Friedman9a156e52008-11-12 09:44:48 +0000669//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000670// Generic Evaluation
671//===----------------------------------------------------------------------===//
672namespace {
673
674template <class Derived, typename RetTy=void>
675class ExprEvaluatorBase
676 : public ConstStmtVisitor<Derived, RetTy> {
677private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000678 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000679 return static_cast<Derived*>(this)->Success(V, E);
680 }
681 RetTy DerivedError(const Expr *E) {
682 return static_cast<Derived*>(this)->Error(E);
683 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000684 RetTy DerivedValueInitialization(const Expr *E) {
685 return static_cast<Derived*>(this)->ValueInitialization(E);
686 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000687
688protected:
689 EvalInfo &Info;
690 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
691 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
692
Richard Smith4ce706a2011-10-11 21:43:33 +0000693 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
694
Peter Collingbournee9200682011-05-13 03:29:01 +0000695public:
696 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
697
698 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000699 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000700 }
701 RetTy VisitExpr(const Expr *E) {
702 return DerivedError(E);
703 }
704
705 RetTy VisitParenExpr(const ParenExpr *E)
706 { return StmtVisitorTy::Visit(E->getSubExpr()); }
707 RetTy VisitUnaryExtension(const UnaryOperator *E)
708 { return StmtVisitorTy::Visit(E->getSubExpr()); }
709 RetTy VisitUnaryPlus(const UnaryOperator *E)
710 { return StmtVisitorTy::Visit(E->getSubExpr()); }
711 RetTy VisitChooseExpr(const ChooseExpr *E)
712 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
713 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
714 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000715 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
716 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000717
718 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
719 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
720 if (opaque.hasError())
721 return DerivedError(E);
722
723 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000724 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000725 return DerivedError(E);
726
727 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
728 }
729
730 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
731 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000732 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000733 return DerivedError(E);
734
Richard Smith11562c52011-10-28 17:51:58 +0000735 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000736 return StmtVisitorTy::Visit(EvalExpr);
737 }
738
739 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000740 const CCValue *Value = Info.getOpaqueValue(E);
741 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000742 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
743 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000744 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000745 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000746
Richard Smith254a73d2011-10-28 22:34:42 +0000747 RetTy VisitCallExpr(const CallExpr *E) {
748 const Expr *Callee = E->getCallee();
749 QualType CalleeType = Callee->getType();
750
751 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
752 // non-static member function.
753 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
754 return DerivedError(E);
755
756 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
757 return DerivedError(E);
758
Richard Smith0b0a0b62011-10-29 20:57:55 +0000759 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000760 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
761 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
762 return DerivedError(Callee);
763
764 const FunctionDecl *FD = 0;
765 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
766 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
767 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
768 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
769 if (!FD)
770 return DerivedError(Callee);
771
772 // Don't call function pointers which have been cast to some other type.
773 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
774 return DerivedError(E);
775
776 const FunctionDecl *Definition;
777 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000778 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000779 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
780
781 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
782 HandleFunctionCall(Args, Body, Info, Result))
783 return DerivedSuccess(Result, E);
784
785 return DerivedError(E);
786 }
787
Richard Smith11562c52011-10-28 17:51:58 +0000788 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
789 return StmtVisitorTy::Visit(E->getInitializer());
790 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000791 RetTy VisitInitListExpr(const InitListExpr *E) {
792 if (Info.getLangOpts().CPlusPlus0x) {
793 if (E->getNumInits() == 0)
794 return DerivedValueInitialization(E);
795 if (E->getNumInits() == 1)
796 return StmtVisitorTy::Visit(E->getInit(0));
797 }
798 return DerivedError(E);
799 }
800 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
801 return DerivedValueInitialization(E);
802 }
803 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
804 return DerivedValueInitialization(E);
805 }
806
Richard Smith11562c52011-10-28 17:51:58 +0000807 RetTy VisitCastExpr(const CastExpr *E) {
808 switch (E->getCastKind()) {
809 default:
810 break;
811
812 case CK_NoOp:
813 return StmtVisitorTy::Visit(E->getSubExpr());
814
815 case CK_LValueToRValue: {
816 LValue LVal;
817 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000818 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000819 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
820 return DerivedSuccess(RVal, E);
821 }
822 break;
823 }
824 }
825
826 return DerivedError(E);
827 }
828
Richard Smith4a678122011-10-24 18:44:57 +0000829 /// Visit a value which is evaluated, but whose value is ignored.
830 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000831 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000832 if (!Evaluate(Scratch, Info, E))
833 Info.EvalStatus.HasSideEffects = true;
834 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000835};
836
837}
838
839//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000840// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000841//
842// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
843// function designators (in C), decl references to void objects (in C), and
844// temporaries (if building with -Wno-address-of-temporary).
845//
846// LValue evaluation produces values comprising a base expression of one of the
847// following types:
848// * DeclRefExpr
849// * MemberExpr for a static member
850// * CompoundLiteralExpr in C
851// * StringLiteral
852// * PredefinedExpr
853// * ObjCEncodeExpr
854// * AddrLabelExpr
855// * BlockExpr
856// * CallExpr for a MakeStringConstant builtin
857// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000858//===----------------------------------------------------------------------===//
859namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000860class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000861 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000862 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000863 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000864
Peter Collingbournee9200682011-05-13 03:29:01 +0000865 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000866 Result.Base = E;
867 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000869 return true;
870 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000871public:
Mike Stump11289f42009-09-09 15:08:12 +0000872
John McCall45d55e42010-05-07 21:00:08 +0000873 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000874 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000875
Richard Smith0b0a0b62011-10-29 20:57:55 +0000876 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000877 Result.setFrom(V);
878 return true;
879 }
880 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000881 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000882 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000883
Richard Smith11562c52011-10-28 17:51:58 +0000884 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
885
Peter Collingbournee9200682011-05-13 03:29:01 +0000886 bool VisitDeclRefExpr(const DeclRefExpr *E);
887 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
888 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
889 bool VisitMemberExpr(const MemberExpr *E);
890 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
891 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
892 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
893 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000894
Peter Collingbournee9200682011-05-13 03:29:01 +0000895 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000896 switch (E->getCastKind()) {
897 default:
Richard Smith11562c52011-10-28 17:51:58 +0000898 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000899
Eli Friedmance3e02a2011-10-11 00:13:24 +0000900 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000901 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000902
Richard Smith11562c52011-10-28 17:51:58 +0000903 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
904 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000905 }
906 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000907
Eli Friedman449fe542009-03-23 04:56:01 +0000908 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000909
Eli Friedman9a156e52008-11-12 09:44:48 +0000910};
911} // end anonymous namespace
912
Richard Smith11562c52011-10-28 17:51:58 +0000913/// Evaluate an expression as an lvalue. This can be legitimately called on
914/// expressions which are not glvalues, in a few cases:
915/// * function designators in C,
916/// * "extern void" objects,
917/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000918static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000919 assert((E->isGLValue() || E->getType()->isFunctionType() ||
920 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
921 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000922 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000923}
924
Peter Collingbournee9200682011-05-13 03:29:01 +0000925bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000926 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000927 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000928 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
929 return VisitVarDecl(E, VD);
930 return Error(E);
931}
Richard Smith733237d2011-10-24 23:14:33 +0000932
Richard Smith11562c52011-10-28 17:51:58 +0000933bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
934 if (!VD->getType()->isReferenceType())
935 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000936
Richard Smith0b0a0b62011-10-29 20:57:55 +0000937 CCValue V;
938 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
939 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000940
941 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000942}
943
Peter Collingbournee9200682011-05-13 03:29:01 +0000944bool
945LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000946 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
947 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
948 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000949 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000950}
951
Peter Collingbournee9200682011-05-13 03:29:01 +0000952bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000953 // Handle static data members.
954 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
955 VisitIgnoredValue(E->getBase());
956 return VisitVarDecl(E, VD);
957 }
958
Richard Smith254a73d2011-10-28 22:34:42 +0000959 // Handle static member functions.
960 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
961 if (MD->isStatic()) {
962 VisitIgnoredValue(E->getBase());
963 return Success(E);
964 }
965 }
966
Eli Friedman9a156e52008-11-12 09:44:48 +0000967 QualType Ty;
968 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000969 if (!EvaluatePointer(E->getBase(), Result, Info))
970 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000971 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000972 } else {
John McCall45d55e42010-05-07 21:00:08 +0000973 if (!Visit(E->getBase()))
974 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000975 Ty = E->getBase()->getType();
976 }
977
Peter Collingbournee9200682011-05-13 03:29:01 +0000978 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000979 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000980
Peter Collingbournee9200682011-05-13 03:29:01 +0000981 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000982 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000983 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000984
985 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000986 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000987
Eli Friedmana3c122d2011-07-07 01:54:01 +0000988 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000989 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000990 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000991}
992
Peter Collingbournee9200682011-05-13 03:29:01 +0000993bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000994 // FIXME: Deal with vectors as array subscript bases.
995 if (E->getBase()->getType()->isVectorType())
996 return false;
997
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000998 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000999 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001000
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001001 APSInt Index;
1002 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001003 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001004
Ken Dyck40775002010-01-11 17:06:35 +00001005 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001006 Result.Offset += Index.getSExtValue() * ElementSize;
1007 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001008}
Eli Friedman9a156e52008-11-12 09:44:48 +00001009
Peter Collingbournee9200682011-05-13 03:29:01 +00001010bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001011 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001012}
1013
Eli Friedman9a156e52008-11-12 09:44:48 +00001014//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001015// Pointer Evaluation
1016//===----------------------------------------------------------------------===//
1017
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001018namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001019class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001020 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001021 LValue &Result;
1022
Peter Collingbournee9200682011-05-13 03:29:01 +00001023 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001024 Result.Base = E;
1025 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001026 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001027 return true;
1028 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001029public:
Mike Stump11289f42009-09-09 15:08:12 +00001030
John McCall45d55e42010-05-07 21:00:08 +00001031 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001032 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001033
Richard Smith0b0a0b62011-10-29 20:57:55 +00001034 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001035 Result.setFrom(V);
1036 return true;
1037 }
1038 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001039 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001040 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001041 bool ValueInitialization(const Expr *E) {
1042 return Success((Expr*)0);
1043 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001044
John McCall45d55e42010-05-07 21:00:08 +00001045 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001046 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001047 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001048 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001049 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001050 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001051 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001052 bool VisitCallExpr(const CallExpr *E);
1053 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001054 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001055 return Success(E);
1056 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001057 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001058 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001059 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001060
Eli Friedman449fe542009-03-23 04:56:01 +00001061 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001062};
Chris Lattner05706e882008-07-11 18:11:29 +00001063} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001064
John McCall45d55e42010-05-07 21:00:08 +00001065static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001066 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001067 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001068}
1069
John McCall45d55e42010-05-07 21:00:08 +00001070bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001071 if (E->getOpcode() != BO_Add &&
1072 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001073 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner05706e882008-07-11 18:11:29 +00001075 const Expr *PExp = E->getLHS();
1076 const Expr *IExp = E->getRHS();
1077 if (IExp->getType()->isPointerType())
1078 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001079
John McCall45d55e42010-05-07 21:00:08 +00001080 if (!EvaluatePointer(PExp, Result, Info))
1081 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001082
John McCall45d55e42010-05-07 21:00:08 +00001083 llvm::APSInt Offset;
1084 if (!EvaluateInteger(IExp, Offset, Info))
1085 return false;
1086 int64_t AdditionalOffset
1087 = Offset.isSigned() ? Offset.getSExtValue()
1088 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001089
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001090 // Compute the new offset in the appropriate width.
1091
1092 QualType PointeeType =
1093 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001094 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001095
Anders Carlssonef56fba2009-02-19 04:55:58 +00001096 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1097 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001098 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001099 else
John McCall45d55e42010-05-07 21:00:08 +00001100 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001101
John McCalle3027922010-08-25 11:45:40 +00001102 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001103 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001104 else
John McCall45d55e42010-05-07 21:00:08 +00001105 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001106
John McCall45d55e42010-05-07 21:00:08 +00001107 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001108}
Eli Friedman9a156e52008-11-12 09:44:48 +00001109
John McCall45d55e42010-05-07 21:00:08 +00001110bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1111 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001112}
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattner05706e882008-07-11 18:11:29 +00001114
Peter Collingbournee9200682011-05-13 03:29:01 +00001115bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1116 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001117
Eli Friedman847a2bc2009-12-27 05:43:15 +00001118 switch (E->getCastKind()) {
1119 default:
1120 break;
1121
John McCalle3027922010-08-25 11:45:40 +00001122 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001123 case CK_CPointerToObjCPointerCast:
1124 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001125 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001126 return Visit(SubExpr);
1127
Anders Carlsson18275092010-10-31 20:41:46 +00001128 case CK_DerivedToBase:
1129 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001130 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001131 return false;
1132
1133 // Now figure out the necessary offset to add to the baseLV to get from
1134 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001135 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001136
1137 QualType Ty = E->getSubExpr()->getType();
1138 const CXXRecordDecl *DerivedDecl =
1139 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1140
1141 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1142 PathE = E->path_end(); PathI != PathE; ++PathI) {
1143 const CXXBaseSpecifier *Base = *PathI;
1144
1145 // FIXME: If the base is virtual, we'd need to determine the type of the
1146 // most derived class and we don't support that right now.
1147 if (Base->isVirtual())
1148 return false;
1149
1150 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1151 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1152
Richard Smith0b0a0b62011-10-29 20:57:55 +00001153 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001154 DerivedDecl = BaseDecl;
1155 }
1156
Anders Carlsson18275092010-10-31 20:41:46 +00001157 return true;
1158 }
1159
Richard Smith0b0a0b62011-10-29 20:57:55 +00001160 case CK_NullToPointer:
1161 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001162
John McCalle3027922010-08-25 11:45:40 +00001163 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001164 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001165 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001166 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001167
John McCall45d55e42010-05-07 21:00:08 +00001168 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001169 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1170 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001171 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001172 Result.Offset = CharUnits::fromQuantity(N);
1173 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001174 return true;
1175 } else {
1176 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001177 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001178 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001179 }
1180 }
John McCalle3027922010-08-25 11:45:40 +00001181 case CK_ArrayToPointerDecay:
1182 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001183 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 }
1185
Richard Smith11562c52011-10-28 17:51:58 +00001186 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001187}
Chris Lattner05706e882008-07-11 18:11:29 +00001188
Peter Collingbournee9200682011-05-13 03:29:01 +00001189bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001190 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001191 Builtin::BI__builtin___CFStringMakeConstantString ||
1192 E->isBuiltinCall(Info.Ctx) ==
1193 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001194 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001195
Peter Collingbournee9200682011-05-13 03:29:01 +00001196 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001197}
Chris Lattner05706e882008-07-11 18:11:29 +00001198
1199//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001200// Vector Evaluation
1201//===----------------------------------------------------------------------===//
1202
1203namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001204 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001205 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1206 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001207 public:
Mike Stump11289f42009-09-09 15:08:12 +00001208
Richard Smith2d406342011-10-22 21:10:00 +00001209 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1210 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001211
Richard Smith2d406342011-10-22 21:10:00 +00001212 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1213 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1214 // FIXME: remove this APValue copy.
1215 Result = APValue(V.data(), V.size());
1216 return true;
1217 }
1218 bool Success(const APValue &V, const Expr *E) {
1219 Result = V;
1220 return true;
1221 }
1222 bool Error(const Expr *E) { return false; }
1223 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001224
Richard Smith2d406342011-10-22 21:10:00 +00001225 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001226 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001227 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001228 bool VisitInitListExpr(const InitListExpr *E);
1229 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001230 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001231 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001232 // shufflevector, ExtVectorElementExpr
1233 // (Note that these require implementing conversions
1234 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001235 };
1236} // end anonymous namespace
1237
1238static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001239 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001240 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001241}
1242
Richard Smith2d406342011-10-22 21:10:00 +00001243bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1244 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001245 QualType EltTy = VTy->getElementType();
1246 unsigned NElts = VTy->getNumElements();
1247 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001249 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001250 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001251
Eli Friedmanc757de22011-03-25 00:43:55 +00001252 switch (E->getCastKind()) {
1253 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001254 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001255 if (SETy->isIntegerType()) {
1256 APSInt IntResult;
1257 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001258 return Error(E);
1259 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001260 } else if (SETy->isRealFloatingType()) {
1261 APFloat F(0.0);
1262 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001263 return Error(E);
1264 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001265 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001266 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001267 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001268
1269 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001270 SmallVector<APValue, 4> Elts(NElts, Val);
1271 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001272 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001273 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001274 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001275 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001276 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001277
Eli Friedmanc757de22011-03-25 00:43:55 +00001278 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001279 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001280
Eli Friedmanc757de22011-03-25 00:43:55 +00001281 APSInt Init;
1282 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001283 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001284
Eli Friedmanc757de22011-03-25 00:43:55 +00001285 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1286 "Vectors must be composed of ints or floats");
1287
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001288 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001289 for (unsigned i = 0; i != NElts; ++i) {
1290 APSInt Tmp = Init.extOrTrunc(EltWidth);
1291
1292 if (EltTy->isIntegerType())
1293 Elts.push_back(APValue(Tmp));
1294 else
1295 Elts.push_back(APValue(APFloat(Tmp)));
1296
1297 Init >>= EltWidth;
1298 }
Richard Smith2d406342011-10-22 21:10:00 +00001299 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001300 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001301 default:
Richard Smith11562c52011-10-28 17:51:58 +00001302 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001303 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001304}
1305
Richard Smith2d406342011-10-22 21:10:00 +00001306bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001307VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001308 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001309 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001310 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001311
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001312 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001313 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001314
John McCall875679e2010-06-11 17:54:15 +00001315 // If a vector is initialized with a single element, that value
1316 // becomes every element of the vector, not just the first.
1317 // This is the behavior described in the IBM AltiVec documentation.
1318 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001319
1320 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001321 // vector (OpenCL 6.1.6).
1322 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001323 return Visit(E->getInit(0));
1324
John McCall875679e2010-06-11 17:54:15 +00001325 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001326 if (EltTy->isIntegerType()) {
1327 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001328 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001329 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001330 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001331 } else {
1332 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001333 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001334 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001335 InitValue = APValue(f);
1336 }
1337 for (unsigned i = 0; i < NumElements; i++) {
1338 Elements.push_back(InitValue);
1339 }
1340 } else {
1341 for (unsigned i = 0; i < NumElements; i++) {
1342 if (EltTy->isIntegerType()) {
1343 llvm::APSInt sInt(32);
1344 if (i < NumInits) {
1345 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001346 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001347 } else {
1348 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1349 }
1350 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001351 } else {
John McCall875679e2010-06-11 17:54:15 +00001352 llvm::APFloat f(0.0);
1353 if (i < NumInits) {
1354 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001355 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001356 } else {
1357 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1358 }
1359 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001360 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001361 }
1362 }
Richard Smith2d406342011-10-22 21:10:00 +00001363 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001364}
1365
Richard Smith2d406342011-10-22 21:10:00 +00001366bool
1367VectorExprEvaluator::ValueInitialization(const Expr *E) {
1368 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001369 QualType EltTy = VT->getElementType();
1370 APValue ZeroElement;
1371 if (EltTy->isIntegerType())
1372 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1373 else
1374 ZeroElement =
1375 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1376
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001377 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001378 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001379}
1380
Richard Smith2d406342011-10-22 21:10:00 +00001381bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001382 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001383 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001384}
1385
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001386//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001387// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001388//
1389// As a GNU extension, we support casting pointers to sufficiently-wide integer
1390// types and back in constant folding. Integer values are thus represented
1391// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001392//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001393
1394namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001395class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001396 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001397 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001398public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001399 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001400 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001401
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001402 bool Success(const llvm::APSInt &SI, const Expr *E) {
1403 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001404 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001405 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001406 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001407 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001408 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001409 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001410 return true;
1411 }
1412
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001413 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001414 assert(E->getType()->isIntegralOrEnumerationType() &&
1415 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001416 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001417 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001418 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001419 Result.getInt().setIsUnsigned(
1420 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001421 return true;
1422 }
1423
1424 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001425 assert(E->getType()->isIntegralOrEnumerationType() &&
1426 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001427 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001428 return true;
1429 }
1430
Ken Dyckdbc01912011-03-11 02:13:43 +00001431 bool Success(CharUnits Size, const Expr *E) {
1432 return Success(Size.getQuantity(), E);
1433 }
1434
1435
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001436 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001437 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001438 if (Info.EvalStatus.Diag == 0) {
1439 Info.EvalStatus.DiagLoc = L;
1440 Info.EvalStatus.Diag = D;
1441 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001442 }
Chris Lattner99415702008-07-12 00:14:42 +00001443 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001444 }
Mike Stump11289f42009-09-09 15:08:12 +00001445
Richard Smith0b0a0b62011-10-29 20:57:55 +00001446 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001447 if (V.isLValue()) {
1448 Result = V;
1449 return true;
1450 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001451 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001452 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001453 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001454 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
Richard Smith4ce706a2011-10-11 21:43:33 +00001457 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1458
Peter Collingbournee9200682011-05-13 03:29:01 +00001459 //===--------------------------------------------------------------------===//
1460 // Visitor Methods
1461 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001462
Chris Lattner7174bf32008-07-12 00:38:25 +00001463 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001464 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001465 }
1466 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001467 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001468 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001469
1470 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1471 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001472 if (CheckReferencedDecl(E, E->getDecl()))
1473 return true;
1474
1475 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001476 }
1477 bool VisitMemberExpr(const MemberExpr *E) {
1478 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001479 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001480 return true;
1481 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001482
1483 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001484 }
1485
Peter Collingbournee9200682011-05-13 03:29:01 +00001486 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001487 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001488 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001489 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001490
Peter Collingbournee9200682011-05-13 03:29:01 +00001491 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001492 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001493
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001494 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001495 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Richard Smith4ce706a2011-10-11 21:43:33 +00001498 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001499 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001500 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001501 }
1502
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001503 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001504 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001505 }
1506
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001507 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1508 return Success(E->getValue(), E);
1509 }
1510
John Wiegley6242b6a2011-04-28 00:16:57 +00001511 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1512 return Success(E->getValue(), E);
1513 }
1514
John Wiegleyf9f65842011-04-25 06:54:41 +00001515 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1516 return Success(E->getValue(), E);
1517 }
1518
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001519 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001520 bool VisitUnaryImag(const UnaryOperator *E);
1521
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001522 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001523 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001524
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001525private:
Ken Dyck160146e2010-01-27 17:10:57 +00001526 CharUnits GetAlignOfExpr(const Expr *E);
1527 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001528 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001529 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001530 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001531};
Chris Lattner05706e882008-07-11 18:11:29 +00001532} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001533
Richard Smith11562c52011-10-28 17:51:58 +00001534/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1535/// produce either the integer value or a pointer.
1536///
1537/// GCC has a heinous extension which folds casts between pointer types and
1538/// pointer-sized integral types. We support this by allowing the evaluation of
1539/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1540/// Some simple arithmetic on such values is supported (they are treated much
1541/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001542static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1543 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001544 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001545 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001546}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001547
Daniel Dunbarce399542009-02-20 18:22:23 +00001548static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001549 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001550 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1551 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001552 Result = Val.getInt();
1553 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001554}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001555
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001556bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001557 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001558 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001559 // Check for signedness/width mismatches between E type and ECD value.
1560 bool SameSign = (ECD->getInitVal().isSigned()
1561 == E->getType()->isSignedIntegerOrEnumerationType());
1562 bool SameWidth = (ECD->getInitVal().getBitWidth()
1563 == Info.Ctx.getIntWidth(E->getType()));
1564 if (SameSign && SameWidth)
1565 return Success(ECD->getInitVal(), E);
1566 else {
1567 // Get rid of mismatch (otherwise Success assertions will fail)
1568 // by computing a new value matching the type of E.
1569 llvm::APSInt Val = ECD->getInitVal();
1570 if (!SameSign)
1571 Val.setIsSigned(!ECD->getInitVal().isSigned());
1572 if (!SameWidth)
1573 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1574 return Success(Val, E);
1575 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001576 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001577 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001578}
1579
Chris Lattner86ee2862008-10-06 06:40:35 +00001580/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1581/// as GCC.
1582static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1583 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001584 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001585 enum gcc_type_class {
1586 no_type_class = -1,
1587 void_type_class, integer_type_class, char_type_class,
1588 enumeral_type_class, boolean_type_class,
1589 pointer_type_class, reference_type_class, offset_type_class,
1590 real_type_class, complex_type_class,
1591 function_type_class, method_type_class,
1592 record_type_class, union_type_class,
1593 array_type_class, string_type_class,
1594 lang_type_class
1595 };
Mike Stump11289f42009-09-09 15:08:12 +00001596
1597 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001598 // ideal, however it is what gcc does.
1599 if (E->getNumArgs() == 0)
1600 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001601
Chris Lattner86ee2862008-10-06 06:40:35 +00001602 QualType ArgTy = E->getArg(0)->getType();
1603 if (ArgTy->isVoidType())
1604 return void_type_class;
1605 else if (ArgTy->isEnumeralType())
1606 return enumeral_type_class;
1607 else if (ArgTy->isBooleanType())
1608 return boolean_type_class;
1609 else if (ArgTy->isCharType())
1610 return string_type_class; // gcc doesn't appear to use char_type_class
1611 else if (ArgTy->isIntegerType())
1612 return integer_type_class;
1613 else if (ArgTy->isPointerType())
1614 return pointer_type_class;
1615 else if (ArgTy->isReferenceType())
1616 return reference_type_class;
1617 else if (ArgTy->isRealType())
1618 return real_type_class;
1619 else if (ArgTy->isComplexType())
1620 return complex_type_class;
1621 else if (ArgTy->isFunctionType())
1622 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001623 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001624 return record_type_class;
1625 else if (ArgTy->isUnionType())
1626 return union_type_class;
1627 else if (ArgTy->isArrayType())
1628 return array_type_class;
1629 else if (ArgTy->isUnionType())
1630 return union_type_class;
1631 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001632 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001633 return -1;
1634}
1635
John McCall95007602010-05-10 23:27:23 +00001636/// Retrieves the "underlying object type" of the given expression,
1637/// as used by __builtin_object_size.
1638QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1639 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1640 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1641 return VD->getType();
1642 } else if (isa<CompoundLiteralExpr>(E)) {
1643 return E->getType();
1644 }
1645
1646 return QualType();
1647}
1648
Peter Collingbournee9200682011-05-13 03:29:01 +00001649bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001650 // TODO: Perhaps we should let LLVM lower this?
1651 LValue Base;
1652 if (!EvaluatePointer(E->getArg(0), Base, Info))
1653 return false;
1654
1655 // If we can prove the base is null, lower to zero now.
1656 const Expr *LVBase = Base.getLValueBase();
1657 if (!LVBase) return Success(0, E);
1658
1659 QualType T = GetObjectType(LVBase);
1660 if (T.isNull() ||
1661 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001662 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001663 T->isVariablyModifiedType() ||
1664 T->isDependentType())
1665 return false;
1666
1667 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1668 CharUnits Offset = Base.getLValueOffset();
1669
1670 if (!Offset.isNegative() && Offset <= Size)
1671 Size -= Offset;
1672 else
1673 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001674 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001675}
1676
Peter Collingbournee9200682011-05-13 03:29:01 +00001677bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001678 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001679 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001680 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001681
1682 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001683 if (TryEvaluateBuiltinObjectSize(E))
1684 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001685
Eric Christopher99469702010-01-19 22:58:35 +00001686 // If evaluating the argument has side-effects we can't determine
1687 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001688 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001689 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001690 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001691 return Success(0, E);
1692 }
Mike Stump876387b2009-10-27 22:09:17 +00001693
Mike Stump722cedf2009-10-26 18:35:08 +00001694 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1695 }
1696
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001697 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001698 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Anders Carlsson4c76e932008-11-24 04:21:33 +00001700 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001701 // __builtin_constant_p always has one operand: it returns true if that
1702 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001703 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001704
1705 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001706 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001708 return Success(Operand, E);
1709 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001710
1711 case Builtin::BI__builtin_expect:
1712 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001713
1714 case Builtin::BIstrlen:
1715 case Builtin::BI__builtin_strlen:
1716 // As an extension, we support strlen() and __builtin_strlen() as constant
1717 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001718 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001719 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1720 // The string literal may have embedded null characters. Find the first
1721 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001722 StringRef Str = S->getString();
1723 StringRef::size_type Pos = Str.find(0);
1724 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001725 Str = Str.substr(0, Pos);
1726
1727 return Success(Str.size(), E);
1728 }
1729
1730 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001731
1732 case Builtin::BI__atomic_is_lock_free: {
1733 APSInt SizeVal;
1734 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1735 return false;
1736
1737 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1738 // of two less than the maximum inline atomic width, we know it is
1739 // lock-free. If the size isn't a power of two, or greater than the
1740 // maximum alignment where we promote atomics, we know it is not lock-free
1741 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1742 // the answer can only be determined at runtime; for example, 16-byte
1743 // atomics have lock-free implementations on some, but not all,
1744 // x86-64 processors.
1745
1746 // Check power-of-two.
1747 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1748 if (!Size.isPowerOfTwo())
1749#if 0
1750 // FIXME: Suppress this folding until the ABI for the promotion width
1751 // settles.
1752 return Success(0, E);
1753#else
1754 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1755#endif
1756
1757#if 0
1758 // Check against promotion width.
1759 // FIXME: Suppress this folding until the ABI for the promotion width
1760 // settles.
1761 unsigned PromoteWidthBits =
1762 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1763 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1764 return Success(0, E);
1765#endif
1766
1767 // Check against inlining width.
1768 unsigned InlineWidthBits =
1769 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1770 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1771 return Success(1, E);
1772
1773 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1774 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001775 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001776}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001777
Richard Smith8b3497e2011-10-31 01:37:14 +00001778static bool HasSameBase(const LValue &A, const LValue &B) {
1779 if (!A.getLValueBase())
1780 return !B.getLValueBase();
1781 if (!B.getLValueBase())
1782 return false;
1783
1784 if (A.getLValueBase() != B.getLValueBase()) {
1785 const Decl *ADecl = GetLValueBaseDecl(A);
1786 if (!ADecl)
1787 return false;
1788 const Decl *BDecl = GetLValueBaseDecl(B);
1789 if (ADecl != BDecl)
1790 return false;
1791 }
1792
1793 return IsGlobalLValue(A.getLValueBase()) ||
1794 A.getLValueCallIndex() == B.getLValueCallIndex();
1795}
1796
Chris Lattnere13042c2008-07-11 19:10:17 +00001797bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001798 if (E->isAssignmentOp())
1799 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1800
John McCalle3027922010-08-25 11:45:40 +00001801 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001802 VisitIgnoredValue(E->getLHS());
1803 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001804 }
1805
1806 if (E->isLogicalOp()) {
1807 // These need to be handled specially because the operands aren't
1808 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001809 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001810
Richard Smith11562c52011-10-28 17:51:58 +00001811 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001812 // We were able to evaluate the LHS, see if we can get away with not
1813 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001814 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001815 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001816
Richard Smith11562c52011-10-28 17:51:58 +00001817 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001818 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001819 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001820 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001821 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001822 }
1823 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001824 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001825 // We can't evaluate the LHS; however, sometimes the result
1826 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001827 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1828 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001829 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001830 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001831 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001832
1833 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001834 }
1835 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001836 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001837
Eli Friedman5a332ea2008-11-13 06:09:17 +00001838 return false;
1839 }
1840
Anders Carlssonacc79812008-11-16 07:17:21 +00001841 QualType LHSTy = E->getLHS()->getType();
1842 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001843
1844 if (LHSTy->isAnyComplexType()) {
1845 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001846 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001847
1848 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1849 return false;
1850
1851 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1852 return false;
1853
1854 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001855 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001856 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001857 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001858 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1859
John McCalle3027922010-08-25 11:45:40 +00001860 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001861 return Success((CR_r == APFloat::cmpEqual &&
1862 CR_i == APFloat::cmpEqual), E);
1863 else {
John McCalle3027922010-08-25 11:45:40 +00001864 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001865 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001866 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001867 CR_r == APFloat::cmpLessThan ||
1868 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001869 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001870 CR_i == APFloat::cmpLessThan ||
1871 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001872 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001873 } else {
John McCalle3027922010-08-25 11:45:40 +00001874 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001875 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1876 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1877 else {
John McCalle3027922010-08-25 11:45:40 +00001878 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001879 "Invalid compex comparison.");
1880 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1881 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1882 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001883 }
1884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Anders Carlssonacc79812008-11-16 07:17:21 +00001886 if (LHSTy->isRealFloatingType() &&
1887 RHSTy->isRealFloatingType()) {
1888 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001889
Anders Carlssonacc79812008-11-16 07:17:21 +00001890 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1891 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001892
Anders Carlssonacc79812008-11-16 07:17:21 +00001893 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1894 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Anders Carlssonacc79812008-11-16 07:17:21 +00001896 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001897
Anders Carlssonacc79812008-11-16 07:17:21 +00001898 switch (E->getOpcode()) {
1899 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001900 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001901 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001902 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001903 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001904 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001905 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001906 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001907 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001908 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001909 E);
John McCalle3027922010-08-25 11:45:40 +00001910 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001911 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001912 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001913 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001914 || CR == APFloat::cmpLessThan
1915 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001916 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001917 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Eli Friedmana38da572009-04-28 19:17:36 +00001919 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00001920 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001921 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001922 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1923 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001924
John McCall45d55e42010-05-07 21:00:08 +00001925 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001926 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1927 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001928
Richard Smith8b3497e2011-10-31 01:37:14 +00001929 // Reject differing bases from the normal codepath; we special-case
1930 // comparisons to null.
1931 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00001932 // Inequalities and subtractions between unrelated pointers have
1933 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00001934 if (!E->isEqualityOp())
1935 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001936 // It's implementation-defined whether distinct literals will have
1937 // distinct addresses. We define it to be unspecified.
1938 if (IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001939 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001940 // We can't tell whether weak symbols will end up pointing to the same
1941 // object.
1942 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001943 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001944 // Pointers with different bases cannot represent the same object.
1945 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00001946 }
Eli Friedman64004332009-03-23 04:38:34 +00001947
John McCalle3027922010-08-25 11:45:40 +00001948 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001949 QualType Type = E->getLHS()->getType();
1950 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001951
Ken Dyck02990832010-01-15 12:37:54 +00001952 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001953 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001954 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001955
Ken Dyck02990832010-01-15 12:37:54 +00001956 CharUnits Diff = LHSValue.getLValueOffset() -
1957 RHSValue.getLValueOffset();
1958 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001959 }
Richard Smith8b3497e2011-10-31 01:37:14 +00001960
1961 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
1962 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
1963 switch (E->getOpcode()) {
1964 default: llvm_unreachable("missing comparison operator");
1965 case BO_LT: return Success(LHSOffset < RHSOffset, E);
1966 case BO_GT: return Success(LHSOffset > RHSOffset, E);
1967 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
1968 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
1969 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
1970 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001971 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001972 }
1973 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001974 if (!LHSTy->isIntegralOrEnumerationType() ||
1975 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001976 // We can't continue from here for non-integral types, and they
1977 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001978 return false;
1979 }
1980
Anders Carlsson9c181652008-07-08 14:35:21 +00001981 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001982 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00001983 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001984 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001985
Richard Smith11562c52011-10-28 17:51:58 +00001986 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001987 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001988 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001989
1990 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001991 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001992 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1993 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001994 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00001995 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001996 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00001997 LHSVal.getLValueOffset() -= AdditionalOffset;
1998 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00001999 return true;
2000 }
2001
2002 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002003 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002004 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002005 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2006 LHSVal.getInt().getZExtValue());
2007 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002008 return true;
2009 }
2010
2011 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002012 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002013 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002014
Richard Smith11562c52011-10-28 17:51:58 +00002015 APSInt &LHS = LHSVal.getInt();
2016 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002017
Anders Carlsson9c181652008-07-08 14:35:21 +00002018 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002019 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002020 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002021 case BO_Mul: return Success(LHS * RHS, E);
2022 case BO_Add: return Success(LHS + RHS, E);
2023 case BO_Sub: return Success(LHS - RHS, E);
2024 case BO_And: return Success(LHS & RHS, E);
2025 case BO_Xor: return Success(LHS ^ RHS, E);
2026 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002027 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002028 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002029 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002030 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002031 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002032 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002033 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002034 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002035 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002036 // During constant-folding, a negative shift is an opposite shift.
2037 if (RHS.isSigned() && RHS.isNegative()) {
2038 RHS = -RHS;
2039 goto shift_right;
2040 }
2041
2042 shift_left:
2043 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002044 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2045 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002046 }
John McCalle3027922010-08-25 11:45:40 +00002047 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002048 // During constant-folding, a negative shift is an opposite shift.
2049 if (RHS.isSigned() && RHS.isNegative()) {
2050 RHS = -RHS;
2051 goto shift_left;
2052 }
2053
2054 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002055 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002056 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2057 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Richard Smith11562c52011-10-28 17:51:58 +00002060 case BO_LT: return Success(LHS < RHS, E);
2061 case BO_GT: return Success(LHS > RHS, E);
2062 case BO_LE: return Success(LHS <= RHS, E);
2063 case BO_GE: return Success(LHS >= RHS, E);
2064 case BO_EQ: return Success(LHS == RHS, E);
2065 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002066 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002067}
2068
Ken Dyck160146e2010-01-27 17:10:57 +00002069CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002070 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2071 // the result is the size of the referenced type."
2072 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2073 // result shall be the alignment of the referenced type."
2074 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2075 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002076
2077 // __alignof is defined to return the preferred alignment.
2078 return Info.Ctx.toCharUnitsFromBits(
2079 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002080}
2081
Ken Dyck160146e2010-01-27 17:10:57 +00002082CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002083 E = E->IgnoreParens();
2084
2085 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002086 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002087 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002088 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2089 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002090
Chris Lattner68061312009-01-24 21:53:27 +00002091 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002092 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2093 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002094
Chris Lattner24aeeab2009-01-24 21:09:06 +00002095 return GetAlignOfType(E->getType());
2096}
2097
2098
Peter Collingbournee190dee2011-03-11 19:24:49 +00002099/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2100/// a result as the expression's type.
2101bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2102 const UnaryExprOrTypeTraitExpr *E) {
2103 switch(E->getKind()) {
2104 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002105 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002106 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002107 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002108 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002109 }
Eli Friedman64004332009-03-23 04:38:34 +00002110
Peter Collingbournee190dee2011-03-11 19:24:49 +00002111 case UETT_VecStep: {
2112 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002113
Peter Collingbournee190dee2011-03-11 19:24:49 +00002114 if (Ty->isVectorType()) {
2115 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002116
Peter Collingbournee190dee2011-03-11 19:24:49 +00002117 // The vec_step built-in functions that take a 3-component
2118 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2119 if (n == 3)
2120 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002121
Peter Collingbournee190dee2011-03-11 19:24:49 +00002122 return Success(n, E);
2123 } else
2124 return Success(1, E);
2125 }
2126
2127 case UETT_SizeOf: {
2128 QualType SrcTy = E->getTypeOfArgument();
2129 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2130 // the result is the size of the referenced type."
2131 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2132 // result shall be the alignment of the referenced type."
2133 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2134 SrcTy = Ref->getPointeeType();
2135
2136 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2137 // extension.
2138 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2139 return Success(1, E);
2140
2141 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2142 if (!SrcTy->isConstantSizeType())
2143 return false;
2144
2145 // Get information about the size.
2146 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2147 }
2148 }
2149
2150 llvm_unreachable("unknown expr/type trait");
2151 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002152}
2153
Peter Collingbournee9200682011-05-13 03:29:01 +00002154bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002155 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002156 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002157 if (n == 0)
2158 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002159 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002160 for (unsigned i = 0; i != n; ++i) {
2161 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2162 switch (ON.getKind()) {
2163 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002164 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002165 APSInt IdxResult;
2166 if (!EvaluateInteger(Idx, IdxResult, Info))
2167 return false;
2168 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2169 if (!AT)
2170 return false;
2171 CurrentType = AT->getElementType();
2172 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2173 Result += IdxResult.getSExtValue() * ElementSize;
2174 break;
2175 }
2176
2177 case OffsetOfExpr::OffsetOfNode::Field: {
2178 FieldDecl *MemberDecl = ON.getField();
2179 const RecordType *RT = CurrentType->getAs<RecordType>();
2180 if (!RT)
2181 return false;
2182 RecordDecl *RD = RT->getDecl();
2183 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002184 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002185 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002186 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002187 CurrentType = MemberDecl->getType().getNonReferenceType();
2188 break;
2189 }
2190
2191 case OffsetOfExpr::OffsetOfNode::Identifier:
2192 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002193 return false;
2194
2195 case OffsetOfExpr::OffsetOfNode::Base: {
2196 CXXBaseSpecifier *BaseSpec = ON.getBase();
2197 if (BaseSpec->isVirtual())
2198 return false;
2199
2200 // Find the layout of the class whose base we are looking into.
2201 const RecordType *RT = CurrentType->getAs<RecordType>();
2202 if (!RT)
2203 return false;
2204 RecordDecl *RD = RT->getDecl();
2205 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2206
2207 // Find the base class itself.
2208 CurrentType = BaseSpec->getType();
2209 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2210 if (!BaseRT)
2211 return false;
2212
2213 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002214 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002215 break;
2216 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002217 }
2218 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002219 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002220}
2221
Chris Lattnere13042c2008-07-11 19:10:17 +00002222bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002223 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002224 // LNot's operand isn't necessarily an integer, so we handle it specially.
2225 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002226 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002227 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002228 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002229 }
2230
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002231 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002232 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002233 return false;
2234
Richard Smith11562c52011-10-28 17:51:58 +00002235 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002236 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002237 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002238 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002239
Chris Lattnerf09ad162008-07-11 22:15:16 +00002240 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002241 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002242 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2243 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002244 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002245 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002246 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2247 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002248 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002249 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002250 // The result is just the value.
2251 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002252 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002253 if (!Val.isInt()) return false;
2254 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002255 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002256 if (!Val.isInt()) return false;
2257 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002258 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002259}
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattner477c4be2008-07-12 01:15:53 +00002261/// HandleCast - This is used to evaluate implicit or explicit casts where the
2262/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002263bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2264 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002265 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002266 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002267
Eli Friedmanc757de22011-03-25 00:43:55 +00002268 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002269 case CK_BaseToDerived:
2270 case CK_DerivedToBase:
2271 case CK_UncheckedDerivedToBase:
2272 case CK_Dynamic:
2273 case CK_ToUnion:
2274 case CK_ArrayToPointerDecay:
2275 case CK_FunctionToPointerDecay:
2276 case CK_NullToPointer:
2277 case CK_NullToMemberPointer:
2278 case CK_BaseToDerivedMemberPointer:
2279 case CK_DerivedToBaseMemberPointer:
2280 case CK_ConstructorConversion:
2281 case CK_IntegralToPointer:
2282 case CK_ToVoid:
2283 case CK_VectorSplat:
2284 case CK_IntegralToFloating:
2285 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002286 case CK_CPointerToObjCPointerCast:
2287 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002288 case CK_AnyPointerToBlockPointerCast:
2289 case CK_ObjCObjectLValueCast:
2290 case CK_FloatingRealToComplex:
2291 case CK_FloatingComplexToReal:
2292 case CK_FloatingComplexCast:
2293 case CK_FloatingComplexToIntegralComplex:
2294 case CK_IntegralRealToComplex:
2295 case CK_IntegralComplexCast:
2296 case CK_IntegralComplexToFloatingComplex:
2297 llvm_unreachable("invalid cast kind for integral value");
2298
Eli Friedman9faf2f92011-03-25 19:07:11 +00002299 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002300 case CK_Dependent:
2301 case CK_GetObjCProperty:
2302 case CK_LValueBitCast:
2303 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002304 case CK_ARCProduceObject:
2305 case CK_ARCConsumeObject:
2306 case CK_ARCReclaimReturnedObject:
2307 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002308 return false;
2309
2310 case CK_LValueToRValue:
2311 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002312 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002313
2314 case CK_MemberPointerToBoolean:
2315 case CK_PointerToBoolean:
2316 case CK_IntegralToBoolean:
2317 case CK_FloatingToBoolean:
2318 case CK_FloatingComplexToBoolean:
2319 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002320 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002321 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002322 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002323 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002324 }
2325
Eli Friedmanc757de22011-03-25 00:43:55 +00002326 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002327 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002328 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002329
Eli Friedman742421e2009-02-20 01:15:07 +00002330 if (!Result.isInt()) {
2331 // Only allow casts of lvalues if they are lossless.
2332 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2333 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002334
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002335 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002336 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002337 }
Mike Stump11289f42009-09-09 15:08:12 +00002338
Eli Friedmanc757de22011-03-25 00:43:55 +00002339 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002340 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002341 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002342 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002343
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002344 if (LV.getLValueBase()) {
2345 // Only allow based lvalue casts if they are lossless.
2346 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2347 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002348
John McCall45d55e42010-05-07 21:00:08 +00002349 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002350 return true;
2351 }
2352
Ken Dyck02990832010-01-15 12:37:54 +00002353 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2354 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002355 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002356 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002357
Eli Friedmanc757de22011-03-25 00:43:55 +00002358 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002359 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002360 if (!EvaluateComplex(SubExpr, C, Info))
2361 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002362 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002363 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002364
Eli Friedmanc757de22011-03-25 00:43:55 +00002365 case CK_FloatingToIntegral: {
2366 APFloat F(0.0);
2367 if (!EvaluateFloat(SubExpr, F, Info))
2368 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002369
Eli Friedmanc757de22011-03-25 00:43:55 +00002370 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2371 }
2372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Eli Friedmanc757de22011-03-25 00:43:55 +00002374 llvm_unreachable("unknown cast resulting in integral value");
2375 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002376}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002377
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002378bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2379 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002380 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002381 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2382 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2383 return Success(LV.getComplexIntReal(), E);
2384 }
2385
2386 return Visit(E->getSubExpr());
2387}
2388
Eli Friedman4e7a2412009-02-27 04:45:43 +00002389bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002390 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002391 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002392 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2393 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2394 return Success(LV.getComplexIntImag(), E);
2395 }
2396
Richard Smith4a678122011-10-24 18:44:57 +00002397 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002398 return Success(0, E);
2399}
2400
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002401bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2402 return Success(E->getPackLength(), E);
2403}
2404
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002405bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2406 return Success(E->getValue(), E);
2407}
2408
Chris Lattner05706e882008-07-11 18:11:29 +00002409//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002410// Float Evaluation
2411//===----------------------------------------------------------------------===//
2412
2413namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002414class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002415 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002416 APFloat &Result;
2417public:
2418 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002419 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002420
Richard Smith0b0a0b62011-10-29 20:57:55 +00002421 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002422 Result = V.getFloat();
2423 return true;
2424 }
2425 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002426 return false;
2427 }
2428
Richard Smith4ce706a2011-10-11 21:43:33 +00002429 bool ValueInitialization(const Expr *E) {
2430 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2431 return true;
2432 }
2433
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002434 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002435
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002436 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002437 bool VisitBinaryOperator(const BinaryOperator *E);
2438 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002439 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002440
John McCallb1fb0d32010-05-07 22:08:54 +00002441 bool VisitUnaryReal(const UnaryOperator *E);
2442 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002443
John McCallb1fb0d32010-05-07 22:08:54 +00002444 // FIXME: Missing: array subscript of vector, member of vector,
2445 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002446};
2447} // end anonymous namespace
2448
2449static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002450 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002451 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002452}
2453
Jay Foad39c79802011-01-12 09:06:06 +00002454static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002455 QualType ResultTy,
2456 const Expr *Arg,
2457 bool SNaN,
2458 llvm::APFloat &Result) {
2459 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2460 if (!S) return false;
2461
2462 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2463
2464 llvm::APInt fill;
2465
2466 // Treat empty strings as if they were zero.
2467 if (S->getString().empty())
2468 fill = llvm::APInt(32, 0);
2469 else if (S->getString().getAsInteger(0, fill))
2470 return false;
2471
2472 if (SNaN)
2473 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2474 else
2475 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2476 return true;
2477}
2478
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002479bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002480 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002481 default:
2482 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2483
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002484 case Builtin::BI__builtin_huge_val:
2485 case Builtin::BI__builtin_huge_valf:
2486 case Builtin::BI__builtin_huge_vall:
2487 case Builtin::BI__builtin_inf:
2488 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002489 case Builtin::BI__builtin_infl: {
2490 const llvm::fltSemantics &Sem =
2491 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002492 Result = llvm::APFloat::getInf(Sem);
2493 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
John McCall16291492010-02-28 13:00:19 +00002496 case Builtin::BI__builtin_nans:
2497 case Builtin::BI__builtin_nansf:
2498 case Builtin::BI__builtin_nansl:
2499 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2500 true, Result);
2501
Chris Lattner0b7282e2008-10-06 06:31:58 +00002502 case Builtin::BI__builtin_nan:
2503 case Builtin::BI__builtin_nanf:
2504 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002505 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002506 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002507 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2508 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002509
2510 case Builtin::BI__builtin_fabs:
2511 case Builtin::BI__builtin_fabsf:
2512 case Builtin::BI__builtin_fabsl:
2513 if (!EvaluateFloat(E->getArg(0), Result, Info))
2514 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002516 if (Result.isNegative())
2517 Result.changeSign();
2518 return true;
2519
Mike Stump11289f42009-09-09 15:08:12 +00002520 case Builtin::BI__builtin_copysign:
2521 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002522 case Builtin::BI__builtin_copysignl: {
2523 APFloat RHS(0.);
2524 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2525 !EvaluateFloat(E->getArg(1), RHS, Info))
2526 return false;
2527 Result.copySign(RHS);
2528 return true;
2529 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002530 }
2531}
2532
John McCallb1fb0d32010-05-07 22:08:54 +00002533bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002534 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2535 ComplexValue CV;
2536 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2537 return false;
2538 Result = CV.FloatReal;
2539 return true;
2540 }
2541
2542 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002543}
2544
2545bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002546 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2547 ComplexValue CV;
2548 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2549 return false;
2550 Result = CV.FloatImag;
2551 return true;
2552 }
2553
Richard Smith4a678122011-10-24 18:44:57 +00002554 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002555 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2556 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002557 return true;
2558}
2559
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002560bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002561 switch (E->getOpcode()) {
2562 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002563 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002564 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002565 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002566 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2567 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002568 Result.changeSign();
2569 return true;
2570 }
2571}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002572
Eli Friedman24c01542008-08-22 00:06:13 +00002573bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002574 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002575 VisitIgnoredValue(E->getLHS());
2576 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002577 }
2578
Richard Smith472d4952011-10-28 23:26:52 +00002579 // We can't evaluate pointer-to-member operations or assignments.
2580 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002581 return false;
2582
Eli Friedman24c01542008-08-22 00:06:13 +00002583 // FIXME: Diagnostics? I really don't understand how the warnings
2584 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002585 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002586 if (!EvaluateFloat(E->getLHS(), Result, Info))
2587 return false;
2588 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2589 return false;
2590
2591 switch (E->getOpcode()) {
2592 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002593 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002594 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2595 return true;
John McCalle3027922010-08-25 11:45:40 +00002596 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002597 Result.add(RHS, APFloat::rmNearestTiesToEven);
2598 return true;
John McCalle3027922010-08-25 11:45:40 +00002599 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002600 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2601 return true;
John McCalle3027922010-08-25 11:45:40 +00002602 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002603 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2604 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002605 }
2606}
2607
2608bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2609 Result = E->getValue();
2610 return true;
2611}
2612
Peter Collingbournee9200682011-05-13 03:29:01 +00002613bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2614 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002615
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002616 switch (E->getCastKind()) {
2617 default:
Richard Smith11562c52011-10-28 17:51:58 +00002618 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002619
2620 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002621 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002622 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002623 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002624 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002625 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002626 return true;
2627 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002628
2629 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002630 if (!Visit(SubExpr))
2631 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002632 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2633 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002634 return true;
2635 }
John McCalld7646252010-11-14 08:17:51 +00002636
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002637 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002638 ComplexValue V;
2639 if (!EvaluateComplex(SubExpr, V, Info))
2640 return false;
2641 Result = V.getComplexFloatReal();
2642 return true;
2643 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002644 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002645
2646 return false;
2647}
2648
Eli Friedman24c01542008-08-22 00:06:13 +00002649//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002650// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002651//===----------------------------------------------------------------------===//
2652
2653namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002654class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002655 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002656 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002657
Anders Carlsson537969c2008-11-16 20:27:53 +00002658public:
John McCall93d91dc2010-05-07 17:22:02 +00002659 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002660 : ExprEvaluatorBaseTy(info), Result(Result) {}
2661
Richard Smith0b0a0b62011-10-29 20:57:55 +00002662 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002663 Result.setFrom(V);
2664 return true;
2665 }
2666 bool Error(const Expr *E) {
2667 return false;
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Anders Carlsson537969c2008-11-16 20:27:53 +00002670 //===--------------------------------------------------------------------===//
2671 // Visitor Methods
2672 //===--------------------------------------------------------------------===//
2673
Peter Collingbournee9200682011-05-13 03:29:01 +00002674 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002675
Peter Collingbournee9200682011-05-13 03:29:01 +00002676 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002677
John McCall93d91dc2010-05-07 17:22:02 +00002678 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002679 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002680 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002681};
2682} // end anonymous namespace
2683
John McCall93d91dc2010-05-07 17:22:02 +00002684static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2685 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002686 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002687 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002688}
2689
Peter Collingbournee9200682011-05-13 03:29:01 +00002690bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2691 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002692
2693 if (SubExpr->getType()->isRealFloatingType()) {
2694 Result.makeComplexFloat();
2695 APFloat &Imag = Result.FloatImag;
2696 if (!EvaluateFloat(SubExpr, Imag, Info))
2697 return false;
2698
2699 Result.FloatReal = APFloat(Imag.getSemantics());
2700 return true;
2701 } else {
2702 assert(SubExpr->getType()->isIntegerType() &&
2703 "Unexpected imaginary literal.");
2704
2705 Result.makeComplexInt();
2706 APSInt &Imag = Result.IntImag;
2707 if (!EvaluateInteger(SubExpr, Imag, Info))
2708 return false;
2709
2710 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2711 return true;
2712 }
2713}
2714
Peter Collingbournee9200682011-05-13 03:29:01 +00002715bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002716
John McCallfcef3cf2010-12-14 17:51:41 +00002717 switch (E->getCastKind()) {
2718 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002719 case CK_BaseToDerived:
2720 case CK_DerivedToBase:
2721 case CK_UncheckedDerivedToBase:
2722 case CK_Dynamic:
2723 case CK_ToUnion:
2724 case CK_ArrayToPointerDecay:
2725 case CK_FunctionToPointerDecay:
2726 case CK_NullToPointer:
2727 case CK_NullToMemberPointer:
2728 case CK_BaseToDerivedMemberPointer:
2729 case CK_DerivedToBaseMemberPointer:
2730 case CK_MemberPointerToBoolean:
2731 case CK_ConstructorConversion:
2732 case CK_IntegralToPointer:
2733 case CK_PointerToIntegral:
2734 case CK_PointerToBoolean:
2735 case CK_ToVoid:
2736 case CK_VectorSplat:
2737 case CK_IntegralCast:
2738 case CK_IntegralToBoolean:
2739 case CK_IntegralToFloating:
2740 case CK_FloatingToIntegral:
2741 case CK_FloatingToBoolean:
2742 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002743 case CK_CPointerToObjCPointerCast:
2744 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002745 case CK_AnyPointerToBlockPointerCast:
2746 case CK_ObjCObjectLValueCast:
2747 case CK_FloatingComplexToReal:
2748 case CK_FloatingComplexToBoolean:
2749 case CK_IntegralComplexToReal:
2750 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002751 case CK_ARCProduceObject:
2752 case CK_ARCConsumeObject:
2753 case CK_ARCReclaimReturnedObject:
2754 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002755 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002756
John McCallfcef3cf2010-12-14 17:51:41 +00002757 case CK_LValueToRValue:
2758 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002759 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002760
2761 case CK_Dependent:
2762 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002763 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002764 case CK_UserDefinedConversion:
2765 return false;
2766
2767 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002768 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002769 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002770 return false;
2771
John McCallfcef3cf2010-12-14 17:51:41 +00002772 Result.makeComplexFloat();
2773 Result.FloatImag = APFloat(Real.getSemantics());
2774 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002775 }
2776
John McCallfcef3cf2010-12-14 17:51:41 +00002777 case CK_FloatingComplexCast: {
2778 if (!Visit(E->getSubExpr()))
2779 return false;
2780
2781 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2782 QualType From
2783 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2784
2785 Result.FloatReal
2786 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2787 Result.FloatImag
2788 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2789 return true;
2790 }
2791
2792 case CK_FloatingComplexToIntegralComplex: {
2793 if (!Visit(E->getSubExpr()))
2794 return false;
2795
2796 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2797 QualType From
2798 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2799 Result.makeComplexInt();
2800 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2801 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2802 return true;
2803 }
2804
2805 case CK_IntegralRealToComplex: {
2806 APSInt &Real = Result.IntReal;
2807 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2808 return false;
2809
2810 Result.makeComplexInt();
2811 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2812 return true;
2813 }
2814
2815 case CK_IntegralComplexCast: {
2816 if (!Visit(E->getSubExpr()))
2817 return false;
2818
2819 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2820 QualType From
2821 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2822
2823 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2824 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2825 return true;
2826 }
2827
2828 case CK_IntegralComplexToFloatingComplex: {
2829 if (!Visit(E->getSubExpr()))
2830 return false;
2831
2832 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2833 QualType From
2834 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2835 Result.makeComplexFloat();
2836 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2837 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2838 return true;
2839 }
2840 }
2841
2842 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002843 return false;
2844}
2845
John McCall93d91dc2010-05-07 17:22:02 +00002846bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002847 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002848 VisitIgnoredValue(E->getLHS());
2849 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002850 }
John McCall93d91dc2010-05-07 17:22:02 +00002851 if (!Visit(E->getLHS()))
2852 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002853
John McCall93d91dc2010-05-07 17:22:02 +00002854 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002855 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002856 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002857
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002858 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2859 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002860 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002861 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002862 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002863 if (Result.isComplexFloat()) {
2864 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2865 APFloat::rmNearestTiesToEven);
2866 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2867 APFloat::rmNearestTiesToEven);
2868 } else {
2869 Result.getComplexIntReal() += RHS.getComplexIntReal();
2870 Result.getComplexIntImag() += RHS.getComplexIntImag();
2871 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002872 break;
John McCalle3027922010-08-25 11:45:40 +00002873 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002874 if (Result.isComplexFloat()) {
2875 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2876 APFloat::rmNearestTiesToEven);
2877 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2878 APFloat::rmNearestTiesToEven);
2879 } else {
2880 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2881 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2882 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002883 break;
John McCalle3027922010-08-25 11:45:40 +00002884 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002885 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002886 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002887 APFloat &LHS_r = LHS.getComplexFloatReal();
2888 APFloat &LHS_i = LHS.getComplexFloatImag();
2889 APFloat &RHS_r = RHS.getComplexFloatReal();
2890 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002891
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002892 APFloat Tmp = LHS_r;
2893 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2894 Result.getComplexFloatReal() = Tmp;
2895 Tmp = LHS_i;
2896 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2897 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2898
2899 Tmp = LHS_r;
2900 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2901 Result.getComplexFloatImag() = Tmp;
2902 Tmp = LHS_i;
2903 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2904 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2905 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002906 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002907 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002908 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2909 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002910 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002911 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2912 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2913 }
2914 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002915 case BO_Div:
2916 if (Result.isComplexFloat()) {
2917 ComplexValue LHS = Result;
2918 APFloat &LHS_r = LHS.getComplexFloatReal();
2919 APFloat &LHS_i = LHS.getComplexFloatImag();
2920 APFloat &RHS_r = RHS.getComplexFloatReal();
2921 APFloat &RHS_i = RHS.getComplexFloatImag();
2922 APFloat &Res_r = Result.getComplexFloatReal();
2923 APFloat &Res_i = Result.getComplexFloatImag();
2924
2925 APFloat Den = RHS_r;
2926 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2927 APFloat Tmp = RHS_i;
2928 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2929 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2930
2931 Res_r = LHS_r;
2932 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2933 Tmp = LHS_i;
2934 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2935 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2936 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2937
2938 Res_i = LHS_i;
2939 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2940 Tmp = LHS_r;
2941 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2942 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2943 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2944 } else {
2945 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2946 // FIXME: what about diagnostics?
2947 return false;
2948 }
2949 ComplexValue LHS = Result;
2950 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2951 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2952 Result.getComplexIntReal() =
2953 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2954 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2955 Result.getComplexIntImag() =
2956 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2957 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2958 }
2959 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002960 }
2961
John McCall93d91dc2010-05-07 17:22:02 +00002962 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002963}
2964
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002965bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2966 // Get the operand value into 'Result'.
2967 if (!Visit(E->getSubExpr()))
2968 return false;
2969
2970 switch (E->getOpcode()) {
2971 default:
2972 // FIXME: what about diagnostics?
2973 return false;
2974 case UO_Extension:
2975 return true;
2976 case UO_Plus:
2977 // The result is always just the subexpr.
2978 return true;
2979 case UO_Minus:
2980 if (Result.isComplexFloat()) {
2981 Result.getComplexFloatReal().changeSign();
2982 Result.getComplexFloatImag().changeSign();
2983 }
2984 else {
2985 Result.getComplexIntReal() = -Result.getComplexIntReal();
2986 Result.getComplexIntImag() = -Result.getComplexIntImag();
2987 }
2988 return true;
2989 case UO_Not:
2990 if (Result.isComplexFloat())
2991 Result.getComplexFloatImag().changeSign();
2992 else
2993 Result.getComplexIntImag() = -Result.getComplexIntImag();
2994 return true;
2995 }
2996}
2997
Anders Carlsson537969c2008-11-16 20:27:53 +00002998//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00002999// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003000//===----------------------------------------------------------------------===//
3001
Richard Smith0b0a0b62011-10-29 20:57:55 +00003002static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003003 // In C, function designators are not lvalues, but we evaluate them as if they
3004 // are.
3005 if (E->isGLValue() || E->getType()->isFunctionType()) {
3006 LValue LV;
3007 if (!EvaluateLValue(E, LV, Info))
3008 return false;
3009 LV.moveInto(Result);
3010 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003011 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003012 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003013 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003014 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003015 return false;
John McCall45d55e42010-05-07 21:00:08 +00003016 } else if (E->getType()->hasPointerRepresentation()) {
3017 LValue LV;
3018 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003019 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003020 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003021 } else if (E->getType()->isRealFloatingType()) {
3022 llvm::APFloat F(0.0);
3023 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003024 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003025 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003026 } else if (E->getType()->isAnyComplexType()) {
3027 ComplexValue C;
3028 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003029 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003030 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003031 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003032 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003033
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003034 return true;
3035}
3036
Richard Smith11562c52011-10-28 17:51:58 +00003037
Richard Smith7b553f12011-10-29 00:50:52 +00003038/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003039/// any crazy technique (that has nothing to do with language standards) that
3040/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003041/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3042/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003043bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003044 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003045
Richard Smith0b0a0b62011-10-29 20:57:55 +00003046 CCValue Value;
3047 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003048 return false;
3049
3050 if (isGLValue()) {
3051 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003052 LV.setFrom(Value);
3053 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3054 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003055 }
3056
Richard Smith0b0a0b62011-10-29 20:57:55 +00003057 // Check this core constant expression is a constant expression, and if so,
3058 // slice it down to one.
3059 if (!CheckConstantExpression(Value))
3060 return false;
3061 Result.Val = Value;
3062 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003063}
3064
Jay Foad39c79802011-01-12 09:06:06 +00003065bool Expr::EvaluateAsBooleanCondition(bool &Result,
3066 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003067 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003068 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003069 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3070 Result);
John McCall1be1c632010-01-05 23:42:56 +00003071}
3072
Richard Smithcaf33902011-10-10 18:28:20 +00003073bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003074 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003075 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003076 !ExprResult.Val.isInt()) {
3077 return false;
3078 }
3079 Result = ExprResult.Val.getInt();
3080 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003081}
3082
Jay Foad39c79802011-01-12 09:06:06 +00003083bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003084 EvalInfo Info(Ctx, Result);
3085
John McCall45d55e42010-05-07 21:00:08 +00003086 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003087 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003088 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003089 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003090 return true;
3091 }
3092 return false;
3093}
3094
Jay Foad39c79802011-01-12 09:06:06 +00003095bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3096 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003097 EvalInfo Info(Ctx, Result);
3098
3099 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003100 // Don't allow references to out-of-scope function parameters to escape.
3101 if (EvaluateLValue(this, LV, Info) &&
3102 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3103 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003104 return true;
3105 }
3106 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003107}
3108
Richard Smith7b553f12011-10-29 00:50:52 +00003109/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3110/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003111bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003112 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003113 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003114}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003115
Jay Foad39c79802011-01-12 09:06:06 +00003116bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003117 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003118}
3119
Richard Smithcaf33902011-10-10 18:28:20 +00003120APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003121 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003122 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003123 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003124 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003125 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003126
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003127 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003128}
John McCall864e3962010-05-07 05:32:02 +00003129
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003130 bool Expr::EvalResult::isGlobalLValue() const {
3131 assert(Val.isLValue());
3132 return IsGlobalLValue(Val.getLValueBase());
3133 }
3134
3135
John McCall864e3962010-05-07 05:32:02 +00003136/// isIntegerConstantExpr - this recursive routine will test if an expression is
3137/// an integer constant expression.
3138
3139/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3140/// comma, etc
3141///
3142/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3143/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3144/// cast+dereference.
3145
3146// CheckICE - This function does the fundamental ICE checking: the returned
3147// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3148// Note that to reduce code duplication, this helper does no evaluation
3149// itself; the caller checks whether the expression is evaluatable, and
3150// in the rare cases where CheckICE actually cares about the evaluated
3151// value, it calls into Evalute.
3152//
3153// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003154// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003155// 1: This expression is not an ICE, but if it isn't evaluated, it's
3156// a legal subexpression for an ICE. This return value is used to handle
3157// the comma operator in C99 mode.
3158// 2: This expression is not an ICE, and is not a legal subexpression for one.
3159
Dan Gohman28ade552010-07-26 21:25:24 +00003160namespace {
3161
John McCall864e3962010-05-07 05:32:02 +00003162struct ICEDiag {
3163 unsigned Val;
3164 SourceLocation Loc;
3165
3166 public:
3167 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3168 ICEDiag() : Val(0) {}
3169};
3170
Dan Gohman28ade552010-07-26 21:25:24 +00003171}
3172
3173static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003174
3175static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3176 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003177 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003178 !EVResult.Val.isInt()) {
3179 return ICEDiag(2, E->getLocStart());
3180 }
3181 return NoDiag();
3182}
3183
3184static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3185 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003186 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003187 return ICEDiag(2, E->getLocStart());
3188 }
3189
3190 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003191#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003192#define STMT(Node, Base) case Expr::Node##Class:
3193#define EXPR(Node, Base)
3194#include "clang/AST/StmtNodes.inc"
3195 case Expr::PredefinedExprClass:
3196 case Expr::FloatingLiteralClass:
3197 case Expr::ImaginaryLiteralClass:
3198 case Expr::StringLiteralClass:
3199 case Expr::ArraySubscriptExprClass:
3200 case Expr::MemberExprClass:
3201 case Expr::CompoundAssignOperatorClass:
3202 case Expr::CompoundLiteralExprClass:
3203 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003204 case Expr::DesignatedInitExprClass:
3205 case Expr::ImplicitValueInitExprClass:
3206 case Expr::ParenListExprClass:
3207 case Expr::VAArgExprClass:
3208 case Expr::AddrLabelExprClass:
3209 case Expr::StmtExprClass:
3210 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003211 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003212 case Expr::CXXDynamicCastExprClass:
3213 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003214 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003215 case Expr::CXXNullPtrLiteralExprClass:
3216 case Expr::CXXThisExprClass:
3217 case Expr::CXXThrowExprClass:
3218 case Expr::CXXNewExprClass:
3219 case Expr::CXXDeleteExprClass:
3220 case Expr::CXXPseudoDestructorExprClass:
3221 case Expr::UnresolvedLookupExprClass:
3222 case Expr::DependentScopeDeclRefExprClass:
3223 case Expr::CXXConstructExprClass:
3224 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003225 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003226 case Expr::CXXTemporaryObjectExprClass:
3227 case Expr::CXXUnresolvedConstructExprClass:
3228 case Expr::CXXDependentScopeMemberExprClass:
3229 case Expr::UnresolvedMemberExprClass:
3230 case Expr::ObjCStringLiteralClass:
3231 case Expr::ObjCEncodeExprClass:
3232 case Expr::ObjCMessageExprClass:
3233 case Expr::ObjCSelectorExprClass:
3234 case Expr::ObjCProtocolExprClass:
3235 case Expr::ObjCIvarRefExprClass:
3236 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003237 case Expr::ObjCIsaExprClass:
3238 case Expr::ShuffleVectorExprClass:
3239 case Expr::BlockExprClass:
3240 case Expr::BlockDeclRefExprClass:
3241 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003242 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003243 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003244 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003245 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003246 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003247 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003248 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003249 return ICEDiag(2, E->getLocStart());
3250
Sebastian Redl12757ab2011-09-24 17:48:14 +00003251 case Expr::InitListExprClass:
3252 if (Ctx.getLangOptions().CPlusPlus0x) {
3253 const InitListExpr *ILE = cast<InitListExpr>(E);
3254 if (ILE->getNumInits() == 0)
3255 return NoDiag();
3256 if (ILE->getNumInits() == 1)
3257 return CheckICE(ILE->getInit(0), Ctx);
3258 // Fall through for more than 1 expression.
3259 }
3260 return ICEDiag(2, E->getLocStart());
3261
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003262 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003263 case Expr::GNUNullExprClass:
3264 // GCC considers the GNU __null value to be an integral constant expression.
3265 return NoDiag();
3266
John McCall7c454bb2011-07-15 05:09:51 +00003267 case Expr::SubstNonTypeTemplateParmExprClass:
3268 return
3269 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3270
John McCall864e3962010-05-07 05:32:02 +00003271 case Expr::ParenExprClass:
3272 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003273 case Expr::GenericSelectionExprClass:
3274 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003275 case Expr::IntegerLiteralClass:
3276 case Expr::CharacterLiteralClass:
3277 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003278 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003279 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003280 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003281 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003282 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003283 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003284 return NoDiag();
3285 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003286 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003287 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3288 // constant expressions, but they can never be ICEs because an ICE cannot
3289 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003290 const CallExpr *CE = cast<CallExpr>(E);
3291 if (CE->isBuiltinCall(Ctx))
3292 return CheckEvalInICE(E, Ctx);
3293 return ICEDiag(2, E->getLocStart());
3294 }
3295 case Expr::DeclRefExprClass:
3296 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3297 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003298 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003299 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3300
3301 // Parameter variables are never constants. Without this check,
3302 // getAnyInitializer() can find a default argument, which leads
3303 // to chaos.
3304 if (isa<ParmVarDecl>(D))
3305 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3306
3307 // C++ 7.1.5.1p2
3308 // A variable of non-volatile const-qualified integral or enumeration
3309 // type initialized by an ICE can be used in ICEs.
3310 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003311 // Look for a declaration of this variable that has an initializer.
3312 const VarDecl *ID = 0;
3313 const Expr *Init = Dcl->getAnyInitializer(ID);
3314 if (Init) {
3315 if (ID->isInitKnownICE()) {
3316 // We have already checked whether this subexpression is an
3317 // integral constant expression.
3318 if (ID->isInitICE())
3319 return NoDiag();
3320 else
3321 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3322 }
3323
3324 // It's an ICE whether or not the definition we found is
3325 // out-of-line. See DR 721 and the discussion in Clang PR
3326 // 6206 for details.
3327
3328 if (Dcl->isCheckingICE()) {
3329 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3330 }
3331
3332 Dcl->setCheckingICE();
3333 ICEDiag Result = CheckICE(Init, Ctx);
3334 // Cache the result of the ICE test.
3335 Dcl->setInitKnownICE(Result.Val == 0);
3336 return Result;
3337 }
3338 }
3339 }
3340 return ICEDiag(2, E->getLocStart());
3341 case Expr::UnaryOperatorClass: {
3342 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3343 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003344 case UO_PostInc:
3345 case UO_PostDec:
3346 case UO_PreInc:
3347 case UO_PreDec:
3348 case UO_AddrOf:
3349 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003350 // C99 6.6/3 allows increment and decrement within unevaluated
3351 // subexpressions of constant expressions, but they can never be ICEs
3352 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003353 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003354 case UO_Extension:
3355 case UO_LNot:
3356 case UO_Plus:
3357 case UO_Minus:
3358 case UO_Not:
3359 case UO_Real:
3360 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003361 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003362 }
3363
3364 // OffsetOf falls through here.
3365 }
3366 case Expr::OffsetOfExprClass: {
3367 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003368 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003369 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003370 // compliance: we should warn earlier for offsetof expressions with
3371 // array subscripts that aren't ICEs, and if the array subscripts
3372 // are ICEs, the value of the offsetof must be an integer constant.
3373 return CheckEvalInICE(E, Ctx);
3374 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003375 case Expr::UnaryExprOrTypeTraitExprClass: {
3376 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3377 if ((Exp->getKind() == UETT_SizeOf) &&
3378 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003379 return ICEDiag(2, E->getLocStart());
3380 return NoDiag();
3381 }
3382 case Expr::BinaryOperatorClass: {
3383 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3384 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003385 case BO_PtrMemD:
3386 case BO_PtrMemI:
3387 case BO_Assign:
3388 case BO_MulAssign:
3389 case BO_DivAssign:
3390 case BO_RemAssign:
3391 case BO_AddAssign:
3392 case BO_SubAssign:
3393 case BO_ShlAssign:
3394 case BO_ShrAssign:
3395 case BO_AndAssign:
3396 case BO_XorAssign:
3397 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003398 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3399 // constant expressions, but they can never be ICEs because an ICE cannot
3400 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003401 return ICEDiag(2, E->getLocStart());
3402
John McCalle3027922010-08-25 11:45:40 +00003403 case BO_Mul:
3404 case BO_Div:
3405 case BO_Rem:
3406 case BO_Add:
3407 case BO_Sub:
3408 case BO_Shl:
3409 case BO_Shr:
3410 case BO_LT:
3411 case BO_GT:
3412 case BO_LE:
3413 case BO_GE:
3414 case BO_EQ:
3415 case BO_NE:
3416 case BO_And:
3417 case BO_Xor:
3418 case BO_Or:
3419 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003420 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3421 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003422 if (Exp->getOpcode() == BO_Div ||
3423 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003424 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003425 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003426 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003427 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003428 if (REval == 0)
3429 return ICEDiag(1, E->getLocStart());
3430 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003431 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003432 if (LEval.isMinSignedValue())
3433 return ICEDiag(1, E->getLocStart());
3434 }
3435 }
3436 }
John McCalle3027922010-08-25 11:45:40 +00003437 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003438 if (Ctx.getLangOptions().C99) {
3439 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3440 // if it isn't evaluated.
3441 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3442 return ICEDiag(1, E->getLocStart());
3443 } else {
3444 // In both C89 and C++, commas in ICEs are illegal.
3445 return ICEDiag(2, E->getLocStart());
3446 }
3447 }
3448 if (LHSResult.Val >= RHSResult.Val)
3449 return LHSResult;
3450 return RHSResult;
3451 }
John McCalle3027922010-08-25 11:45:40 +00003452 case BO_LAnd:
3453 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003454 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003455
3456 // C++0x [expr.const]p2:
3457 // [...] subexpressions of logical AND (5.14), logical OR
3458 // (5.15), and condi- tional (5.16) operations that are not
3459 // evaluated are not considered.
3460 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3461 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003462 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003463 return LHSResult;
3464
3465 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003466 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003467 return LHSResult;
3468 }
3469
John McCall864e3962010-05-07 05:32:02 +00003470 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3471 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3472 // Rare case where the RHS has a comma "side-effect"; we need
3473 // to actually check the condition to see whether the side
3474 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003475 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003476 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003477 return RHSResult;
3478 return NoDiag();
3479 }
3480
3481 if (LHSResult.Val >= RHSResult.Val)
3482 return LHSResult;
3483 return RHSResult;
3484 }
3485 }
3486 }
3487 case Expr::ImplicitCastExprClass:
3488 case Expr::CStyleCastExprClass:
3489 case Expr::CXXFunctionalCastExprClass:
3490 case Expr::CXXStaticCastExprClass:
3491 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003492 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003493 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003494 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003495 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003496 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3497 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003498 switch (cast<CastExpr>(E)->getCastKind()) {
3499 case CK_LValueToRValue:
3500 case CK_NoOp:
3501 case CK_IntegralToBoolean:
3502 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003503 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003504 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003505 return ICEDiag(2, E->getLocStart());
3506 }
John McCall864e3962010-05-07 05:32:02 +00003507 }
John McCallc07a0c72011-02-17 10:25:35 +00003508 case Expr::BinaryConditionalOperatorClass: {
3509 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3510 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3511 if (CommonResult.Val == 2) return CommonResult;
3512 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3513 if (FalseResult.Val == 2) return FalseResult;
3514 if (CommonResult.Val == 1) return CommonResult;
3515 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003516 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003517 return FalseResult;
3518 }
John McCall864e3962010-05-07 05:32:02 +00003519 case Expr::ConditionalOperatorClass: {
3520 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3521 // If the condition (ignoring parens) is a __builtin_constant_p call,
3522 // then only the true side is actually considered in an integer constant
3523 // expression, and it is fully evaluated. This is an important GNU
3524 // extension. See GCC PR38377 for discussion.
3525 if (const CallExpr *CallCE
3526 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3527 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3528 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003529 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003530 !EVResult.Val.isInt()) {
3531 return ICEDiag(2, E->getLocStart());
3532 }
3533 return NoDiag();
3534 }
3535 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003536 if (CondResult.Val == 2)
3537 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003538
3539 // C++0x [expr.const]p2:
3540 // subexpressions of [...] conditional (5.16) operations that
3541 // are not evaluated are not considered
3542 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003543 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003544 : false;
3545 ICEDiag TrueResult = NoDiag();
3546 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3547 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3548 ICEDiag FalseResult = NoDiag();
3549 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3550 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3551
John McCall864e3962010-05-07 05:32:02 +00003552 if (TrueResult.Val == 2)
3553 return TrueResult;
3554 if (FalseResult.Val == 2)
3555 return FalseResult;
3556 if (CondResult.Val == 1)
3557 return CondResult;
3558 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3559 return NoDiag();
3560 // Rare case where the diagnostics depend on which side is evaluated
3561 // Note that if we get here, CondResult is 0, and at least one of
3562 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003563 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003564 return FalseResult;
3565 }
3566 return TrueResult;
3567 }
3568 case Expr::CXXDefaultArgExprClass:
3569 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3570 case Expr::ChooseExprClass: {
3571 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3572 }
3573 }
3574
3575 // Silence a GCC warning
3576 return ICEDiag(2, E->getLocStart());
3577}
3578
3579bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3580 SourceLocation *Loc, bool isEvaluated) const {
3581 ICEDiag d = CheckICE(this, Ctx);
3582 if (d.Val != 0) {
3583 if (Loc) *Loc = d.Loc;
3584 return false;
3585 }
Richard Smith11562c52011-10-28 17:51:58 +00003586 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003587 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003588 return true;
3589}