blob: a12beb51792a8f17f94cea7a74b2f5ae6892c4b2 [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;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000049 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000050
Richard Smith0b0a0b62011-10-29 20:57:55 +000051 /// A core constant value. This can be the value of any constant expression,
52 /// or a pointer or reference to a non-static object or function parameter.
53 class CCValue : public APValue {
54 typedef llvm::APSInt APSInt;
55 typedef llvm::APFloat APFloat;
56 /// If the value is a DeclRefExpr lvalue referring to a ParmVarDecl, this is
57 /// the index of the corresponding function call.
58 unsigned CallIndex;
59 public:
60 CCValue() {}
61 explicit CCValue(const APSInt &I) : APValue(I) {}
62 explicit CCValue(const APFloat &F) : APValue(F) {}
63 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
64 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
65 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
66 CCValue(const CCValue &V) : APValue(V), CallIndex(V.CallIndex) {}
67 CCValue(const Expr *B, const CharUnits &O, unsigned I) :
68 APValue(B, O), CallIndex(I) {}
69 CCValue(const APValue &V, unsigned CallIndex) :
70 APValue(V), CallIndex(CallIndex) {}
71
Richard Smith4e4c78ff2011-10-31 05:52:43 +000072 enum { NoCallIndex = (unsigned)0 };
Richard Smith0b0a0b62011-10-29 20:57:55 +000073
74 unsigned getLValueCallIndex() const {
75 assert(getKind() == LValue);
76 return CallIndex;
77 }
78 };
79
Richard Smith254a73d2011-10-28 22:34:42 +000080 /// A stack frame in the constexpr call stack.
81 struct CallStackFrame {
82 EvalInfo &Info;
83
84 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +000085 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +000086
87 /// ParmBindings - Parameter bindings for this function call, indexed by
88 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +000089 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +000090
91 /// CallIndex - The index of the current call. This is used to match lvalues
92 /// referring to parameters up with the corresponding stack frame, and to
93 /// detect when the parameter is no longer in scope.
94 unsigned CallIndex;
95
Richard Smith4e4c78ff2011-10-31 05:52:43 +000096 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
97 typedef MapTy::const_iterator temp_iterator;
98 /// Temporaries - Temporary lvalues materialized within this stack frame.
99 MapTy Temporaries;
100
101 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
102 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000103 };
104
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000105 struct EvalInfo {
106 const ASTContext &Ctx;
107
108 /// EvalStatus - Contains information about the evaluation.
109 Expr::EvalStatus &EvalStatus;
110
111 /// CurrentCall - The top of the constexpr call stack.
112 CallStackFrame *CurrentCall;
113
114 /// NumCalls - The number of calls we've evaluated so far.
115 unsigned NumCalls;
116
117 /// CallStackDepth - The number of calls in the call stack right now.
118 unsigned CallStackDepth;
119
120 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
121 /// OpaqueValues - Values used as the common expression in a
122 /// BinaryConditionalOperator.
123 MapTy OpaqueValues;
124
125 /// BottomFrame - The frame in which evaluation started. This must be
126 /// initialized last.
127 CallStackFrame BottomFrame;
128
129
130 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
131 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
132 BottomFrame(*this, 0) {}
133
134 unsigned getCurrentCallIndex() const { return CurrentCall->CallIndex; }
135 CallStackFrame *getStackFrame(unsigned CallIndex) const;
136 const CCValue *getCallValue(unsigned CallIndex, unsigned ArgIndex) const;
137
138 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
139 MapTy::const_iterator i = OpaqueValues.find(e);
140 if (i == OpaqueValues.end()) return 0;
141 return &i->second;
142 }
143
144 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
145 };
146
147 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
148 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments),
149 CallIndex(Info.NumCalls++) {
150 Info.CurrentCall = this;
151 ++Info.CallStackDepth;
152 }
153
154 CallStackFrame::~CallStackFrame() {
155 assert(Info.CurrentCall == this && "calls retired out of order");
156 --Info.CallStackDepth;
157 Info.CurrentCall = Caller;
158 }
159
160 CallStackFrame *EvalInfo::getStackFrame(unsigned CallIndex) const {
161 for (CallStackFrame *Frame = CurrentCall;
162 Frame && Frame->CallIndex >= CallIndex; Frame = Frame->Caller)
163 if (Frame->CallIndex == CallIndex)
164 return Frame;
165 return 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000166 }
167
168 const CCValue *EvalInfo::getCallValue(unsigned CallIndex,
169 unsigned ArgIndex) const {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000170 if (CallIndex == 0)
171 return 0;
172 if (CallStackFrame *Frame = getStackFrame(CallIndex))
173 return Frame->Arguments + ArgIndex;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000174 return 0;
175 }
176
John McCall93d91dc2010-05-07 17:22:02 +0000177 struct ComplexValue {
178 private:
179 bool IsInt;
180
181 public:
182 APSInt IntReal, IntImag;
183 APFloat FloatReal, FloatImag;
184
185 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
186
187 void makeComplexFloat() { IsInt = false; }
188 bool isComplexFloat() const { return !IsInt; }
189 APFloat &getComplexFloatReal() { return FloatReal; }
190 APFloat &getComplexFloatImag() { return FloatImag; }
191
192 void makeComplexInt() { IsInt = true; }
193 bool isComplexInt() const { return IsInt; }
194 APSInt &getComplexIntReal() { return IntReal; }
195 APSInt &getComplexIntImag() { return IntImag; }
196
Richard Smith0b0a0b62011-10-29 20:57:55 +0000197 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000198 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000199 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000200 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000201 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000202 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000203 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000204 assert(v.isComplexFloat() || v.isComplexInt());
205 if (v.isComplexFloat()) {
206 makeComplexFloat();
207 FloatReal = v.getComplexFloatReal();
208 FloatImag = v.getComplexFloatImag();
209 } else {
210 makeComplexInt();
211 IntReal = v.getComplexIntReal();
212 IntImag = v.getComplexIntImag();
213 }
214 }
John McCall93d91dc2010-05-07 17:22:02 +0000215 };
John McCall45d55e42010-05-07 21:00:08 +0000216
217 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000218 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000219 CharUnits Offset;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000220 unsigned CallIndex;
John McCall45d55e42010-05-07 21:00:08 +0000221
Richard Smith8b3497e2011-10-31 01:37:14 +0000222 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000223 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000224 const CharUnits &getLValueOffset() const { return Offset; }
225 unsigned getLValueCallIndex() const { return CallIndex; }
John McCall45d55e42010-05-07 21:00:08 +0000226
Richard Smith0b0a0b62011-10-29 20:57:55 +0000227 void moveInto(CCValue &V) const {
228 V = CCValue(Base, Offset, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000229 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000230 void setFrom(const CCValue &V) {
231 assert(V.isLValue());
232 Base = V.getLValueBase();
233 Offset = V.getLValueOffset();
234 CallIndex = V.getLValueCallIndex();
John McCallc07a0c72011-02-17 10:25:35 +0000235 }
John McCall45d55e42010-05-07 21:00:08 +0000236 };
John McCall93d91dc2010-05-07 17:22:02 +0000237}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000238
Richard Smith0b0a0b62011-10-29 20:57:55 +0000239static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000240static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
241static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000242static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000243static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000244 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000245static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000246static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000247
248//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000249// Misc utilities
250//===----------------------------------------------------------------------===//
251
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000252static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000253 if (!E) return true;
254
255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
256 if (isa<FunctionDecl>(DRE->getDecl()))
257 return true;
258 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
259 return VD->hasGlobalStorage();
260 return false;
261 }
262
263 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
264 return CLE->isFileScope();
265
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000266 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000267 return false;
268
John McCall95007602010-05-10 23:27:23 +0000269 return true;
270}
271
Richard Smith0b0a0b62011-10-29 20:57:55 +0000272static bool IsParamLValue(const Expr *E) {
273 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
274 return isa<ParmVarDecl>(DRE->getDecl());
275 return false;
276}
277
278/// Check that this core constant expression value is a valid value for a
279/// constant expression.
280static bool CheckConstantExpression(const CCValue &Value) {
281 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
282}
283
Richard Smith83c68212011-10-31 05:11:32 +0000284const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
285 if (!LVal.Base)
286 return 0;
287
288 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
289 return DRE->getDecl();
290
291 // FIXME: Static data members accessed via a MemberExpr are represented as
292 // that MemberExpr. We should use the Decl directly instead.
293 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
294 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
295 return ME->getMemberDecl();
296 }
297
298 return 0;
299}
300
301static bool IsLiteralLValue(const LValue &Value) {
302 return Value.Base &&
303 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000304 !isa<MemberExpr>(Value.Base) &&
305 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000306}
307
308static bool IsWeakLValue(const LValue &Value) {
309 const ValueDecl *Decl = GetLValueBaseDecl(Value);
310 if (!Decl)
311 return false;
312
313 return Decl->hasAttr<WeakAttr>() ||
314 Decl->hasAttr<WeakRefAttr>() ||
315 Decl->isWeakImported();
316}
317
Richard Smith11562c52011-10-28 17:51:58 +0000318static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000319 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000320
John McCalleb3e4f32010-05-07 21:34:32 +0000321 // A null base expression indicates a null pointer. These are always
322 // evaluatable, and they are false unless the offset is zero.
323 if (!Base) {
324 Result = !Value.Offset.isZero();
325 return true;
326 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000327
John McCall95007602010-05-10 23:27:23 +0000328 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000329 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000330 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000331
John McCalleb3e4f32010-05-07 21:34:32 +0000332 // We have a non-null base expression. These are generally known to
333 // be true, but if it'a decl-ref to a weak symbol it can be null at
334 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000335 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000336 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000337}
338
Richard Smith0b0a0b62011-10-29 20:57:55 +0000339static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000340 switch (Val.getKind()) {
341 case APValue::Uninitialized:
342 return false;
343 case APValue::Int:
344 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000345 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000346 case APValue::Float:
347 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000348 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000349 case APValue::ComplexInt:
350 Result = Val.getComplexIntReal().getBoolValue() ||
351 Val.getComplexIntImag().getBoolValue();
352 return true;
353 case APValue::ComplexFloat:
354 Result = !Val.getComplexFloatReal().isZero() ||
355 !Val.getComplexFloatImag().isZero();
356 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000357 case APValue::LValue: {
358 LValue PointerResult;
359 PointerResult.setFrom(Val);
360 return EvalPointerValueAsBool(PointerResult, Result);
361 }
Richard Smith11562c52011-10-28 17:51:58 +0000362 case APValue::Vector:
363 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000364 }
365
Richard Smith11562c52011-10-28 17:51:58 +0000366 llvm_unreachable("unknown APValue kind");
367}
368
369static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
370 EvalInfo &Info) {
371 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000372 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000373 if (!Evaluate(Val, Info, E))
374 return false;
375 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000376}
377
Mike Stump11289f42009-09-09 15:08:12 +0000378static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000379 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000380 unsigned DestWidth = Ctx.getIntWidth(DestType);
381 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000382 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000383
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000384 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000385 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000386 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000387 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
388 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000389}
390
Mike Stump11289f42009-09-09 15:08:12 +0000391static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000392 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000393 bool ignored;
394 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000395 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000396 APFloat::rmNearestTiesToEven, &ignored);
397 return Result;
398}
399
Mike Stump11289f42009-09-09 15:08:12 +0000400static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000401 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000402 unsigned DestWidth = Ctx.getIntWidth(DestType);
403 APSInt Result = Value;
404 // Figure out if this is a truncate, extend or noop cast.
405 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000406 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000407 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000408 return Result;
409}
410
Mike Stump11289f42009-09-09 15:08:12 +0000411static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000412 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000413
414 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
415 Result.convertFromAPInt(Value, Value.isSigned(),
416 APFloat::rmNearestTiesToEven);
417 return Result;
418}
419
Richard Smith27908702011-10-24 17:54:18 +0000420/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000421static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
422 unsigned CallIndex, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000423 // If this is a parameter to an active constexpr function call, perform
424 // argument substitution.
425 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000426 if (const CCValue *ArgValue =
427 Info.getCallValue(CallIndex, PVD->getFunctionScopeIndex())) {
428 Result = *ArgValue;
429 return true;
430 }
431 return false;
Richard Smith254a73d2011-10-28 22:34:42 +0000432 }
Richard Smith27908702011-10-24 17:54:18 +0000433
434 const Expr *Init = VD->getAnyInitializer();
435 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000436 return false;
Richard Smith27908702011-10-24 17:54:18 +0000437
Richard Smith0b0a0b62011-10-29 20:57:55 +0000438 if (APValue *V = VD->getEvaluatedValue()) {
439 Result = CCValue(*V, CCValue::NoCallIndex);
440 return !Result.isUninit();
441 }
Richard Smith27908702011-10-24 17:54:18 +0000442
443 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000444 return false;
Richard Smith27908702011-10-24 17:54:18 +0000445
446 VD->setEvaluatingValue();
447
Richard Smith0b0a0b62011-10-29 20:57:55 +0000448 Expr::EvalStatus EStatus;
449 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000450 // FIXME: The caller will need to know whether the value was a constant
451 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000452 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000453 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000454 return false;
455 }
Richard Smith27908702011-10-24 17:54:18 +0000456
Richard Smith0b0a0b62011-10-29 20:57:55 +0000457 VD->setEvaluatedValue(Result);
458 return true;
Richard Smith27908702011-10-24 17:54:18 +0000459}
460
Richard Smith11562c52011-10-28 17:51:58 +0000461static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000462 Qualifiers Quals = T.getQualifiers();
463 return Quals.hasConst() && !Quals.hasVolatile();
464}
465
Richard Smith11562c52011-10-28 17:51:58 +0000466bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000467 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000468 const Expr *Base = LVal.Base;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000469 unsigned CallIndex = LVal.CallIndex;
Richard Smith11562c52011-10-28 17:51:58 +0000470
471 // FIXME: Indirection through a null pointer deserves a diagnostic.
472 if (!Base)
473 return false;
474
475 // FIXME: Support accessing subobjects of objects of literal types. A simple
476 // byte offset is insufficient for C++11 semantics: we need to know how the
477 // reference was formed (which union member was named, for instance).
478 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
479 if (!LVal.Offset.isZero())
480 return false;
481
Richard Smith8b3497e2011-10-31 01:37:14 +0000482 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000483 // If the lvalue has been cast to some other type, don't try to read it.
484 // FIXME: Could simulate a bitcast here.
Richard Smith8b3497e2011-10-31 01:37:14 +0000485 if (!Info.Ctx.hasSameUnqualifiedType(Type, D->getType()))
486 return 0;
Richard Smith11562c52011-10-28 17:51:58 +0000487
Richard Smith11562c52011-10-28 17:51:58 +0000488 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
489 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000490 // expressions are constant expressions too. Inside constexpr functions,
491 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000492 // In C, such things can also be folded, although they are not ICEs.
493 //
Richard Smith254a73d2011-10-28 22:34:42 +0000494 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
495 // interpretation of C++11 suggests that volatile parameters are OK if
496 // they're never read (there's no prohibition against constructing volatile
497 // objects in constant expressions), but lvalue-to-rvalue conversions on
498 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000499 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000500 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith35a1f852011-10-29 21:53:17 +0000501 !Type->isLiteralType() ||
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000502 !EvaluateVarDeclInit(Info, VD, CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000503 return false;
504
Richard Smith0b0a0b62011-10-29 20:57:55 +0000505 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000506 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000507
508 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
509 // conversion. This happens when the declaration and the lvalue should be
510 // considered synonymous, for instance when initializing an array of char
511 // from a string literal. Continue as if the initializer lvalue was the
512 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000513 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000514 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000515 Base = RVal.getLValueBase();
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000516 CallIndex = RVal.getLValueCallIndex();
Richard Smith11562c52011-10-28 17:51:58 +0000517 }
518
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000519 // If this is an lvalue expression with a nontrivial initializer, grab the
520 // value from the relevant stack frame, if the object is still in scope.
521 if (isa<MaterializeTemporaryExpr>(Base)) {
522 if (CallStackFrame *Frame = Info.getStackFrame(CallIndex)) {
523 RVal = Frame->Temporaries[Base];
524 return true;
525 }
526 return false;
527 }
Richard Smith11562c52011-10-28 17:51:58 +0000528
529 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
530 // initializer until now for such expressions. Such an expression can't be
531 // an ICE in C, so this only matters for fold.
532 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
533 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
534 return Evaluate(RVal, Info, CLE->getInitializer());
535 }
536
537 return false;
538}
539
Mike Stump876387b2009-10-27 22:09:17 +0000540namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000541enum EvalStmtResult {
542 /// Evaluation failed.
543 ESR_Failed,
544 /// Hit a 'return' statement.
545 ESR_Returned,
546 /// Evaluation succeeded.
547 ESR_Succeeded
548};
549}
550
551// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000552static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000553 const Stmt *S) {
554 switch (S->getStmtClass()) {
555 default:
556 return ESR_Failed;
557
558 case Stmt::NullStmtClass:
559 case Stmt::DeclStmtClass:
560 return ESR_Succeeded;
561
562 case Stmt::ReturnStmtClass:
563 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
564 return ESR_Returned;
565 return ESR_Failed;
566
567 case Stmt::CompoundStmtClass: {
568 const CompoundStmt *CS = cast<CompoundStmt>(S);
569 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
570 BE = CS->body_end(); BI != BE; ++BI) {
571 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
572 if (ESR != ESR_Succeeded)
573 return ESR;
574 }
575 return ESR_Succeeded;
576 }
577 }
578}
579
580/// Evaluate a function call.
581static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000582 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000583 // FIXME: Implement a proper call limit, along with a command-line flag.
584 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
585 return false;
586
Richard Smith0b0a0b62011-10-29 20:57:55 +0000587 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000588 // FIXME: Deal with default arguments and 'this'.
589 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
590 I != E; ++I)
591 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
592 return false;
593
594 CallStackFrame Frame(Info, ArgValues.data());
595 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
596}
597
598namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000599class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000600 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000601 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000602public:
603
Richard Smith725810a2011-10-16 21:26:27 +0000604 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000605
606 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000607 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000608 return true;
609 }
610
Peter Collingbournee9200682011-05-13 03:29:01 +0000611 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
612 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000613 return Visit(E->getResultExpr());
614 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000615 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000616 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000617 return true;
618 return false;
619 }
John McCall31168b02011-06-15 23:02:42 +0000620 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000621 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000622 return true;
623 return false;
624 }
625 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000626 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000627 return true;
628 return false;
629 }
630
Mike Stump876387b2009-10-27 22:09:17 +0000631 // We don't want to evaluate BlockExprs multiple times, as they generate
632 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000633 bool VisitBlockExpr(const BlockExpr *E) { return true; }
634 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
635 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000636 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000637 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
638 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
639 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
640 bool VisitStringLiteral(const StringLiteral *E) { return false; }
641 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
642 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000643 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000644 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000645 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000646 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000647 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000648 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
649 bool VisitBinAssign(const BinaryOperator *E) { return true; }
650 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
651 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000652 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000653 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
654 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
655 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
656 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
657 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000658 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000659 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000660 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000661 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000662 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000663
664 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000665 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000666 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
667 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000668 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000669 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000670 return false;
671 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000672
Peter Collingbournee9200682011-05-13 03:29:01 +0000673 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000674};
675
John McCallc07a0c72011-02-17 10:25:35 +0000676class OpaqueValueEvaluation {
677 EvalInfo &info;
678 OpaqueValueExpr *opaqueValue;
679
680public:
681 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
682 Expr *value)
683 : info(info), opaqueValue(opaqueValue) {
684
685 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000686 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000687 this->opaqueValue = 0;
688 return;
689 }
John McCallc07a0c72011-02-17 10:25:35 +0000690 }
691
692 bool hasError() const { return opaqueValue == 0; }
693
694 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000695 // FIXME: This will not work for recursive constexpr functions using opaque
696 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000697 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
698 }
699};
700
Mike Stump876387b2009-10-27 22:09:17 +0000701} // end anonymous namespace
702
Eli Friedman9a156e52008-11-12 09:44:48 +0000703//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000704// Generic Evaluation
705//===----------------------------------------------------------------------===//
706namespace {
707
708template <class Derived, typename RetTy=void>
709class ExprEvaluatorBase
710 : public ConstStmtVisitor<Derived, RetTy> {
711private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000712 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000713 return static_cast<Derived*>(this)->Success(V, E);
714 }
715 RetTy DerivedError(const Expr *E) {
716 return static_cast<Derived*>(this)->Error(E);
717 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000718 RetTy DerivedValueInitialization(const Expr *E) {
719 return static_cast<Derived*>(this)->ValueInitialization(E);
720 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000721
722protected:
723 EvalInfo &Info;
724 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
725 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
726
Richard Smith4ce706a2011-10-11 21:43:33 +0000727 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
728
Peter Collingbournee9200682011-05-13 03:29:01 +0000729public:
730 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
731
732 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000733 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000734 }
735 RetTy VisitExpr(const Expr *E) {
736 return DerivedError(E);
737 }
738
739 RetTy VisitParenExpr(const ParenExpr *E)
740 { return StmtVisitorTy::Visit(E->getSubExpr()); }
741 RetTy VisitUnaryExtension(const UnaryOperator *E)
742 { return StmtVisitorTy::Visit(E->getSubExpr()); }
743 RetTy VisitUnaryPlus(const UnaryOperator *E)
744 { return StmtVisitorTy::Visit(E->getSubExpr()); }
745 RetTy VisitChooseExpr(const ChooseExpr *E)
746 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
747 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
748 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000749 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
750 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000751
752 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
753 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
754 if (opaque.hasError())
755 return DerivedError(E);
756
757 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000758 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000759 return DerivedError(E);
760
761 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
762 }
763
764 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
765 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000766 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000767 return DerivedError(E);
768
Richard Smith11562c52011-10-28 17:51:58 +0000769 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000770 return StmtVisitorTy::Visit(EvalExpr);
771 }
772
773 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000774 const CCValue *Value = Info.getOpaqueValue(E);
775 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000776 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
777 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000778 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000779 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000780
Richard Smith254a73d2011-10-28 22:34:42 +0000781 RetTy VisitCallExpr(const CallExpr *E) {
782 const Expr *Callee = E->getCallee();
783 QualType CalleeType = Callee->getType();
784
785 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
786 // non-static member function.
787 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
788 return DerivedError(E);
789
790 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
791 return DerivedError(E);
792
Richard Smith0b0a0b62011-10-29 20:57:55 +0000793 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000794 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
795 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
796 return DerivedError(Callee);
797
798 const FunctionDecl *FD = 0;
799 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
800 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
801 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
802 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
803 if (!FD)
804 return DerivedError(Callee);
805
806 // Don't call function pointers which have been cast to some other type.
807 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
808 return DerivedError(E);
809
810 const FunctionDecl *Definition;
811 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000812 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000813 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
814
815 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
816 HandleFunctionCall(Args, Body, Info, Result))
817 return DerivedSuccess(Result, E);
818
819 return DerivedError(E);
820 }
821
Richard Smith11562c52011-10-28 17:51:58 +0000822 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
823 return StmtVisitorTy::Visit(E->getInitializer());
824 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000825 RetTy VisitInitListExpr(const InitListExpr *E) {
826 if (Info.getLangOpts().CPlusPlus0x) {
827 if (E->getNumInits() == 0)
828 return DerivedValueInitialization(E);
829 if (E->getNumInits() == 1)
830 return StmtVisitorTy::Visit(E->getInit(0));
831 }
832 return DerivedError(E);
833 }
834 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
835 return DerivedValueInitialization(E);
836 }
837 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
838 return DerivedValueInitialization(E);
839 }
840
Richard Smith11562c52011-10-28 17:51:58 +0000841 RetTy VisitCastExpr(const CastExpr *E) {
842 switch (E->getCastKind()) {
843 default:
844 break;
845
846 case CK_NoOp:
847 return StmtVisitorTy::Visit(E->getSubExpr());
848
849 case CK_LValueToRValue: {
850 LValue LVal;
851 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000852 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000853 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
854 return DerivedSuccess(RVal, E);
855 }
856 break;
857 }
858 }
859
860 return DerivedError(E);
861 }
862
Richard Smith4a678122011-10-24 18:44:57 +0000863 /// Visit a value which is evaluated, but whose value is ignored.
864 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000865 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000866 if (!Evaluate(Scratch, Info, E))
867 Info.EvalStatus.HasSideEffects = true;
868 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000869};
870
871}
872
873//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000874// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000875//
876// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
877// function designators (in C), decl references to void objects (in C), and
878// temporaries (if building with -Wno-address-of-temporary).
879//
880// LValue evaluation produces values comprising a base expression of one of the
881// following types:
882// * DeclRefExpr
883// * MemberExpr for a static member
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000884// * MaterializeTemporaryExpr
Richard Smith11562c52011-10-28 17:51:58 +0000885// * CompoundLiteralExpr in C
886// * StringLiteral
887// * PredefinedExpr
888// * ObjCEncodeExpr
889// * AddrLabelExpr
890// * BlockExpr
891// * CallExpr for a MakeStringConstant builtin
892// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000893//===----------------------------------------------------------------------===//
894namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000895class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000896 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000897 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000898 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000899
Peter Collingbournee9200682011-05-13 03:29:01 +0000900 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000901 Result.Base = E;
902 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000903 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000904 return true;
905 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000906public:
Mike Stump11289f42009-09-09 15:08:12 +0000907
John McCall45d55e42010-05-07 21:00:08 +0000908 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000909 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000910
Richard Smith0b0a0b62011-10-29 20:57:55 +0000911 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000912 Result.setFrom(V);
913 return true;
914 }
915 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000916 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000917 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000918
Richard Smith11562c52011-10-28 17:51:58 +0000919 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
920
Peter Collingbournee9200682011-05-13 03:29:01 +0000921 bool VisitDeclRefExpr(const DeclRefExpr *E);
922 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000923 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000924 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
925 bool VisitMemberExpr(const MemberExpr *E);
926 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
927 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
928 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
929 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000930
Peter Collingbournee9200682011-05-13 03:29:01 +0000931 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000932 switch (E->getCastKind()) {
933 default:
Richard Smith11562c52011-10-28 17:51:58 +0000934 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000935
Eli Friedmance3e02a2011-10-11 00:13:24 +0000936 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000937 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000938
Richard Smith11562c52011-10-28 17:51:58 +0000939 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
940 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000941 }
942 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000943
Eli Friedman449fe542009-03-23 04:56:01 +0000944 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000945
Eli Friedman9a156e52008-11-12 09:44:48 +0000946};
947} // end anonymous namespace
948
Richard Smith11562c52011-10-28 17:51:58 +0000949/// Evaluate an expression as an lvalue. This can be legitimately called on
950/// expressions which are not glvalues, in a few cases:
951/// * function designators in C,
952/// * "extern void" objects,
953/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000954static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000955 assert((E->isGLValue() || E->getType()->isFunctionType() ||
956 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
957 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000958 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000959}
960
Peter Collingbournee9200682011-05-13 03:29:01 +0000961bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000962 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000963 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000964 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
965 return VisitVarDecl(E, VD);
966 return Error(E);
967}
Richard Smith733237d2011-10-24 23:14:33 +0000968
Richard Smith11562c52011-10-28 17:51:58 +0000969bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
970 if (!VD->getType()->isReferenceType())
971 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000972
Richard Smith0b0a0b62011-10-29 20:57:55 +0000973 CCValue V;
974 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
975 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000976
977 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000978}
979
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000980bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
981 const MaterializeTemporaryExpr *E) {
982 if (!Evaluate(Info.CurrentCall->Temporaries[E], Info, E->GetTemporaryExpr()))
983 return false;
984 return Success(E);
985}
986
Peter Collingbournee9200682011-05-13 03:29:01 +0000987bool
988LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000989 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
990 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
991 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000992 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000993}
994
Peter Collingbournee9200682011-05-13 03:29:01 +0000995bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000996 // Handle static data members.
997 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
998 VisitIgnoredValue(E->getBase());
999 return VisitVarDecl(E, VD);
1000 }
1001
Richard Smith254a73d2011-10-28 22:34:42 +00001002 // Handle static member functions.
1003 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1004 if (MD->isStatic()) {
1005 VisitIgnoredValue(E->getBase());
1006 return Success(E);
1007 }
1008 }
1009
Eli Friedman9a156e52008-11-12 09:44:48 +00001010 QualType Ty;
1011 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001012 if (!EvaluatePointer(E->getBase(), Result, Info))
1013 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001014 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001015 } else {
John McCall45d55e42010-05-07 21:00:08 +00001016 if (!Visit(E->getBase()))
1017 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001018 Ty = E->getBase()->getType();
1019 }
1020
Peter Collingbournee9200682011-05-13 03:29:01 +00001021 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001022 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001023
Peter Collingbournee9200682011-05-13 03:29:01 +00001024 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001025 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001026 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001027
1028 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001029 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001030
Eli Friedmana3c122d2011-07-07 01:54:01 +00001031 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001032 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +00001033 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001034}
1035
Peter Collingbournee9200682011-05-13 03:29:01 +00001036bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001037 // FIXME: Deal with vectors as array subscript bases.
1038 if (E->getBase()->getType()->isVectorType())
1039 return false;
1040
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001041 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001042 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001044 APSInt Index;
1045 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001046 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001047
Ken Dyck40775002010-01-11 17:06:35 +00001048 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001049 Result.Offset += Index.getSExtValue() * ElementSize;
1050 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001051}
Eli Friedman9a156e52008-11-12 09:44:48 +00001052
Peter Collingbournee9200682011-05-13 03:29:01 +00001053bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001054 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001055}
1056
Eli Friedman9a156e52008-11-12 09:44:48 +00001057//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001058// Pointer Evaluation
1059//===----------------------------------------------------------------------===//
1060
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001061namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001062class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001063 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001064 LValue &Result;
1065
Peter Collingbournee9200682011-05-13 03:29:01 +00001066 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001067 Result.Base = E;
1068 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001069 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001070 return true;
1071 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001072public:
Mike Stump11289f42009-09-09 15:08:12 +00001073
John McCall45d55e42010-05-07 21:00:08 +00001074 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001075 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001076
Richard Smith0b0a0b62011-10-29 20:57:55 +00001077 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001078 Result.setFrom(V);
1079 return true;
1080 }
1081 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001082 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001083 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001084 bool ValueInitialization(const Expr *E) {
1085 return Success((Expr*)0);
1086 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001087
John McCall45d55e42010-05-07 21:00:08 +00001088 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001089 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001090 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001091 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001092 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001093 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001094 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001095 bool VisitCallExpr(const CallExpr *E);
1096 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001097 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001098 return Success(E);
1099 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001100 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001101 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001102 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001103
Eli Friedman449fe542009-03-23 04:56:01 +00001104 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001105};
Chris Lattner05706e882008-07-11 18:11:29 +00001106} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001107
John McCall45d55e42010-05-07 21:00:08 +00001108static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001109 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001110 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001111}
1112
John McCall45d55e42010-05-07 21:00:08 +00001113bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001114 if (E->getOpcode() != BO_Add &&
1115 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001116 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chris Lattner05706e882008-07-11 18:11:29 +00001118 const Expr *PExp = E->getLHS();
1119 const Expr *IExp = E->getRHS();
1120 if (IExp->getType()->isPointerType())
1121 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001122
John McCall45d55e42010-05-07 21:00:08 +00001123 if (!EvaluatePointer(PExp, Result, Info))
1124 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001125
John McCall45d55e42010-05-07 21:00:08 +00001126 llvm::APSInt Offset;
1127 if (!EvaluateInteger(IExp, Offset, Info))
1128 return false;
1129 int64_t AdditionalOffset
1130 = Offset.isSigned() ? Offset.getSExtValue()
1131 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001132
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001133 // Compute the new offset in the appropriate width.
1134
1135 QualType PointeeType =
1136 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001137 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001138
Anders Carlssonef56fba2009-02-19 04:55:58 +00001139 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1140 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001141 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001142 else
John McCall45d55e42010-05-07 21:00:08 +00001143 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001144
John McCalle3027922010-08-25 11:45:40 +00001145 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001146 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001147 else
John McCall45d55e42010-05-07 21:00:08 +00001148 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001149
John McCall45d55e42010-05-07 21:00:08 +00001150 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001151}
Eli Friedman9a156e52008-11-12 09:44:48 +00001152
John McCall45d55e42010-05-07 21:00:08 +00001153bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1154 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001155}
Mike Stump11289f42009-09-09 15:08:12 +00001156
Chris Lattner05706e882008-07-11 18:11:29 +00001157
Peter Collingbournee9200682011-05-13 03:29:01 +00001158bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1159 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001160
Eli Friedman847a2bc2009-12-27 05:43:15 +00001161 switch (E->getCastKind()) {
1162 default:
1163 break;
1164
John McCalle3027922010-08-25 11:45:40 +00001165 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001166 case CK_CPointerToObjCPointerCast:
1167 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001168 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001169 return Visit(SubExpr);
1170
Anders Carlsson18275092010-10-31 20:41:46 +00001171 case CK_DerivedToBase:
1172 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001173 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001174 return false;
1175
1176 // Now figure out the necessary offset to add to the baseLV to get from
1177 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001178 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001179
1180 QualType Ty = E->getSubExpr()->getType();
1181 const CXXRecordDecl *DerivedDecl =
1182 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1183
1184 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1185 PathE = E->path_end(); PathI != PathE; ++PathI) {
1186 const CXXBaseSpecifier *Base = *PathI;
1187
1188 // FIXME: If the base is virtual, we'd need to determine the type of the
1189 // most derived class and we don't support that right now.
1190 if (Base->isVirtual())
1191 return false;
1192
1193 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1194 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1195
Richard Smith0b0a0b62011-10-29 20:57:55 +00001196 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001197 DerivedDecl = BaseDecl;
1198 }
1199
Anders Carlsson18275092010-10-31 20:41:46 +00001200 return true;
1201 }
1202
Richard Smith0b0a0b62011-10-29 20:57:55 +00001203 case CK_NullToPointer:
1204 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001205
John McCalle3027922010-08-25 11:45:40 +00001206 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001207 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001208 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001209 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001210
John McCall45d55e42010-05-07 21:00:08 +00001211 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001212 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1213 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001214 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001215 Result.Offset = CharUnits::fromQuantity(N);
1216 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001217 return true;
1218 } else {
1219 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001220 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001221 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001222 }
1223 }
John McCalle3027922010-08-25 11:45:40 +00001224 case CK_ArrayToPointerDecay:
1225 case CK_FunctionToPointerDecay:
Richard Smithfdc6a592011-10-31 20:20:33 +00001226 if (SubExpr->isGLValue() || SubExpr->getType()->isFunctionType())
1227 return EvaluateLValue(SubExpr, Result, Info);
1228 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001229 }
1230
Richard Smith11562c52011-10-28 17:51:58 +00001231 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001232}
Chris Lattner05706e882008-07-11 18:11:29 +00001233
Peter Collingbournee9200682011-05-13 03:29:01 +00001234bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001235 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001236 Builtin::BI__builtin___CFStringMakeConstantString ||
1237 E->isBuiltinCall(Info.Ctx) ==
1238 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001239 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001240
Peter Collingbournee9200682011-05-13 03:29:01 +00001241 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001242}
Chris Lattner05706e882008-07-11 18:11:29 +00001243
1244//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001245// Vector Evaluation
1246//===----------------------------------------------------------------------===//
1247
1248namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001249 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001250 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1251 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001252 public:
Mike Stump11289f42009-09-09 15:08:12 +00001253
Richard Smith2d406342011-10-22 21:10:00 +00001254 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1255 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001256
Richard Smith2d406342011-10-22 21:10:00 +00001257 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1258 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1259 // FIXME: remove this APValue copy.
1260 Result = APValue(V.data(), V.size());
1261 return true;
1262 }
1263 bool Success(const APValue &V, const Expr *E) {
1264 Result = V;
1265 return true;
1266 }
1267 bool Error(const Expr *E) { return false; }
1268 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Richard Smith2d406342011-10-22 21:10:00 +00001270 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001271 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001272 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001273 bool VisitInitListExpr(const InitListExpr *E);
1274 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001275 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001276 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001277 // shufflevector, ExtVectorElementExpr
1278 // (Note that these require implementing conversions
1279 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001280 };
1281} // end anonymous namespace
1282
1283static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001284 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001285 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001286}
1287
Richard Smith2d406342011-10-22 21:10:00 +00001288bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1289 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001290 QualType EltTy = VTy->getElementType();
1291 unsigned NElts = VTy->getNumElements();
1292 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001293
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001294 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001295 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001296
Eli Friedmanc757de22011-03-25 00:43:55 +00001297 switch (E->getCastKind()) {
1298 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001299 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001300 if (SETy->isIntegerType()) {
1301 APSInt IntResult;
1302 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001303 return Error(E);
1304 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001305 } else if (SETy->isRealFloatingType()) {
1306 APFloat F(0.0);
1307 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001308 return Error(E);
1309 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001310 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001311 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001312 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001313
1314 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001315 SmallVector<APValue, 4> Elts(NElts, Val);
1316 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001317 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001318 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001319 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001320 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001321 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001322
Eli Friedmanc757de22011-03-25 00:43:55 +00001323 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001324 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Eli Friedmanc757de22011-03-25 00:43:55 +00001326 APSInt Init;
1327 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001328 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001329
Eli Friedmanc757de22011-03-25 00:43:55 +00001330 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1331 "Vectors must be composed of ints or floats");
1332
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001333 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001334 for (unsigned i = 0; i != NElts; ++i) {
1335 APSInt Tmp = Init.extOrTrunc(EltWidth);
1336
1337 if (EltTy->isIntegerType())
1338 Elts.push_back(APValue(Tmp));
1339 else
1340 Elts.push_back(APValue(APFloat(Tmp)));
1341
1342 Init >>= EltWidth;
1343 }
Richard Smith2d406342011-10-22 21:10:00 +00001344 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001345 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001346 default:
Richard Smith11562c52011-10-28 17:51:58 +00001347 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001348 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001349}
1350
Richard Smith2d406342011-10-22 21:10:00 +00001351bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001352VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001353 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001354 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001355 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001356
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001357 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001358 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001359
John McCall875679e2010-06-11 17:54:15 +00001360 // If a vector is initialized with a single element, that value
1361 // becomes every element of the vector, not just the first.
1362 // This is the behavior described in the IBM AltiVec documentation.
1363 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001364
1365 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001366 // vector (OpenCL 6.1.6).
1367 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001368 return Visit(E->getInit(0));
1369
John McCall875679e2010-06-11 17:54:15 +00001370 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001371 if (EltTy->isIntegerType()) {
1372 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001373 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001374 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001375 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001376 } else {
1377 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001378 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001379 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001380 InitValue = APValue(f);
1381 }
1382 for (unsigned i = 0; i < NumElements; i++) {
1383 Elements.push_back(InitValue);
1384 }
1385 } else {
1386 for (unsigned i = 0; i < NumElements; i++) {
1387 if (EltTy->isIntegerType()) {
1388 llvm::APSInt sInt(32);
1389 if (i < NumInits) {
1390 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001391 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001392 } else {
1393 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1394 }
1395 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001396 } else {
John McCall875679e2010-06-11 17:54:15 +00001397 llvm::APFloat f(0.0);
1398 if (i < NumInits) {
1399 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001400 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001401 } else {
1402 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1403 }
1404 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001405 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001406 }
1407 }
Richard Smith2d406342011-10-22 21:10:00 +00001408 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001409}
1410
Richard Smith2d406342011-10-22 21:10:00 +00001411bool
1412VectorExprEvaluator::ValueInitialization(const Expr *E) {
1413 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001414 QualType EltTy = VT->getElementType();
1415 APValue ZeroElement;
1416 if (EltTy->isIntegerType())
1417 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1418 else
1419 ZeroElement =
1420 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1421
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001422 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001423 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001424}
1425
Richard Smith2d406342011-10-22 21:10:00 +00001426bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001427 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001428 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001429}
1430
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001431//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001432// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001433//
1434// As a GNU extension, we support casting pointers to sufficiently-wide integer
1435// types and back in constant folding. Integer values are thus represented
1436// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001437//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001438
1439namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001440class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001441 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001442 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001443public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001444 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001445 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001446
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001447 bool Success(const llvm::APSInt &SI, const Expr *E) {
1448 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001449 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001450 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001451 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001452 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001453 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001454 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001455 return true;
1456 }
1457
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001458 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001459 assert(E->getType()->isIntegralOrEnumerationType() &&
1460 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001461 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001462 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001463 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001464 Result.getInt().setIsUnsigned(
1465 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001466 return true;
1467 }
1468
1469 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001470 assert(E->getType()->isIntegralOrEnumerationType() &&
1471 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001472 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001473 return true;
1474 }
1475
Ken Dyckdbc01912011-03-11 02:13:43 +00001476 bool Success(CharUnits Size, const Expr *E) {
1477 return Success(Size.getQuantity(), E);
1478 }
1479
1480
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001481 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001482 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001483 if (Info.EvalStatus.Diag == 0) {
1484 Info.EvalStatus.DiagLoc = L;
1485 Info.EvalStatus.Diag = D;
1486 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001487 }
Chris Lattner99415702008-07-12 00:14:42 +00001488 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001489 }
Mike Stump11289f42009-09-09 15:08:12 +00001490
Richard Smith0b0a0b62011-10-29 20:57:55 +00001491 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001492 if (V.isLValue()) {
1493 Result = V;
1494 return true;
1495 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001496 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001497 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001498 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001499 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Richard Smith4ce706a2011-10-11 21:43:33 +00001502 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1503
Peter Collingbournee9200682011-05-13 03:29:01 +00001504 //===--------------------------------------------------------------------===//
1505 // Visitor Methods
1506 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001507
Chris Lattner7174bf32008-07-12 00:38:25 +00001508 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001509 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001510 }
1511 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001512 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001513 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001514
1515 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1516 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001517 if (CheckReferencedDecl(E, E->getDecl()))
1518 return true;
1519
1520 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001521 }
1522 bool VisitMemberExpr(const MemberExpr *E) {
1523 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001524 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001525 return true;
1526 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001527
1528 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001529 }
1530
Peter Collingbournee9200682011-05-13 03:29:01 +00001531 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001532 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001533 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001534 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001535
Peter Collingbournee9200682011-05-13 03:29:01 +00001536 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001537 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001538
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001539 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001540 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Richard Smith4ce706a2011-10-11 21:43:33 +00001543 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001544 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001545 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001546 }
1547
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001548 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001549 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001550 }
1551
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001552 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1553 return Success(E->getValue(), E);
1554 }
1555
John Wiegley6242b6a2011-04-28 00:16:57 +00001556 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1557 return Success(E->getValue(), E);
1558 }
1559
John Wiegleyf9f65842011-04-25 06:54:41 +00001560 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1561 return Success(E->getValue(), E);
1562 }
1563
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001564 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001565 bool VisitUnaryImag(const UnaryOperator *E);
1566
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001567 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001568 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001569
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001570private:
Ken Dyck160146e2010-01-27 17:10:57 +00001571 CharUnits GetAlignOfExpr(const Expr *E);
1572 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001573 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001574 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001575 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001576};
Chris Lattner05706e882008-07-11 18:11:29 +00001577} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001578
Richard Smith11562c52011-10-28 17:51:58 +00001579/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1580/// produce either the integer value or a pointer.
1581///
1582/// GCC has a heinous extension which folds casts between pointer types and
1583/// pointer-sized integral types. We support this by allowing the evaluation of
1584/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1585/// Some simple arithmetic on such values is supported (they are treated much
1586/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001587static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1588 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001589 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001590 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001591}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001592
Daniel Dunbarce399542009-02-20 18:22:23 +00001593static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001594 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001595 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1596 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001597 Result = Val.getInt();
1598 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001599}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001600
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001601bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001602 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001603 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001604 // Check for signedness/width mismatches between E type and ECD value.
1605 bool SameSign = (ECD->getInitVal().isSigned()
1606 == E->getType()->isSignedIntegerOrEnumerationType());
1607 bool SameWidth = (ECD->getInitVal().getBitWidth()
1608 == Info.Ctx.getIntWidth(E->getType()));
1609 if (SameSign && SameWidth)
1610 return Success(ECD->getInitVal(), E);
1611 else {
1612 // Get rid of mismatch (otherwise Success assertions will fail)
1613 // by computing a new value matching the type of E.
1614 llvm::APSInt Val = ECD->getInitVal();
1615 if (!SameSign)
1616 Val.setIsSigned(!ECD->getInitVal().isSigned());
1617 if (!SameWidth)
1618 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1619 return Success(Val, E);
1620 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001621 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001622 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001623}
1624
Chris Lattner86ee2862008-10-06 06:40:35 +00001625/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1626/// as GCC.
1627static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1628 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001629 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001630 enum gcc_type_class {
1631 no_type_class = -1,
1632 void_type_class, integer_type_class, char_type_class,
1633 enumeral_type_class, boolean_type_class,
1634 pointer_type_class, reference_type_class, offset_type_class,
1635 real_type_class, complex_type_class,
1636 function_type_class, method_type_class,
1637 record_type_class, union_type_class,
1638 array_type_class, string_type_class,
1639 lang_type_class
1640 };
Mike Stump11289f42009-09-09 15:08:12 +00001641
1642 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001643 // ideal, however it is what gcc does.
1644 if (E->getNumArgs() == 0)
1645 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Chris Lattner86ee2862008-10-06 06:40:35 +00001647 QualType ArgTy = E->getArg(0)->getType();
1648 if (ArgTy->isVoidType())
1649 return void_type_class;
1650 else if (ArgTy->isEnumeralType())
1651 return enumeral_type_class;
1652 else if (ArgTy->isBooleanType())
1653 return boolean_type_class;
1654 else if (ArgTy->isCharType())
1655 return string_type_class; // gcc doesn't appear to use char_type_class
1656 else if (ArgTy->isIntegerType())
1657 return integer_type_class;
1658 else if (ArgTy->isPointerType())
1659 return pointer_type_class;
1660 else if (ArgTy->isReferenceType())
1661 return reference_type_class;
1662 else if (ArgTy->isRealType())
1663 return real_type_class;
1664 else if (ArgTy->isComplexType())
1665 return complex_type_class;
1666 else if (ArgTy->isFunctionType())
1667 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001668 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001669 return record_type_class;
1670 else if (ArgTy->isUnionType())
1671 return union_type_class;
1672 else if (ArgTy->isArrayType())
1673 return array_type_class;
1674 else if (ArgTy->isUnionType())
1675 return union_type_class;
1676 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001677 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001678 return -1;
1679}
1680
John McCall95007602010-05-10 23:27:23 +00001681/// Retrieves the "underlying object type" of the given expression,
1682/// as used by __builtin_object_size.
1683QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1685 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1686 return VD->getType();
1687 } else if (isa<CompoundLiteralExpr>(E)) {
1688 return E->getType();
1689 }
1690
1691 return QualType();
1692}
1693
Peter Collingbournee9200682011-05-13 03:29:01 +00001694bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001695 // TODO: Perhaps we should let LLVM lower this?
1696 LValue Base;
1697 if (!EvaluatePointer(E->getArg(0), Base, Info))
1698 return false;
1699
1700 // If we can prove the base is null, lower to zero now.
1701 const Expr *LVBase = Base.getLValueBase();
1702 if (!LVBase) return Success(0, E);
1703
1704 QualType T = GetObjectType(LVBase);
1705 if (T.isNull() ||
1706 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001707 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001708 T->isVariablyModifiedType() ||
1709 T->isDependentType())
1710 return false;
1711
1712 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1713 CharUnits Offset = Base.getLValueOffset();
1714
1715 if (!Offset.isNegative() && Offset <= Size)
1716 Size -= Offset;
1717 else
1718 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001719 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001720}
1721
Peter Collingbournee9200682011-05-13 03:29:01 +00001722bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001723 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001724 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001725 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001726
1727 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001728 if (TryEvaluateBuiltinObjectSize(E))
1729 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001730
Eric Christopher99469702010-01-19 22:58:35 +00001731 // If evaluating the argument has side-effects we can't determine
1732 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001733 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001734 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001735 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001736 return Success(0, E);
1737 }
Mike Stump876387b2009-10-27 22:09:17 +00001738
Mike Stump722cedf2009-10-26 18:35:08 +00001739 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1740 }
1741
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001742 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001743 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001744
Anders Carlsson4c76e932008-11-24 04:21:33 +00001745 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001746 // __builtin_constant_p always has one operand: it returns true if that
1747 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001748 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001749
1750 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001751 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001752 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001753 return Success(Operand, E);
1754 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001755
1756 case Builtin::BI__builtin_expect:
1757 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001758
1759 case Builtin::BIstrlen:
1760 case Builtin::BI__builtin_strlen:
1761 // As an extension, we support strlen() and __builtin_strlen() as constant
1762 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001763 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001764 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1765 // The string literal may have embedded null characters. Find the first
1766 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001767 StringRef Str = S->getString();
1768 StringRef::size_type Pos = Str.find(0);
1769 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001770 Str = Str.substr(0, Pos);
1771
1772 return Success(Str.size(), E);
1773 }
1774
1775 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001776
1777 case Builtin::BI__atomic_is_lock_free: {
1778 APSInt SizeVal;
1779 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1780 return false;
1781
1782 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1783 // of two less than the maximum inline atomic width, we know it is
1784 // lock-free. If the size isn't a power of two, or greater than the
1785 // maximum alignment where we promote atomics, we know it is not lock-free
1786 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1787 // the answer can only be determined at runtime; for example, 16-byte
1788 // atomics have lock-free implementations on some, but not all,
1789 // x86-64 processors.
1790
1791 // Check power-of-two.
1792 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1793 if (!Size.isPowerOfTwo())
1794#if 0
1795 // FIXME: Suppress this folding until the ABI for the promotion width
1796 // settles.
1797 return Success(0, E);
1798#else
1799 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1800#endif
1801
1802#if 0
1803 // Check against promotion width.
1804 // FIXME: Suppress this folding until the ABI for the promotion width
1805 // settles.
1806 unsigned PromoteWidthBits =
1807 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1808 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1809 return Success(0, E);
1810#endif
1811
1812 // Check against inlining width.
1813 unsigned InlineWidthBits =
1814 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1815 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1816 return Success(1, E);
1817
1818 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1819 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001820 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001821}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001822
Richard Smith8b3497e2011-10-31 01:37:14 +00001823static bool HasSameBase(const LValue &A, const LValue &B) {
1824 if (!A.getLValueBase())
1825 return !B.getLValueBase();
1826 if (!B.getLValueBase())
1827 return false;
1828
1829 if (A.getLValueBase() != B.getLValueBase()) {
1830 const Decl *ADecl = GetLValueBaseDecl(A);
1831 if (!ADecl)
1832 return false;
1833 const Decl *BDecl = GetLValueBaseDecl(B);
1834 if (ADecl != BDecl)
1835 return false;
1836 }
1837
1838 return IsGlobalLValue(A.getLValueBase()) ||
1839 A.getLValueCallIndex() == B.getLValueCallIndex();
1840}
1841
Chris Lattnere13042c2008-07-11 19:10:17 +00001842bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001843 if (E->isAssignmentOp())
1844 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1845
John McCalle3027922010-08-25 11:45:40 +00001846 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001847 VisitIgnoredValue(E->getLHS());
1848 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001849 }
1850
1851 if (E->isLogicalOp()) {
1852 // These need to be handled specially because the operands aren't
1853 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001854 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001855
Richard Smith11562c52011-10-28 17:51:58 +00001856 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001857 // We were able to evaluate the LHS, see if we can get away with not
1858 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001859 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001860 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001861
Richard Smith11562c52011-10-28 17:51:58 +00001862 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001863 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001864 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001865 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001866 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001867 }
1868 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001869 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001870 // We can't evaluate the LHS; however, sometimes the result
1871 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001872 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1873 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001874 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001875 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001876 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001877
1878 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001879 }
1880 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001881 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001882
Eli Friedman5a332ea2008-11-13 06:09:17 +00001883 return false;
1884 }
1885
Anders Carlssonacc79812008-11-16 07:17:21 +00001886 QualType LHSTy = E->getLHS()->getType();
1887 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001888
1889 if (LHSTy->isAnyComplexType()) {
1890 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001891 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001892
1893 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1894 return false;
1895
1896 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1897 return false;
1898
1899 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001900 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001901 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001902 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001903 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1904
John McCalle3027922010-08-25 11:45:40 +00001905 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001906 return Success((CR_r == APFloat::cmpEqual &&
1907 CR_i == APFloat::cmpEqual), E);
1908 else {
John McCalle3027922010-08-25 11:45:40 +00001909 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001910 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001911 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001912 CR_r == APFloat::cmpLessThan ||
1913 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001914 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001915 CR_i == APFloat::cmpLessThan ||
1916 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001917 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001918 } else {
John McCalle3027922010-08-25 11:45:40 +00001919 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001920 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1921 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1922 else {
John McCalle3027922010-08-25 11:45:40 +00001923 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001924 "Invalid compex comparison.");
1925 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1926 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1927 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001928 }
1929 }
Mike Stump11289f42009-09-09 15:08:12 +00001930
Anders Carlssonacc79812008-11-16 07:17:21 +00001931 if (LHSTy->isRealFloatingType() &&
1932 RHSTy->isRealFloatingType()) {
1933 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001934
Anders Carlssonacc79812008-11-16 07:17:21 +00001935 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1936 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001937
Anders Carlssonacc79812008-11-16 07:17:21 +00001938 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1939 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001940
Anders Carlssonacc79812008-11-16 07:17:21 +00001941 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001942
Anders Carlssonacc79812008-11-16 07:17:21 +00001943 switch (E->getOpcode()) {
1944 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001945 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001946 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001947 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001948 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001949 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001950 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001951 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001952 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001953 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001954 E);
John McCalle3027922010-08-25 11:45:40 +00001955 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001956 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001957 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001958 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001959 || CR == APFloat::cmpLessThan
1960 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001961 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Eli Friedmana38da572009-04-28 19:17:36 +00001964 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00001965 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001966 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001967 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1968 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001969
John McCall45d55e42010-05-07 21:00:08 +00001970 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001971 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1972 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001973
Richard Smith8b3497e2011-10-31 01:37:14 +00001974 // Reject differing bases from the normal codepath; we special-case
1975 // comparisons to null.
1976 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00001977 // Inequalities and subtractions between unrelated pointers have
1978 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00001979 if (!E->isEqualityOp())
1980 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001981 // It's implementation-defined whether distinct literals will have
1982 // distinct addresses. We define it to be unspecified.
1983 if (IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001984 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001985 // We can't tell whether weak symbols will end up pointing to the same
1986 // object.
1987 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001988 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001989 // Pointers with different bases cannot represent the same object.
1990 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00001991 }
Eli Friedman64004332009-03-23 04:38:34 +00001992
John McCalle3027922010-08-25 11:45:40 +00001993 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001994 QualType Type = E->getLHS()->getType();
1995 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001996
Ken Dyck02990832010-01-15 12:37:54 +00001997 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001998 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001999 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002000
Ken Dyck02990832010-01-15 12:37:54 +00002001 CharUnits Diff = LHSValue.getLValueOffset() -
2002 RHSValue.getLValueOffset();
2003 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002004 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002005
2006 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2007 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2008 switch (E->getOpcode()) {
2009 default: llvm_unreachable("missing comparison operator");
2010 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2011 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2012 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2013 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2014 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2015 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002016 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002017 }
2018 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002019 if (!LHSTy->isIntegralOrEnumerationType() ||
2020 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002021 // We can't continue from here for non-integral types, and they
2022 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002023 return false;
2024 }
2025
Anders Carlsson9c181652008-07-08 14:35:21 +00002026 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002027 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002028 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002029 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002030
Richard Smith11562c52011-10-28 17:51:58 +00002031 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002032 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002033 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002034
2035 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002036 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002037 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2038 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002039 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002040 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002041 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002042 LHSVal.getLValueOffset() -= AdditionalOffset;
2043 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002044 return true;
2045 }
2046
2047 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002048 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002049 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002050 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2051 LHSVal.getInt().getZExtValue());
2052 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002053 return true;
2054 }
2055
2056 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002057 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002058 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002059
Richard Smith11562c52011-10-28 17:51:58 +00002060 APSInt &LHS = LHSVal.getInt();
2061 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002062
Anders Carlsson9c181652008-07-08 14:35:21 +00002063 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002064 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002065 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002066 case BO_Mul: return Success(LHS * RHS, E);
2067 case BO_Add: return Success(LHS + RHS, E);
2068 case BO_Sub: return Success(LHS - RHS, E);
2069 case BO_And: return Success(LHS & RHS, E);
2070 case BO_Xor: return Success(LHS ^ RHS, E);
2071 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002072 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002073 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002074 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002075 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002076 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002077 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002078 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002079 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002080 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002081 // During constant-folding, a negative shift is an opposite shift.
2082 if (RHS.isSigned() && RHS.isNegative()) {
2083 RHS = -RHS;
2084 goto shift_right;
2085 }
2086
2087 shift_left:
2088 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002089 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2090 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002091 }
John McCalle3027922010-08-25 11:45:40 +00002092 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002093 // During constant-folding, a negative shift is an opposite shift.
2094 if (RHS.isSigned() && RHS.isNegative()) {
2095 RHS = -RHS;
2096 goto shift_left;
2097 }
2098
2099 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002100 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002101 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2102 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104
Richard Smith11562c52011-10-28 17:51:58 +00002105 case BO_LT: return Success(LHS < RHS, E);
2106 case BO_GT: return Success(LHS > RHS, E);
2107 case BO_LE: return Success(LHS <= RHS, E);
2108 case BO_GE: return Success(LHS >= RHS, E);
2109 case BO_EQ: return Success(LHS == RHS, E);
2110 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002111 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002112}
2113
Ken Dyck160146e2010-01-27 17:10:57 +00002114CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002115 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2116 // the result is the size of the referenced type."
2117 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2118 // result shall be the alignment of the referenced type."
2119 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2120 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002121
2122 // __alignof is defined to return the preferred alignment.
2123 return Info.Ctx.toCharUnitsFromBits(
2124 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002125}
2126
Ken Dyck160146e2010-01-27 17:10:57 +00002127CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002128 E = E->IgnoreParens();
2129
2130 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002131 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002132 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002133 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2134 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002135
Chris Lattner68061312009-01-24 21:53:27 +00002136 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002137 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2138 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002139
Chris Lattner24aeeab2009-01-24 21:09:06 +00002140 return GetAlignOfType(E->getType());
2141}
2142
2143
Peter Collingbournee190dee2011-03-11 19:24:49 +00002144/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2145/// a result as the expression's type.
2146bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2147 const UnaryExprOrTypeTraitExpr *E) {
2148 switch(E->getKind()) {
2149 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002150 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002151 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002152 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002153 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002154 }
Eli Friedman64004332009-03-23 04:38:34 +00002155
Peter Collingbournee190dee2011-03-11 19:24:49 +00002156 case UETT_VecStep: {
2157 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002158
Peter Collingbournee190dee2011-03-11 19:24:49 +00002159 if (Ty->isVectorType()) {
2160 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002161
Peter Collingbournee190dee2011-03-11 19:24:49 +00002162 // The vec_step built-in functions that take a 3-component
2163 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2164 if (n == 3)
2165 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002166
Peter Collingbournee190dee2011-03-11 19:24:49 +00002167 return Success(n, E);
2168 } else
2169 return Success(1, E);
2170 }
2171
2172 case UETT_SizeOf: {
2173 QualType SrcTy = E->getTypeOfArgument();
2174 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2175 // the result is the size of the referenced type."
2176 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2177 // result shall be the alignment of the referenced type."
2178 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2179 SrcTy = Ref->getPointeeType();
2180
2181 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2182 // extension.
2183 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2184 return Success(1, E);
2185
2186 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2187 if (!SrcTy->isConstantSizeType())
2188 return false;
2189
2190 // Get information about the size.
2191 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2192 }
2193 }
2194
2195 llvm_unreachable("unknown expr/type trait");
2196 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002197}
2198
Peter Collingbournee9200682011-05-13 03:29:01 +00002199bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002200 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002201 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002202 if (n == 0)
2203 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002204 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002205 for (unsigned i = 0; i != n; ++i) {
2206 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2207 switch (ON.getKind()) {
2208 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002209 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002210 APSInt IdxResult;
2211 if (!EvaluateInteger(Idx, IdxResult, Info))
2212 return false;
2213 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2214 if (!AT)
2215 return false;
2216 CurrentType = AT->getElementType();
2217 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2218 Result += IdxResult.getSExtValue() * ElementSize;
2219 break;
2220 }
2221
2222 case OffsetOfExpr::OffsetOfNode::Field: {
2223 FieldDecl *MemberDecl = ON.getField();
2224 const RecordType *RT = CurrentType->getAs<RecordType>();
2225 if (!RT)
2226 return false;
2227 RecordDecl *RD = RT->getDecl();
2228 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002229 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002230 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002231 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002232 CurrentType = MemberDecl->getType().getNonReferenceType();
2233 break;
2234 }
2235
2236 case OffsetOfExpr::OffsetOfNode::Identifier:
2237 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002238 return false;
2239
2240 case OffsetOfExpr::OffsetOfNode::Base: {
2241 CXXBaseSpecifier *BaseSpec = ON.getBase();
2242 if (BaseSpec->isVirtual())
2243 return false;
2244
2245 // Find the layout of the class whose base we are looking into.
2246 const RecordType *RT = CurrentType->getAs<RecordType>();
2247 if (!RT)
2248 return false;
2249 RecordDecl *RD = RT->getDecl();
2250 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2251
2252 // Find the base class itself.
2253 CurrentType = BaseSpec->getType();
2254 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2255 if (!BaseRT)
2256 return false;
2257
2258 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002259 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002260 break;
2261 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002262 }
2263 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002264 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002265}
2266
Chris Lattnere13042c2008-07-11 19:10:17 +00002267bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002268 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002269 // LNot's operand isn't necessarily an integer, so we handle it specially.
2270 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002271 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002272 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002273 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002274 }
2275
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002276 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002277 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002278 return false;
2279
Richard Smith11562c52011-10-28 17:51:58 +00002280 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002281 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002282 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002283 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002284
Chris Lattnerf09ad162008-07-11 22:15:16 +00002285 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002286 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002287 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2288 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002289 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002290 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002291 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2292 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002293 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002294 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002295 // The result is just the value.
2296 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002297 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002298 if (!Val.isInt()) return false;
2299 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002300 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002301 if (!Val.isInt()) return false;
2302 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002303 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002304}
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattner477c4be2008-07-12 01:15:53 +00002306/// HandleCast - This is used to evaluate implicit or explicit casts where the
2307/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002308bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2309 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002310 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002311 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002312
Eli Friedmanc757de22011-03-25 00:43:55 +00002313 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002314 case CK_BaseToDerived:
2315 case CK_DerivedToBase:
2316 case CK_UncheckedDerivedToBase:
2317 case CK_Dynamic:
2318 case CK_ToUnion:
2319 case CK_ArrayToPointerDecay:
2320 case CK_FunctionToPointerDecay:
2321 case CK_NullToPointer:
2322 case CK_NullToMemberPointer:
2323 case CK_BaseToDerivedMemberPointer:
2324 case CK_DerivedToBaseMemberPointer:
2325 case CK_ConstructorConversion:
2326 case CK_IntegralToPointer:
2327 case CK_ToVoid:
2328 case CK_VectorSplat:
2329 case CK_IntegralToFloating:
2330 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002331 case CK_CPointerToObjCPointerCast:
2332 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002333 case CK_AnyPointerToBlockPointerCast:
2334 case CK_ObjCObjectLValueCast:
2335 case CK_FloatingRealToComplex:
2336 case CK_FloatingComplexToReal:
2337 case CK_FloatingComplexCast:
2338 case CK_FloatingComplexToIntegralComplex:
2339 case CK_IntegralRealToComplex:
2340 case CK_IntegralComplexCast:
2341 case CK_IntegralComplexToFloatingComplex:
2342 llvm_unreachable("invalid cast kind for integral value");
2343
Eli Friedman9faf2f92011-03-25 19:07:11 +00002344 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002345 case CK_Dependent:
2346 case CK_GetObjCProperty:
2347 case CK_LValueBitCast:
2348 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002349 case CK_ARCProduceObject:
2350 case CK_ARCConsumeObject:
2351 case CK_ARCReclaimReturnedObject:
2352 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002353 return false;
2354
2355 case CK_LValueToRValue:
2356 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002357 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002358
2359 case CK_MemberPointerToBoolean:
2360 case CK_PointerToBoolean:
2361 case CK_IntegralToBoolean:
2362 case CK_FloatingToBoolean:
2363 case CK_FloatingComplexToBoolean:
2364 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002365 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002366 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002367 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002368 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002369 }
2370
Eli Friedmanc757de22011-03-25 00:43:55 +00002371 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002372 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002373 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002374
Eli Friedman742421e2009-02-20 01:15:07 +00002375 if (!Result.isInt()) {
2376 // Only allow casts of lvalues if they are lossless.
2377 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2378 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002379
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002380 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002381 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002382 }
Mike Stump11289f42009-09-09 15:08:12 +00002383
Eli Friedmanc757de22011-03-25 00:43:55 +00002384 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002385 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002386 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002387 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002388
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002389 if (LV.getLValueBase()) {
2390 // Only allow based lvalue casts if they are lossless.
2391 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2392 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002393
John McCall45d55e42010-05-07 21:00:08 +00002394 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002395 return true;
2396 }
2397
Ken Dyck02990832010-01-15 12:37:54 +00002398 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2399 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002400 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002401 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002402
Eli Friedmanc757de22011-03-25 00:43:55 +00002403 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002404 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002405 if (!EvaluateComplex(SubExpr, C, Info))
2406 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002407 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002408 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002409
Eli Friedmanc757de22011-03-25 00:43:55 +00002410 case CK_FloatingToIntegral: {
2411 APFloat F(0.0);
2412 if (!EvaluateFloat(SubExpr, F, Info))
2413 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002414
Eli Friedmanc757de22011-03-25 00:43:55 +00002415 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2416 }
2417 }
Mike Stump11289f42009-09-09 15:08:12 +00002418
Eli Friedmanc757de22011-03-25 00:43:55 +00002419 llvm_unreachable("unknown cast resulting in integral value");
2420 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002421}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002422
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002423bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2424 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002425 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002426 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2427 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2428 return Success(LV.getComplexIntReal(), E);
2429 }
2430
2431 return Visit(E->getSubExpr());
2432}
2433
Eli Friedman4e7a2412009-02-27 04:45:43 +00002434bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002435 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002436 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002437 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2438 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2439 return Success(LV.getComplexIntImag(), E);
2440 }
2441
Richard Smith4a678122011-10-24 18:44:57 +00002442 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002443 return Success(0, E);
2444}
2445
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002446bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2447 return Success(E->getPackLength(), E);
2448}
2449
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002450bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2451 return Success(E->getValue(), E);
2452}
2453
Chris Lattner05706e882008-07-11 18:11:29 +00002454//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002455// Float Evaluation
2456//===----------------------------------------------------------------------===//
2457
2458namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002459class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002460 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002461 APFloat &Result;
2462public:
2463 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002464 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002465
Richard Smith0b0a0b62011-10-29 20:57:55 +00002466 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002467 Result = V.getFloat();
2468 return true;
2469 }
2470 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002471 return false;
2472 }
2473
Richard Smith4ce706a2011-10-11 21:43:33 +00002474 bool ValueInitialization(const Expr *E) {
2475 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2476 return true;
2477 }
2478
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002479 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002480
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002481 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002482 bool VisitBinaryOperator(const BinaryOperator *E);
2483 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002484 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002485
John McCallb1fb0d32010-05-07 22:08:54 +00002486 bool VisitUnaryReal(const UnaryOperator *E);
2487 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002488
John McCallb1fb0d32010-05-07 22:08:54 +00002489 // FIXME: Missing: array subscript of vector, member of vector,
2490 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002491};
2492} // end anonymous namespace
2493
2494static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002495 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002496 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002497}
2498
Jay Foad39c79802011-01-12 09:06:06 +00002499static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002500 QualType ResultTy,
2501 const Expr *Arg,
2502 bool SNaN,
2503 llvm::APFloat &Result) {
2504 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2505 if (!S) return false;
2506
2507 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2508
2509 llvm::APInt fill;
2510
2511 // Treat empty strings as if they were zero.
2512 if (S->getString().empty())
2513 fill = llvm::APInt(32, 0);
2514 else if (S->getString().getAsInteger(0, fill))
2515 return false;
2516
2517 if (SNaN)
2518 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2519 else
2520 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2521 return true;
2522}
2523
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002524bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002525 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002526 default:
2527 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2528
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002529 case Builtin::BI__builtin_huge_val:
2530 case Builtin::BI__builtin_huge_valf:
2531 case Builtin::BI__builtin_huge_vall:
2532 case Builtin::BI__builtin_inf:
2533 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002534 case Builtin::BI__builtin_infl: {
2535 const llvm::fltSemantics &Sem =
2536 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002537 Result = llvm::APFloat::getInf(Sem);
2538 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
John McCall16291492010-02-28 13:00:19 +00002541 case Builtin::BI__builtin_nans:
2542 case Builtin::BI__builtin_nansf:
2543 case Builtin::BI__builtin_nansl:
2544 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2545 true, Result);
2546
Chris Lattner0b7282e2008-10-06 06:31:58 +00002547 case Builtin::BI__builtin_nan:
2548 case Builtin::BI__builtin_nanf:
2549 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002550 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002551 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002552 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2553 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002554
2555 case Builtin::BI__builtin_fabs:
2556 case Builtin::BI__builtin_fabsf:
2557 case Builtin::BI__builtin_fabsl:
2558 if (!EvaluateFloat(E->getArg(0), Result, Info))
2559 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002561 if (Result.isNegative())
2562 Result.changeSign();
2563 return true;
2564
Mike Stump11289f42009-09-09 15:08:12 +00002565 case Builtin::BI__builtin_copysign:
2566 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002567 case Builtin::BI__builtin_copysignl: {
2568 APFloat RHS(0.);
2569 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2570 !EvaluateFloat(E->getArg(1), RHS, Info))
2571 return false;
2572 Result.copySign(RHS);
2573 return true;
2574 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002575 }
2576}
2577
John McCallb1fb0d32010-05-07 22:08:54 +00002578bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002579 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2580 ComplexValue CV;
2581 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2582 return false;
2583 Result = CV.FloatReal;
2584 return true;
2585 }
2586
2587 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002588}
2589
2590bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002591 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2592 ComplexValue CV;
2593 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2594 return false;
2595 Result = CV.FloatImag;
2596 return true;
2597 }
2598
Richard Smith4a678122011-10-24 18:44:57 +00002599 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002600 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2601 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002602 return true;
2603}
2604
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002605bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002606 switch (E->getOpcode()) {
2607 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002608 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002609 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002610 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002611 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2612 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002613 Result.changeSign();
2614 return true;
2615 }
2616}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002617
Eli Friedman24c01542008-08-22 00:06:13 +00002618bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002619 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002620 VisitIgnoredValue(E->getLHS());
2621 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002622 }
2623
Richard Smith472d4952011-10-28 23:26:52 +00002624 // We can't evaluate pointer-to-member operations or assignments.
2625 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002626 return false;
2627
Eli Friedman24c01542008-08-22 00:06:13 +00002628 // FIXME: Diagnostics? I really don't understand how the warnings
2629 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002630 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002631 if (!EvaluateFloat(E->getLHS(), Result, Info))
2632 return false;
2633 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2634 return false;
2635
2636 switch (E->getOpcode()) {
2637 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002638 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002639 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2640 return true;
John McCalle3027922010-08-25 11:45:40 +00002641 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002642 Result.add(RHS, APFloat::rmNearestTiesToEven);
2643 return true;
John McCalle3027922010-08-25 11:45:40 +00002644 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002645 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2646 return true;
John McCalle3027922010-08-25 11:45:40 +00002647 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002648 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2649 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002650 }
2651}
2652
2653bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2654 Result = E->getValue();
2655 return true;
2656}
2657
Peter Collingbournee9200682011-05-13 03:29:01 +00002658bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2659 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002660
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002661 switch (E->getCastKind()) {
2662 default:
Richard Smith11562c52011-10-28 17:51:58 +00002663 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002664
2665 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002666 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002667 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002668 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002669 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002670 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002671 return true;
2672 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002673
2674 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002675 if (!Visit(SubExpr))
2676 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002677 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2678 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002679 return true;
2680 }
John McCalld7646252010-11-14 08:17:51 +00002681
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002682 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002683 ComplexValue V;
2684 if (!EvaluateComplex(SubExpr, V, Info))
2685 return false;
2686 Result = V.getComplexFloatReal();
2687 return true;
2688 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002689 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002690
2691 return false;
2692}
2693
Eli Friedman24c01542008-08-22 00:06:13 +00002694//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002695// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002696//===----------------------------------------------------------------------===//
2697
2698namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002699class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002700 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002701 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002702
Anders Carlsson537969c2008-11-16 20:27:53 +00002703public:
John McCall93d91dc2010-05-07 17:22:02 +00002704 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002705 : ExprEvaluatorBaseTy(info), Result(Result) {}
2706
Richard Smith0b0a0b62011-10-29 20:57:55 +00002707 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002708 Result.setFrom(V);
2709 return true;
2710 }
2711 bool Error(const Expr *E) {
2712 return false;
2713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Anders Carlsson537969c2008-11-16 20:27:53 +00002715 //===--------------------------------------------------------------------===//
2716 // Visitor Methods
2717 //===--------------------------------------------------------------------===//
2718
Peter Collingbournee9200682011-05-13 03:29:01 +00002719 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002720
Peter Collingbournee9200682011-05-13 03:29:01 +00002721 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002722
John McCall93d91dc2010-05-07 17:22:02 +00002723 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002724 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002725 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002726};
2727} // end anonymous namespace
2728
John McCall93d91dc2010-05-07 17:22:02 +00002729static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2730 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002731 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002732 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002733}
2734
Peter Collingbournee9200682011-05-13 03:29:01 +00002735bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2736 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002737
2738 if (SubExpr->getType()->isRealFloatingType()) {
2739 Result.makeComplexFloat();
2740 APFloat &Imag = Result.FloatImag;
2741 if (!EvaluateFloat(SubExpr, Imag, Info))
2742 return false;
2743
2744 Result.FloatReal = APFloat(Imag.getSemantics());
2745 return true;
2746 } else {
2747 assert(SubExpr->getType()->isIntegerType() &&
2748 "Unexpected imaginary literal.");
2749
2750 Result.makeComplexInt();
2751 APSInt &Imag = Result.IntImag;
2752 if (!EvaluateInteger(SubExpr, Imag, Info))
2753 return false;
2754
2755 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2756 return true;
2757 }
2758}
2759
Peter Collingbournee9200682011-05-13 03:29:01 +00002760bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002761
John McCallfcef3cf2010-12-14 17:51:41 +00002762 switch (E->getCastKind()) {
2763 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002764 case CK_BaseToDerived:
2765 case CK_DerivedToBase:
2766 case CK_UncheckedDerivedToBase:
2767 case CK_Dynamic:
2768 case CK_ToUnion:
2769 case CK_ArrayToPointerDecay:
2770 case CK_FunctionToPointerDecay:
2771 case CK_NullToPointer:
2772 case CK_NullToMemberPointer:
2773 case CK_BaseToDerivedMemberPointer:
2774 case CK_DerivedToBaseMemberPointer:
2775 case CK_MemberPointerToBoolean:
2776 case CK_ConstructorConversion:
2777 case CK_IntegralToPointer:
2778 case CK_PointerToIntegral:
2779 case CK_PointerToBoolean:
2780 case CK_ToVoid:
2781 case CK_VectorSplat:
2782 case CK_IntegralCast:
2783 case CK_IntegralToBoolean:
2784 case CK_IntegralToFloating:
2785 case CK_FloatingToIntegral:
2786 case CK_FloatingToBoolean:
2787 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002788 case CK_CPointerToObjCPointerCast:
2789 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002790 case CK_AnyPointerToBlockPointerCast:
2791 case CK_ObjCObjectLValueCast:
2792 case CK_FloatingComplexToReal:
2793 case CK_FloatingComplexToBoolean:
2794 case CK_IntegralComplexToReal:
2795 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002796 case CK_ARCProduceObject:
2797 case CK_ARCConsumeObject:
2798 case CK_ARCReclaimReturnedObject:
2799 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002800 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002801
John McCallfcef3cf2010-12-14 17:51:41 +00002802 case CK_LValueToRValue:
2803 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002804 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002805
2806 case CK_Dependent:
2807 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002808 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002809 case CK_UserDefinedConversion:
2810 return false;
2811
2812 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002813 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002814 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002815 return false;
2816
John McCallfcef3cf2010-12-14 17:51:41 +00002817 Result.makeComplexFloat();
2818 Result.FloatImag = APFloat(Real.getSemantics());
2819 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002820 }
2821
John McCallfcef3cf2010-12-14 17:51:41 +00002822 case CK_FloatingComplexCast: {
2823 if (!Visit(E->getSubExpr()))
2824 return false;
2825
2826 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2827 QualType From
2828 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2829
2830 Result.FloatReal
2831 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2832 Result.FloatImag
2833 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2834 return true;
2835 }
2836
2837 case CK_FloatingComplexToIntegralComplex: {
2838 if (!Visit(E->getSubExpr()))
2839 return false;
2840
2841 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2842 QualType From
2843 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2844 Result.makeComplexInt();
2845 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2846 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2847 return true;
2848 }
2849
2850 case CK_IntegralRealToComplex: {
2851 APSInt &Real = Result.IntReal;
2852 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2853 return false;
2854
2855 Result.makeComplexInt();
2856 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2857 return true;
2858 }
2859
2860 case CK_IntegralComplexCast: {
2861 if (!Visit(E->getSubExpr()))
2862 return false;
2863
2864 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2865 QualType From
2866 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2867
2868 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2869 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2870 return true;
2871 }
2872
2873 case CK_IntegralComplexToFloatingComplex: {
2874 if (!Visit(E->getSubExpr()))
2875 return false;
2876
2877 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2878 QualType From
2879 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2880 Result.makeComplexFloat();
2881 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2882 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2883 return true;
2884 }
2885 }
2886
2887 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002888 return false;
2889}
2890
John McCall93d91dc2010-05-07 17:22:02 +00002891bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002892 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002893 VisitIgnoredValue(E->getLHS());
2894 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002895 }
John McCall93d91dc2010-05-07 17:22:02 +00002896 if (!Visit(E->getLHS()))
2897 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002898
John McCall93d91dc2010-05-07 17:22:02 +00002899 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002900 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002901 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002902
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002903 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2904 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002905 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002906 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002907 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002908 if (Result.isComplexFloat()) {
2909 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2910 APFloat::rmNearestTiesToEven);
2911 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2912 APFloat::rmNearestTiesToEven);
2913 } else {
2914 Result.getComplexIntReal() += RHS.getComplexIntReal();
2915 Result.getComplexIntImag() += RHS.getComplexIntImag();
2916 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002917 break;
John McCalle3027922010-08-25 11:45:40 +00002918 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002919 if (Result.isComplexFloat()) {
2920 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2921 APFloat::rmNearestTiesToEven);
2922 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2923 APFloat::rmNearestTiesToEven);
2924 } else {
2925 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2926 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2927 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002928 break;
John McCalle3027922010-08-25 11:45:40 +00002929 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002930 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002931 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002932 APFloat &LHS_r = LHS.getComplexFloatReal();
2933 APFloat &LHS_i = LHS.getComplexFloatImag();
2934 APFloat &RHS_r = RHS.getComplexFloatReal();
2935 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002936
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002937 APFloat Tmp = LHS_r;
2938 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2939 Result.getComplexFloatReal() = Tmp;
2940 Tmp = LHS_i;
2941 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2942 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2943
2944 Tmp = LHS_r;
2945 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2946 Result.getComplexFloatImag() = Tmp;
2947 Tmp = LHS_i;
2948 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2949 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2950 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002951 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002952 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002953 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2954 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002955 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002956 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2957 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2958 }
2959 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002960 case BO_Div:
2961 if (Result.isComplexFloat()) {
2962 ComplexValue LHS = Result;
2963 APFloat &LHS_r = LHS.getComplexFloatReal();
2964 APFloat &LHS_i = LHS.getComplexFloatImag();
2965 APFloat &RHS_r = RHS.getComplexFloatReal();
2966 APFloat &RHS_i = RHS.getComplexFloatImag();
2967 APFloat &Res_r = Result.getComplexFloatReal();
2968 APFloat &Res_i = Result.getComplexFloatImag();
2969
2970 APFloat Den = RHS_r;
2971 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2972 APFloat Tmp = RHS_i;
2973 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2974 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2975
2976 Res_r = LHS_r;
2977 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2978 Tmp = LHS_i;
2979 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2980 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2981 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2982
2983 Res_i = LHS_i;
2984 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2985 Tmp = LHS_r;
2986 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2987 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2988 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2989 } else {
2990 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2991 // FIXME: what about diagnostics?
2992 return false;
2993 }
2994 ComplexValue LHS = Result;
2995 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2996 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2997 Result.getComplexIntReal() =
2998 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2999 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3000 Result.getComplexIntImag() =
3001 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3002 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3003 }
3004 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003005 }
3006
John McCall93d91dc2010-05-07 17:22:02 +00003007 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003008}
3009
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003010bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3011 // Get the operand value into 'Result'.
3012 if (!Visit(E->getSubExpr()))
3013 return false;
3014
3015 switch (E->getOpcode()) {
3016 default:
3017 // FIXME: what about diagnostics?
3018 return false;
3019 case UO_Extension:
3020 return true;
3021 case UO_Plus:
3022 // The result is always just the subexpr.
3023 return true;
3024 case UO_Minus:
3025 if (Result.isComplexFloat()) {
3026 Result.getComplexFloatReal().changeSign();
3027 Result.getComplexFloatImag().changeSign();
3028 }
3029 else {
3030 Result.getComplexIntReal() = -Result.getComplexIntReal();
3031 Result.getComplexIntImag() = -Result.getComplexIntImag();
3032 }
3033 return true;
3034 case UO_Not:
3035 if (Result.isComplexFloat())
3036 Result.getComplexFloatImag().changeSign();
3037 else
3038 Result.getComplexIntImag() = -Result.getComplexIntImag();
3039 return true;
3040 }
3041}
3042
Anders Carlsson537969c2008-11-16 20:27:53 +00003043//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003044// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003045//===----------------------------------------------------------------------===//
3046
Richard Smith0b0a0b62011-10-29 20:57:55 +00003047static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003048 // In C, function designators are not lvalues, but we evaluate them as if they
3049 // are.
3050 if (E->isGLValue() || E->getType()->isFunctionType()) {
3051 LValue LV;
3052 if (!EvaluateLValue(E, LV, Info))
3053 return false;
3054 LV.moveInto(Result);
3055 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003056 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003057 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003058 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003059 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003060 return false;
John McCall45d55e42010-05-07 21:00:08 +00003061 } else if (E->getType()->hasPointerRepresentation()) {
3062 LValue LV;
3063 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003064 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003065 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003066 } else if (E->getType()->isRealFloatingType()) {
3067 llvm::APFloat F(0.0);
3068 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003069 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003070 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003071 } else if (E->getType()->isAnyComplexType()) {
3072 ComplexValue C;
3073 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003074 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003075 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003076 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003077 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003078
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003079 return true;
3080}
3081
Richard Smith11562c52011-10-28 17:51:58 +00003082
Richard Smith7b553f12011-10-29 00:50:52 +00003083/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003084/// any crazy technique (that has nothing to do with language standards) that
3085/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003086/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3087/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003088bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003089 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003090
Richard Smith0b0a0b62011-10-29 20:57:55 +00003091 CCValue Value;
3092 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003093 return false;
3094
3095 if (isGLValue()) {
3096 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003097 LV.setFrom(Value);
3098 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3099 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003100 }
3101
Richard Smith0b0a0b62011-10-29 20:57:55 +00003102 // Check this core constant expression is a constant expression, and if so,
3103 // slice it down to one.
3104 if (!CheckConstantExpression(Value))
3105 return false;
3106 Result.Val = Value;
3107 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003108}
3109
Jay Foad39c79802011-01-12 09:06:06 +00003110bool Expr::EvaluateAsBooleanCondition(bool &Result,
3111 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003112 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003113 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003114 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3115 Result);
John McCall1be1c632010-01-05 23:42:56 +00003116}
3117
Richard Smithcaf33902011-10-10 18:28:20 +00003118bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003119 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003120 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003121 !ExprResult.Val.isInt()) {
3122 return false;
3123 }
3124 Result = ExprResult.Val.getInt();
3125 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003126}
3127
Jay Foad39c79802011-01-12 09:06:06 +00003128bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003129 EvalInfo Info(Ctx, Result);
3130
John McCall45d55e42010-05-07 21:00:08 +00003131 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003132 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003133 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003134 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003135 return true;
3136 }
3137 return false;
3138}
3139
Jay Foad39c79802011-01-12 09:06:06 +00003140bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3141 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003142 EvalInfo Info(Ctx, Result);
3143
3144 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003145 // Don't allow references to out-of-scope function parameters to escape.
3146 if (EvaluateLValue(this, LV, Info) &&
3147 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3148 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003149 return true;
3150 }
3151 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003152}
3153
Richard Smith7b553f12011-10-29 00:50:52 +00003154/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3155/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003156bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003157 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003158 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003159}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003160
Jay Foad39c79802011-01-12 09:06:06 +00003161bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003162 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003163}
3164
Richard Smithcaf33902011-10-10 18:28:20 +00003165APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003166 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003167 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003168 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003169 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003170 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003171
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003172 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003173}
John McCall864e3962010-05-07 05:32:02 +00003174
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003175 bool Expr::EvalResult::isGlobalLValue() const {
3176 assert(Val.isLValue());
3177 return IsGlobalLValue(Val.getLValueBase());
3178 }
3179
3180
John McCall864e3962010-05-07 05:32:02 +00003181/// isIntegerConstantExpr - this recursive routine will test if an expression is
3182/// an integer constant expression.
3183
3184/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3185/// comma, etc
3186///
3187/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3188/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3189/// cast+dereference.
3190
3191// CheckICE - This function does the fundamental ICE checking: the returned
3192// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3193// Note that to reduce code duplication, this helper does no evaluation
3194// itself; the caller checks whether the expression is evaluatable, and
3195// in the rare cases where CheckICE actually cares about the evaluated
3196// value, it calls into Evalute.
3197//
3198// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003199// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003200// 1: This expression is not an ICE, but if it isn't evaluated, it's
3201// a legal subexpression for an ICE. This return value is used to handle
3202// the comma operator in C99 mode.
3203// 2: This expression is not an ICE, and is not a legal subexpression for one.
3204
Dan Gohman28ade552010-07-26 21:25:24 +00003205namespace {
3206
John McCall864e3962010-05-07 05:32:02 +00003207struct ICEDiag {
3208 unsigned Val;
3209 SourceLocation Loc;
3210
3211 public:
3212 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3213 ICEDiag() : Val(0) {}
3214};
3215
Dan Gohman28ade552010-07-26 21:25:24 +00003216}
3217
3218static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003219
3220static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3221 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003222 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003223 !EVResult.Val.isInt()) {
3224 return ICEDiag(2, E->getLocStart());
3225 }
3226 return NoDiag();
3227}
3228
3229static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3230 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003231 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003232 return ICEDiag(2, E->getLocStart());
3233 }
3234
3235 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003236#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003237#define STMT(Node, Base) case Expr::Node##Class:
3238#define EXPR(Node, Base)
3239#include "clang/AST/StmtNodes.inc"
3240 case Expr::PredefinedExprClass:
3241 case Expr::FloatingLiteralClass:
3242 case Expr::ImaginaryLiteralClass:
3243 case Expr::StringLiteralClass:
3244 case Expr::ArraySubscriptExprClass:
3245 case Expr::MemberExprClass:
3246 case Expr::CompoundAssignOperatorClass:
3247 case Expr::CompoundLiteralExprClass:
3248 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003249 case Expr::DesignatedInitExprClass:
3250 case Expr::ImplicitValueInitExprClass:
3251 case Expr::ParenListExprClass:
3252 case Expr::VAArgExprClass:
3253 case Expr::AddrLabelExprClass:
3254 case Expr::StmtExprClass:
3255 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003256 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003257 case Expr::CXXDynamicCastExprClass:
3258 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003259 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003260 case Expr::CXXNullPtrLiteralExprClass:
3261 case Expr::CXXThisExprClass:
3262 case Expr::CXXThrowExprClass:
3263 case Expr::CXXNewExprClass:
3264 case Expr::CXXDeleteExprClass:
3265 case Expr::CXXPseudoDestructorExprClass:
3266 case Expr::UnresolvedLookupExprClass:
3267 case Expr::DependentScopeDeclRefExprClass:
3268 case Expr::CXXConstructExprClass:
3269 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003270 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003271 case Expr::CXXTemporaryObjectExprClass:
3272 case Expr::CXXUnresolvedConstructExprClass:
3273 case Expr::CXXDependentScopeMemberExprClass:
3274 case Expr::UnresolvedMemberExprClass:
3275 case Expr::ObjCStringLiteralClass:
3276 case Expr::ObjCEncodeExprClass:
3277 case Expr::ObjCMessageExprClass:
3278 case Expr::ObjCSelectorExprClass:
3279 case Expr::ObjCProtocolExprClass:
3280 case Expr::ObjCIvarRefExprClass:
3281 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003282 case Expr::ObjCIsaExprClass:
3283 case Expr::ShuffleVectorExprClass:
3284 case Expr::BlockExprClass:
3285 case Expr::BlockDeclRefExprClass:
3286 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003287 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003288 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003289 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003290 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003291 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003292 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003293 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003294 return ICEDiag(2, E->getLocStart());
3295
Sebastian Redl12757ab2011-09-24 17:48:14 +00003296 case Expr::InitListExprClass:
3297 if (Ctx.getLangOptions().CPlusPlus0x) {
3298 const InitListExpr *ILE = cast<InitListExpr>(E);
3299 if (ILE->getNumInits() == 0)
3300 return NoDiag();
3301 if (ILE->getNumInits() == 1)
3302 return CheckICE(ILE->getInit(0), Ctx);
3303 // Fall through for more than 1 expression.
3304 }
3305 return ICEDiag(2, E->getLocStart());
3306
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003307 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003308 case Expr::GNUNullExprClass:
3309 // GCC considers the GNU __null value to be an integral constant expression.
3310 return NoDiag();
3311
John McCall7c454bb2011-07-15 05:09:51 +00003312 case Expr::SubstNonTypeTemplateParmExprClass:
3313 return
3314 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3315
John McCall864e3962010-05-07 05:32:02 +00003316 case Expr::ParenExprClass:
3317 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003318 case Expr::GenericSelectionExprClass:
3319 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003320 case Expr::IntegerLiteralClass:
3321 case Expr::CharacterLiteralClass:
3322 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003323 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003324 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003325 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003326 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003327 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003328 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003329 return NoDiag();
3330 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003331 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003332 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3333 // constant expressions, but they can never be ICEs because an ICE cannot
3334 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003335 const CallExpr *CE = cast<CallExpr>(E);
3336 if (CE->isBuiltinCall(Ctx))
3337 return CheckEvalInICE(E, Ctx);
3338 return ICEDiag(2, E->getLocStart());
3339 }
3340 case Expr::DeclRefExprClass:
3341 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3342 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003343 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003344 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3345
3346 // Parameter variables are never constants. Without this check,
3347 // getAnyInitializer() can find a default argument, which leads
3348 // to chaos.
3349 if (isa<ParmVarDecl>(D))
3350 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3351
3352 // C++ 7.1.5.1p2
3353 // A variable of non-volatile const-qualified integral or enumeration
3354 // type initialized by an ICE can be used in ICEs.
3355 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003356 // Look for a declaration of this variable that has an initializer.
3357 const VarDecl *ID = 0;
3358 const Expr *Init = Dcl->getAnyInitializer(ID);
3359 if (Init) {
3360 if (ID->isInitKnownICE()) {
3361 // We have already checked whether this subexpression is an
3362 // integral constant expression.
3363 if (ID->isInitICE())
3364 return NoDiag();
3365 else
3366 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3367 }
3368
3369 // It's an ICE whether or not the definition we found is
3370 // out-of-line. See DR 721 and the discussion in Clang PR
3371 // 6206 for details.
3372
3373 if (Dcl->isCheckingICE()) {
3374 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3375 }
3376
3377 Dcl->setCheckingICE();
3378 ICEDiag Result = CheckICE(Init, Ctx);
3379 // Cache the result of the ICE test.
3380 Dcl->setInitKnownICE(Result.Val == 0);
3381 return Result;
3382 }
3383 }
3384 }
3385 return ICEDiag(2, E->getLocStart());
3386 case Expr::UnaryOperatorClass: {
3387 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3388 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003389 case UO_PostInc:
3390 case UO_PostDec:
3391 case UO_PreInc:
3392 case UO_PreDec:
3393 case UO_AddrOf:
3394 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003395 // C99 6.6/3 allows increment and decrement within unevaluated
3396 // subexpressions of constant expressions, but they can never be ICEs
3397 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003398 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003399 case UO_Extension:
3400 case UO_LNot:
3401 case UO_Plus:
3402 case UO_Minus:
3403 case UO_Not:
3404 case UO_Real:
3405 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003406 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003407 }
3408
3409 // OffsetOf falls through here.
3410 }
3411 case Expr::OffsetOfExprClass: {
3412 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003413 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003414 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003415 // compliance: we should warn earlier for offsetof expressions with
3416 // array subscripts that aren't ICEs, and if the array subscripts
3417 // are ICEs, the value of the offsetof must be an integer constant.
3418 return CheckEvalInICE(E, Ctx);
3419 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003420 case Expr::UnaryExprOrTypeTraitExprClass: {
3421 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3422 if ((Exp->getKind() == UETT_SizeOf) &&
3423 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003424 return ICEDiag(2, E->getLocStart());
3425 return NoDiag();
3426 }
3427 case Expr::BinaryOperatorClass: {
3428 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3429 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003430 case BO_PtrMemD:
3431 case BO_PtrMemI:
3432 case BO_Assign:
3433 case BO_MulAssign:
3434 case BO_DivAssign:
3435 case BO_RemAssign:
3436 case BO_AddAssign:
3437 case BO_SubAssign:
3438 case BO_ShlAssign:
3439 case BO_ShrAssign:
3440 case BO_AndAssign:
3441 case BO_XorAssign:
3442 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003443 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3444 // constant expressions, but they can never be ICEs because an ICE cannot
3445 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003446 return ICEDiag(2, E->getLocStart());
3447
John McCalle3027922010-08-25 11:45:40 +00003448 case BO_Mul:
3449 case BO_Div:
3450 case BO_Rem:
3451 case BO_Add:
3452 case BO_Sub:
3453 case BO_Shl:
3454 case BO_Shr:
3455 case BO_LT:
3456 case BO_GT:
3457 case BO_LE:
3458 case BO_GE:
3459 case BO_EQ:
3460 case BO_NE:
3461 case BO_And:
3462 case BO_Xor:
3463 case BO_Or:
3464 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003465 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3466 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003467 if (Exp->getOpcode() == BO_Div ||
3468 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003469 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003470 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003471 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003472 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003473 if (REval == 0)
3474 return ICEDiag(1, E->getLocStart());
3475 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003476 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003477 if (LEval.isMinSignedValue())
3478 return ICEDiag(1, E->getLocStart());
3479 }
3480 }
3481 }
John McCalle3027922010-08-25 11:45:40 +00003482 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003483 if (Ctx.getLangOptions().C99) {
3484 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3485 // if it isn't evaluated.
3486 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3487 return ICEDiag(1, E->getLocStart());
3488 } else {
3489 // In both C89 and C++, commas in ICEs are illegal.
3490 return ICEDiag(2, E->getLocStart());
3491 }
3492 }
3493 if (LHSResult.Val >= RHSResult.Val)
3494 return LHSResult;
3495 return RHSResult;
3496 }
John McCalle3027922010-08-25 11:45:40 +00003497 case BO_LAnd:
3498 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003499 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003500
3501 // C++0x [expr.const]p2:
3502 // [...] subexpressions of logical AND (5.14), logical OR
3503 // (5.15), and condi- tional (5.16) operations that are not
3504 // evaluated are not considered.
3505 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3506 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003507 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003508 return LHSResult;
3509
3510 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003511 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003512 return LHSResult;
3513 }
3514
John McCall864e3962010-05-07 05:32:02 +00003515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3516 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3517 // Rare case where the RHS has a comma "side-effect"; we need
3518 // to actually check the condition to see whether the side
3519 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003520 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003521 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003522 return RHSResult;
3523 return NoDiag();
3524 }
3525
3526 if (LHSResult.Val >= RHSResult.Val)
3527 return LHSResult;
3528 return RHSResult;
3529 }
3530 }
3531 }
3532 case Expr::ImplicitCastExprClass:
3533 case Expr::CStyleCastExprClass:
3534 case Expr::CXXFunctionalCastExprClass:
3535 case Expr::CXXStaticCastExprClass:
3536 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003537 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003538 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003539 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003540 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003541 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3542 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003543 switch (cast<CastExpr>(E)->getCastKind()) {
3544 case CK_LValueToRValue:
3545 case CK_NoOp:
3546 case CK_IntegralToBoolean:
3547 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003548 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003549 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003550 return ICEDiag(2, E->getLocStart());
3551 }
John McCall864e3962010-05-07 05:32:02 +00003552 }
John McCallc07a0c72011-02-17 10:25:35 +00003553 case Expr::BinaryConditionalOperatorClass: {
3554 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3555 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3556 if (CommonResult.Val == 2) return CommonResult;
3557 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3558 if (FalseResult.Val == 2) return FalseResult;
3559 if (CommonResult.Val == 1) return CommonResult;
3560 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003561 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003562 return FalseResult;
3563 }
John McCall864e3962010-05-07 05:32:02 +00003564 case Expr::ConditionalOperatorClass: {
3565 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3566 // If the condition (ignoring parens) is a __builtin_constant_p call,
3567 // then only the true side is actually considered in an integer constant
3568 // expression, and it is fully evaluated. This is an important GNU
3569 // extension. See GCC PR38377 for discussion.
3570 if (const CallExpr *CallCE
3571 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3572 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3573 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003574 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003575 !EVResult.Val.isInt()) {
3576 return ICEDiag(2, E->getLocStart());
3577 }
3578 return NoDiag();
3579 }
3580 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003581 if (CondResult.Val == 2)
3582 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003583
3584 // C++0x [expr.const]p2:
3585 // subexpressions of [...] conditional (5.16) operations that
3586 // are not evaluated are not considered
3587 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003588 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003589 : false;
3590 ICEDiag TrueResult = NoDiag();
3591 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3592 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3593 ICEDiag FalseResult = NoDiag();
3594 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3595 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3596
John McCall864e3962010-05-07 05:32:02 +00003597 if (TrueResult.Val == 2)
3598 return TrueResult;
3599 if (FalseResult.Val == 2)
3600 return FalseResult;
3601 if (CondResult.Val == 1)
3602 return CondResult;
3603 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3604 return NoDiag();
3605 // Rare case where the diagnostics depend on which side is evaluated
3606 // Note that if we get here, CondResult is 0, and at least one of
3607 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003608 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003609 return FalseResult;
3610 }
3611 return TrueResult;
3612 }
3613 case Expr::CXXDefaultArgExprClass:
3614 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3615 case Expr::ChooseExprClass: {
3616 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3617 }
3618 }
3619
3620 // Silence a GCC warning
3621 return ICEDiag(2, E->getLocStart());
3622}
3623
3624bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3625 SourceLocation *Loc, bool isEvaluated) const {
3626 ICEDiag d = CheckICE(this, Ctx);
3627 if (d.Val != 0) {
3628 if (Loc) *Loc = d.Loc;
3629 return false;
3630 }
Richard Smith11562c52011-10-28 17:51:58 +00003631 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003632 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003633 return true;
3634}