blob: 467fb82b8d054fb1b00c16b2a022a32168657f08 [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//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
204 if (IsOnePastTheEnd)
205 return true;
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208 return true;
209 return false;
210 }
211
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
214 if (Invalid)
215 return false;
216 return !isOnePastTheEnd();
217 }
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000227
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000232 }
233 /// Update this designator to refer to the given base or member of this
234 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000236 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000239 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000240
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
246 }
Richard Smith96e0c102011-11-04 02:25:55 +0000247 }
Richard Smith66c96992012-02-18 22:04:06 +0000248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
250 PathEntry Entry;
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
253
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
259 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000263 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000265 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268 setInvalid();
269 }
Richard Smith96e0c102011-11-04 02:25:55 +0000270 return;
271 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
279 else if (N != 0) {
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 }
Richard Smith96e0c102011-11-04 02:25:55 +0000283 }
284 };
285
Richard Smith254a73d2011-10-28 22:34:42 +0000286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
288 EvalInfo &Info;
289
290 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000291 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000292
Richard Smithf6f003a2011-12-16 19:06:07 +0000293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
295
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
298
Richard Smithb228a862012-02-15 02:18:13 +0000299 /// Index - The call index of this call.
300 unsigned Index;
301
Richard Smithd62306a2011-11-10 06:34:14 +0000302 /// This - The binding for the this pointer in this call, if any.
303 const LValue *This;
304
Richard Smith254a73d2011-10-28 22:34:42 +0000305 /// ParmBindings - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000307 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000308
Eli Friedman4830ec82012-06-25 21:21:08 +0000309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000311 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
314 MapTy Temporaries;
315
Richard Smithf6f003a2011-12-16 19:06:07 +0000316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000318 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000319 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000320 };
321
Richard Smith852c9db2013-04-20 22:23:05 +0000322 /// Temporarily override 'this'.
323 class ThisOverrideRAII {
324 public:
325 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
326 : Frame(Frame), OldThis(Frame.This) {
327 if (Enable)
328 Frame.This = NewThis;
329 }
330 ~ThisOverrideRAII() {
331 Frame.This = OldThis;
332 }
333 private:
334 CallStackFrame &Frame;
335 const LValue *OldThis;
336 };
337
Richard Smith92b1ce02011-12-12 09:28:41 +0000338 /// A partial diagnostic which we might know in advance that we are not going
339 /// to emit.
340 class OptionalDiagnostic {
341 PartialDiagnostic *Diag;
342
343 public:
344 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
345
346 template<typename T>
347 OptionalDiagnostic &operator<<(const T &v) {
348 if (Diag)
349 *Diag << v;
350 return *this;
351 }
Richard Smithfe800032012-01-31 04:08:20 +0000352
353 OptionalDiagnostic &operator<<(const APSInt &I) {
354 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000355 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000356 I.toString(Buffer);
357 *Diag << StringRef(Buffer.data(), Buffer.size());
358 }
359 return *this;
360 }
361
362 OptionalDiagnostic &operator<<(const APFloat &F) {
363 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000364 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000365 F.toString(Buffer);
366 *Diag << StringRef(Buffer.data(), Buffer.size());
367 }
368 return *this;
369 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000370 };
371
Richard Smithb228a862012-02-15 02:18:13 +0000372 /// EvalInfo - This is a private struct used by the evaluator to capture
373 /// information about a subexpression as it is folded. It retains information
374 /// about the AST context, but also maintains information about the folded
375 /// expression.
376 ///
377 /// If an expression could be evaluated, it is still possible it is not a C
378 /// "integer constant expression" or constant expression. If not, this struct
379 /// captures information about how and why not.
380 ///
381 /// One bit of information passed *into* the request for constant folding
382 /// indicates whether the subexpression is "evaluated" or not according to C
383 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
384 /// evaluate the expression regardless of what the RHS is, but C only allows
385 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000386 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000388
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000389 /// EvalStatus - Contains information about the evaluation.
390 Expr::EvalStatus &EvalStatus;
391
392 /// CurrentCall - The top of the constexpr call stack.
393 CallStackFrame *CurrentCall;
394
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395 /// CallStackDepth - The number of calls in the call stack right now.
396 unsigned CallStackDepth;
397
Richard Smithb228a862012-02-15 02:18:13 +0000398 /// NextCallIndex - The next call index to assign.
399 unsigned NextCallIndex;
400
Richard Smitha3d3bd22013-05-08 02:12:03 +0000401 /// StepsLeft - The remaining number of evaluation steps we're permitted
402 /// to perform. This is essentially a limit for the number of statements
403 /// we will evaluate.
404 unsigned StepsLeft;
405
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000406 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000407 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000408 CallStackFrame BottomFrame;
409
Richard Smithd62306a2011-11-10 06:34:14 +0000410 /// EvaluatingDecl - This is the declaration whose initializer is being
411 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000412 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000413
414 /// EvaluatingDeclValue - This is the value being constructed for the
415 /// declaration whose initializer is being evaluated, if any.
416 APValue *EvaluatingDeclValue;
417
Richard Smith357362d2011-12-13 06:39:58 +0000418 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
419 /// notes attached to it will also be stored, otherwise they will not be.
420 bool HasActiveDiagnostic;
421
Richard Smith253c2a32012-01-27 01:14:48 +0000422 /// CheckingPotentialConstantExpression - Are we checking whether the
423 /// expression is a potential constant expression? If so, some diagnostics
424 /// are suppressed.
425 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000426
427 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000428
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000429 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000431 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000432 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000433 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000434 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000435 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
436 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000437 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000438
Richard Smith7525ff62013-05-09 07:14:00 +0000439 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
440 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000441 EvaluatingDeclValue = &Value;
442 }
443
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000445
Richard Smith357362d2011-12-13 06:39:58 +0000446 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000447 // Don't perform any constexpr calls (other than the call we're checking)
448 // when checking a potential constant expression.
449 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
450 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000451 if (NextCallIndex == 0) {
452 // NextCallIndex has wrapped around.
453 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
454 return false;
455 }
Richard Smith357362d2011-12-13 06:39:58 +0000456 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
457 return true;
458 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
459 << getLangOpts().ConstexprCallDepth;
460 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000461 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000462
Richard Smithb228a862012-02-15 02:18:13 +0000463 CallStackFrame *getCallFrame(unsigned CallIndex) {
464 assert(CallIndex && "no call index in getCallFrame");
465 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
466 // be null in this loop.
467 CallStackFrame *Frame = CurrentCall;
468 while (Frame->Index > CallIndex)
469 Frame = Frame->Caller;
470 return (Frame->Index == CallIndex) ? Frame : 0;
471 }
472
Richard Smitha3d3bd22013-05-08 02:12:03 +0000473 bool nextStep(const Stmt *S) {
474 if (!StepsLeft) {
475 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
476 return false;
477 }
478 --StepsLeft;
479 return true;
480 }
481
Richard Smith357362d2011-12-13 06:39:58 +0000482 private:
483 /// Add a diagnostic to the diagnostics list.
484 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
485 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
486 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
487 return EvalStatus.Diag->back().second;
488 }
489
Richard Smithf6f003a2011-12-16 19:06:07 +0000490 /// Add notes containing a call stack to the current point of evaluation.
491 void addCallStack(unsigned Limit);
492
Richard Smith357362d2011-12-13 06:39:58 +0000493 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000494 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000495 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
496 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000497 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000498 // If we have a prior diagnostic, it will be noting that the expression
499 // isn't a constant expression. This diagnostic is more important.
500 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000501 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000502 unsigned CallStackNotes = CallStackDepth - 1;
503 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
504 if (Limit)
505 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000506 if (CheckingPotentialConstantExpression)
507 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000508
Richard Smith357362d2011-12-13 06:39:58 +0000509 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000510 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000511 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
512 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000513 if (!CheckingPotentialConstantExpression)
514 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000515 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000516 }
Richard Smith357362d2011-12-13 06:39:58 +0000517 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000518 return OptionalDiagnostic();
519 }
520
Richard Smithce1ec5e2012-03-15 04:53:45 +0000521 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
522 = diag::note_invalid_subexpr_in_const_expr,
523 unsigned ExtraNotes = 0) {
524 if (EvalStatus.Diag)
525 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
526 HasActiveDiagnostic = false;
527 return OptionalDiagnostic();
528 }
529
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000530 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
531
Richard Smith92b1ce02011-12-12 09:28:41 +0000532 /// Diagnose that the evaluation does not produce a C++11 core constant
533 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000534 template<typename LocArg>
535 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000536 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000537 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000538 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000539 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
540 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000541 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000542 }
Richard Smith357362d2011-12-13 06:39:58 +0000543 return Diag(Loc, DiagId, ExtraNotes);
544 }
545
546 /// Add a note to a prior diagnostic.
547 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
548 if (!HasActiveDiagnostic)
549 return OptionalDiagnostic();
550 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000551 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000552
553 /// Add a stack of notes to a prior diagnostic.
554 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
555 if (HasActiveDiagnostic) {
556 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
557 Diags.begin(), Diags.end());
558 }
559 }
Richard Smith253c2a32012-01-27 01:14:48 +0000560
561 /// Should we continue evaluation as much as possible after encountering a
562 /// construct which can't be folded?
563 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000564 // Should return true in IntOverflowCheckMode, so that we check for
565 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000566 return StepsLeft && (IntOverflowCheckMode ||
567 (CheckingPotentialConstantExpression &&
568 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000569 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000570 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000571
572 /// Object used to treat all foldable expressions as constant expressions.
573 struct FoldConstant {
574 bool Enabled;
575
576 explicit FoldConstant(EvalInfo &Info)
577 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
578 !Info.EvalStatus.HasSideEffects) {
579 }
580 // Treat the value we've computed since this object was created as constant.
581 void Fold(EvalInfo &Info) {
582 if (Enabled && !Info.EvalStatus.Diag->empty() &&
583 !Info.EvalStatus.HasSideEffects)
584 Info.EvalStatus.Diag->clear();
585 }
586 };
Richard Smith17100ba2012-02-16 02:46:34 +0000587
588 /// RAII object used to suppress diagnostics and side-effects from a
589 /// speculative evaluation.
590 class SpeculativeEvaluationRAII {
591 EvalInfo &Info;
592 Expr::EvalStatus Old;
593
594 public:
595 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000596 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000597 : Info(Info), Old(Info.EvalStatus) {
598 Info.EvalStatus.Diag = NewDiag;
599 }
600 ~SpeculativeEvaluationRAII() {
601 Info.EvalStatus = Old;
602 }
603 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000604}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000605
Richard Smitha8105bc2012-01-06 16:39:00 +0000606bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
607 CheckSubobjectKind CSK) {
608 if (Invalid)
609 return false;
610 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000611 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000612 << CSK;
613 setInvalid();
614 return false;
615 }
616 return true;
617}
618
619void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
620 const Expr *E, uint64_t N) {
621 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000623 << static_cast<int>(N) << /*array*/ 0
624 << static_cast<unsigned>(MostDerivedArraySize);
625 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000626 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000627 << static_cast<int>(N) << /*non-array*/ 1;
628 setInvalid();
629}
630
Richard Smithf6f003a2011-12-16 19:06:07 +0000631CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
632 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000633 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000634 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000635 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Info.CurrentCall = this;
637 ++Info.CallStackDepth;
638}
639
640CallStackFrame::~CallStackFrame() {
641 assert(Info.CurrentCall == this && "calls retired out of order");
642 --Info.CallStackDepth;
643 Info.CurrentCall = Caller;
644}
645
Richard Smith84401042013-06-03 05:03:02 +0000646static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000647
648void EvalInfo::addCallStack(unsigned Limit) {
649 // Determine which calls to skip, if any.
650 unsigned ActiveCalls = CallStackDepth - 1;
651 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
652 if (Limit && Limit < ActiveCalls) {
653 SkipStart = Limit / 2 + Limit % 2;
654 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000655 }
656
Richard Smithf6f003a2011-12-16 19:06:07 +0000657 // Walk the call stack and add the diagnostics.
658 unsigned CallIdx = 0;
659 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
660 Frame = Frame->Caller, ++CallIdx) {
661 // Skip this call?
662 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
663 if (CallIdx == SkipStart) {
664 // Note that we're skipping calls.
665 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
666 << unsigned(ActiveCalls - Limit);
667 }
668 continue;
669 }
670
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000671 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000672 llvm::raw_svector_ostream Out(Buffer);
673 describeCall(Frame, Out);
674 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
675 }
676}
677
678namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000679 struct ComplexValue {
680 private:
681 bool IsInt;
682
683 public:
684 APSInt IntReal, IntImag;
685 APFloat FloatReal, FloatImag;
686
687 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
688
689 void makeComplexFloat() { IsInt = false; }
690 bool isComplexFloat() const { return !IsInt; }
691 APFloat &getComplexFloatReal() { return FloatReal; }
692 APFloat &getComplexFloatImag() { return FloatImag; }
693
694 void makeComplexInt() { IsInt = true; }
695 bool isComplexInt() const { return IsInt; }
696 APSInt &getComplexIntReal() { return IntReal; }
697 APSInt &getComplexIntImag() { return IntImag; }
698
Richard Smith2e312c82012-03-03 22:46:17 +0000699 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000700 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000701 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000702 else
Richard Smith2e312c82012-03-03 22:46:17 +0000703 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000704 }
Richard Smith2e312c82012-03-03 22:46:17 +0000705 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000706 assert(v.isComplexFloat() || v.isComplexInt());
707 if (v.isComplexFloat()) {
708 makeComplexFloat();
709 FloatReal = v.getComplexFloatReal();
710 FloatImag = v.getComplexFloatImag();
711 } else {
712 makeComplexInt();
713 IntReal = v.getComplexIntReal();
714 IntImag = v.getComplexIntImag();
715 }
716 }
John McCall93d91dc2010-05-07 17:22:02 +0000717 };
John McCall45d55e42010-05-07 21:00:08 +0000718
719 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000720 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000721 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000722 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000723 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000724
Richard Smithce40ad62011-11-12 22:28:03 +0000725 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000726 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000727 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000728 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000729 SubobjectDesignator &getLValueDesignator() { return Designator; }
730 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000731
Richard Smith2e312c82012-03-03 22:46:17 +0000732 void moveInto(APValue &V) const {
733 if (Designator.Invalid)
734 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
735 else
736 V = APValue(Base, Offset, Designator.Entries,
737 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000738 }
Richard Smith2e312c82012-03-03 22:46:17 +0000739 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000740 assert(V.isLValue());
741 Base = V.getLValueBase();
742 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000743 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000744 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000745 }
746
Richard Smithb228a862012-02-15 02:18:13 +0000747 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000748 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000749 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000750 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000751 Designator = SubobjectDesignator(getType(B));
752 }
753
754 // Check that this LValue is not based on a null pointer. If it is, produce
755 // a diagnostic and mark the designator as invalid.
756 bool checkNullPointer(EvalInfo &Info, const Expr *E,
757 CheckSubobjectKind CSK) {
758 if (Designator.Invalid)
759 return false;
760 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000761 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000762 << CSK;
763 Designator.setInvalid();
764 return false;
765 }
766 return true;
767 }
768
769 // Check this LValue refers to an object. If not, set the designator to be
770 // invalid and emit a diagnostic.
771 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000772 // Outside C++11, do not build a designator referring to a subobject of
773 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000774 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000775 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000776 return checkNullPointer(Info, E, CSK) &&
777 Designator.checkSubobject(Info, E, CSK);
778 }
779
780 void addDecl(EvalInfo &Info, const Expr *E,
781 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000782 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
783 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 }
785 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000786 if (checkSubobject(Info, E, CSK_ArrayToPointer))
787 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000788 }
Richard Smith66c96992012-02-18 22:04:06 +0000789 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000790 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
791 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000792 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000793 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000794 if (checkNullPointer(Info, E, CSK_ArrayIndex))
795 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000796 }
John McCall45d55e42010-05-07 21:00:08 +0000797 };
Richard Smith027bf112011-11-17 22:56:20 +0000798
799 struct MemberPtr {
800 MemberPtr() {}
801 explicit MemberPtr(const ValueDecl *Decl) :
802 DeclAndIsDerivedMember(Decl, false), Path() {}
803
804 /// The member or (direct or indirect) field referred to by this member
805 /// pointer, or 0 if this is a null member pointer.
806 const ValueDecl *getDecl() const {
807 return DeclAndIsDerivedMember.getPointer();
808 }
809 /// Is this actually a member of some type derived from the relevant class?
810 bool isDerivedMember() const {
811 return DeclAndIsDerivedMember.getInt();
812 }
813 /// Get the class which the declaration actually lives in.
814 const CXXRecordDecl *getContainingRecord() const {
815 return cast<CXXRecordDecl>(
816 DeclAndIsDerivedMember.getPointer()->getDeclContext());
817 }
818
Richard Smith2e312c82012-03-03 22:46:17 +0000819 void moveInto(APValue &V) const {
820 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000821 }
Richard Smith2e312c82012-03-03 22:46:17 +0000822 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000823 assert(V.isMemberPointer());
824 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
825 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
826 Path.clear();
827 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
828 Path.insert(Path.end(), P.begin(), P.end());
829 }
830
831 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
832 /// whether the member is a member of some class derived from the class type
833 /// of the member pointer.
834 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
835 /// Path - The path of base/derived classes from the member declaration's
836 /// class (exclusive) to the class type of the member pointer (inclusive).
837 SmallVector<const CXXRecordDecl*, 4> Path;
838
839 /// Perform a cast towards the class of the Decl (either up or down the
840 /// hierarchy).
841 bool castBack(const CXXRecordDecl *Class) {
842 assert(!Path.empty());
843 const CXXRecordDecl *Expected;
844 if (Path.size() >= 2)
845 Expected = Path[Path.size() - 2];
846 else
847 Expected = getContainingRecord();
848 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
849 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
850 // if B does not contain the original member and is not a base or
851 // derived class of the class containing the original member, the result
852 // of the cast is undefined.
853 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
854 // (D::*). We consider that to be a language defect.
855 return false;
856 }
857 Path.pop_back();
858 return true;
859 }
860 /// Perform a base-to-derived member pointer cast.
861 bool castToDerived(const CXXRecordDecl *Derived) {
862 if (!getDecl())
863 return true;
864 if (!isDerivedMember()) {
865 Path.push_back(Derived);
866 return true;
867 }
868 if (!castBack(Derived))
869 return false;
870 if (Path.empty())
871 DeclAndIsDerivedMember.setInt(false);
872 return true;
873 }
874 /// Perform a derived-to-base member pointer cast.
875 bool castToBase(const CXXRecordDecl *Base) {
876 if (!getDecl())
877 return true;
878 if (Path.empty())
879 DeclAndIsDerivedMember.setInt(true);
880 if (isDerivedMember()) {
881 Path.push_back(Base);
882 return true;
883 }
884 return castBack(Base);
885 }
886 };
Richard Smith357362d2011-12-13 06:39:58 +0000887
Richard Smith7bb00672012-02-01 01:42:44 +0000888 /// Compare two member pointers, which are assumed to be of the same type.
889 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
890 if (!LHS.getDecl() || !RHS.getDecl())
891 return !LHS.getDecl() && !RHS.getDecl();
892 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
893 return false;
894 return LHS.Path == RHS.Path;
895 }
John McCall93d91dc2010-05-07 17:22:02 +0000896}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000897
Richard Smith2e312c82012-03-03 22:46:17 +0000898static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000899static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
900 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000901 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000902static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
903static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000904static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
905 EvalInfo &Info);
906static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000907static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000908static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000909 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000910static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000911static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +0000912static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000913
914//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000915// Misc utilities
916//===----------------------------------------------------------------------===//
917
Richard Smith84401042013-06-03 05:03:02 +0000918/// Produce a string describing the given constexpr call.
919static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
920 unsigned ArgIndex = 0;
921 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
922 !isa<CXXConstructorDecl>(Frame->Callee) &&
923 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
924
925 if (!IsMemberCall)
926 Out << *Frame->Callee << '(';
927
928 if (Frame->This && IsMemberCall) {
929 APValue Val;
930 Frame->This->moveInto(Val);
931 Val.printPretty(Out, Frame->Info.Ctx,
932 Frame->This->Designator.MostDerivedType);
933 // FIXME: Add parens around Val if needed.
934 Out << "->" << *Frame->Callee << '(';
935 IsMemberCall = false;
936 }
937
938 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
939 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
940 if (ArgIndex > (unsigned)IsMemberCall)
941 Out << ", ";
942
943 const ParmVarDecl *Param = *I;
944 const APValue &Arg = Frame->Arguments[ArgIndex];
945 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
946
947 if (ArgIndex == 0 && IsMemberCall)
948 Out << "->" << *Frame->Callee << '(';
949 }
950
951 Out << ')';
952}
953
Richard Smithd9f663b2013-04-22 15:31:51 +0000954/// Evaluate an expression to see if it had side-effects, and discard its
955/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000956/// \return \c true if the caller should keep evaluating.
957static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000958 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000959 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000960 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000961 return Info.keepEvaluatingAfterFailure();
962 }
963 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000964}
965
Richard Smith861b5b52013-05-07 23:34:45 +0000966/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
967/// return its existing value.
968static int64_t getExtValue(const APSInt &Value) {
969 return Value.isSigned() ? Value.getSExtValue()
970 : static_cast<int64_t>(Value.getZExtValue());
971}
972
Richard Smithd62306a2011-11-10 06:34:14 +0000973/// Should this call expression be treated as a string literal?
974static bool IsStringLiteralCall(const CallExpr *E) {
975 unsigned Builtin = E->isBuiltinCall();
976 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
977 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
978}
979
Richard Smithce40ad62011-11-12 22:28:03 +0000980static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000981 // C++11 [expr.const]p3 An address constant expression is a prvalue core
982 // constant expression of pointer type that evaluates to...
983
984 // ... a null pointer value, or a prvalue core constant expression of type
985 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000986 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000987
Richard Smithce40ad62011-11-12 22:28:03 +0000988 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
989 // ... the address of an object with static storage duration,
990 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
991 return VD->hasGlobalStorage();
992 // ... the address of a function,
993 return isa<FunctionDecl>(D);
994 }
995
996 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000997 switch (E->getStmtClass()) {
998 default:
999 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001000 case Expr::CompoundLiteralExprClass: {
1001 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1002 return CLE->isFileScope() && CLE->isLValue();
1003 }
Richard Smithd62306a2011-11-10 06:34:14 +00001004 // A string literal has static storage duration.
1005 case Expr::StringLiteralClass:
1006 case Expr::PredefinedExprClass:
1007 case Expr::ObjCStringLiteralClass:
1008 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001009 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001010 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001011 return true;
1012 case Expr::CallExprClass:
1013 return IsStringLiteralCall(cast<CallExpr>(E));
1014 // For GCC compatibility, &&label has static storage duration.
1015 case Expr::AddrLabelExprClass:
1016 return true;
1017 // A Block literal expression may be used as the initialization value for
1018 // Block variables at global or local static scope.
1019 case Expr::BlockExprClass:
1020 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001021 case Expr::ImplicitValueInitExprClass:
1022 // FIXME:
1023 // We can never form an lvalue with an implicit value initialization as its
1024 // base through expression evaluation, so these only appear in one case: the
1025 // implicit variable declaration we invent when checking whether a constexpr
1026 // constructor can produce a constant expression. We must assume that such
1027 // an expression might be a global lvalue.
1028 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001029 }
John McCall95007602010-05-10 23:27:23 +00001030}
1031
Richard Smithb228a862012-02-15 02:18:13 +00001032static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1033 assert(Base && "no location for a null lvalue");
1034 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1035 if (VD)
1036 Info.Note(VD->getLocation(), diag::note_declared_at);
1037 else
Ted Kremenek28831752012-08-23 20:46:57 +00001038 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001039 diag::note_constexpr_temporary_here);
1040}
1041
Richard Smith80815602011-11-07 05:07:52 +00001042/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001043/// value for an address or reference constant expression. Return true if we
1044/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001045static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1046 QualType Type, const LValue &LVal) {
1047 bool IsReferenceType = Type->isReferenceType();
1048
Richard Smith357362d2011-12-13 06:39:58 +00001049 APValue::LValueBase Base = LVal.getLValueBase();
1050 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1051
Richard Smith0dea49e2012-02-18 04:58:18 +00001052 // Check that the object is a global. Note that the fake 'this' object we
1053 // manufacture when checking potential constant expressions is conservatively
1054 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001055 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001056 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001057 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001058 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1059 << IsReferenceType << !Designator.Entries.empty()
1060 << !!VD << VD;
1061 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001062 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001063 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001064 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001065 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001066 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001067 }
Richard Smithb228a862012-02-15 02:18:13 +00001068 assert((Info.CheckingPotentialConstantExpression ||
1069 LVal.getLValueCallIndex() == 0) &&
1070 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001071
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001072 // Check if this is a thread-local variable.
1073 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1074 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001075 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001076 return false;
1077 }
1078 }
1079
Richard Smitha8105bc2012-01-06 16:39:00 +00001080 // Allow address constant expressions to be past-the-end pointers. This is
1081 // an extension: the standard requires them to point to an object.
1082 if (!IsReferenceType)
1083 return true;
1084
1085 // A reference constant expression must refer to an object.
1086 if (!Base) {
1087 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001088 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001089 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001090 }
1091
Richard Smith357362d2011-12-13 06:39:58 +00001092 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001093 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001094 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001095 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001096 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001097 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001098 }
1099
Richard Smith80815602011-11-07 05:07:52 +00001100 return true;
1101}
1102
Richard Smithfddd3842011-12-30 21:15:51 +00001103/// Check that this core constant expression is of literal type, and if not,
1104/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001105static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1106 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001107 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001108 return true;
1109
Richard Smith7525ff62013-05-09 07:14:00 +00001110 // C++1y: A constant initializer for an object o [...] may also invoke
1111 // constexpr constructors for o and its subobjects even if those objects
1112 // are of non-literal class types.
1113 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001114 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001115 return true;
1116
Richard Smithfddd3842011-12-30 21:15:51 +00001117 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001118 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001119 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001120 << E->getType();
1121 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001122 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001123 return false;
1124}
1125
Richard Smith0b0a0b62011-10-29 20:57:55 +00001126/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001127/// constant expression. If not, report an appropriate diagnostic. Does not
1128/// check that the expression is of literal type.
1129static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1130 QualType Type, const APValue &Value) {
1131 // Core issue 1454: For a literal constant expression of array or class type,
1132 // each subobject of its value shall have been initialized by a constant
1133 // expression.
1134 if (Value.isArray()) {
1135 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1136 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1137 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1138 Value.getArrayInitializedElt(I)))
1139 return false;
1140 }
1141 if (!Value.hasArrayFiller())
1142 return true;
1143 return CheckConstantExpression(Info, DiagLoc, EltTy,
1144 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001145 }
Richard Smithb228a862012-02-15 02:18:13 +00001146 if (Value.isUnion() && Value.getUnionField()) {
1147 return CheckConstantExpression(Info, DiagLoc,
1148 Value.getUnionField()->getType(),
1149 Value.getUnionValue());
1150 }
1151 if (Value.isStruct()) {
1152 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1153 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1154 unsigned BaseIndex = 0;
1155 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1156 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1157 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1158 Value.getStructBase(BaseIndex)))
1159 return false;
1160 }
1161 }
1162 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1163 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001164 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1165 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001166 return false;
1167 }
1168 }
1169
1170 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001171 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001172 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001173 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1174 }
1175
1176 // Everything else is fine.
1177 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001178}
1179
Richard Smith83c68212011-10-31 05:11:32 +00001180const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001181 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001182}
1183
1184static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001185 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001186}
1187
Richard Smithcecf1842011-11-01 21:06:14 +00001188static bool IsWeakLValue(const LValue &Value) {
1189 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001190 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001191}
1192
Richard Smith2e312c82012-03-03 22:46:17 +00001193static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001194 // A null base expression indicates a null pointer. These are always
1195 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001196 if (!Value.getLValueBase()) {
1197 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001198 return true;
1199 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001200
Richard Smith027bf112011-11-17 22:56:20 +00001201 // We have a non-null base. These are generally known to be true, but if it's
1202 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001203 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001204 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001205 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001206}
1207
Richard Smith2e312c82012-03-03 22:46:17 +00001208static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001209 switch (Val.getKind()) {
1210 case APValue::Uninitialized:
1211 return false;
1212 case APValue::Int:
1213 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001214 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001215 case APValue::Float:
1216 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001217 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001218 case APValue::ComplexInt:
1219 Result = Val.getComplexIntReal().getBoolValue() ||
1220 Val.getComplexIntImag().getBoolValue();
1221 return true;
1222 case APValue::ComplexFloat:
1223 Result = !Val.getComplexFloatReal().isZero() ||
1224 !Val.getComplexFloatImag().isZero();
1225 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001226 case APValue::LValue:
1227 return EvalPointerValueAsBool(Val, Result);
1228 case APValue::MemberPointer:
1229 Result = Val.getMemberPointerDecl();
1230 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001231 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001232 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001233 case APValue::Struct:
1234 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001235 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001236 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001237 }
1238
Richard Smith11562c52011-10-28 17:51:58 +00001239 llvm_unreachable("unknown APValue kind");
1240}
1241
1242static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1243 EvalInfo &Info) {
1244 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001245 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001246 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001247 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001248 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001249}
1250
Richard Smith357362d2011-12-13 06:39:58 +00001251template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001252static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001253 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001254 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001255 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001256}
1257
1258static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1259 QualType SrcType, const APFloat &Value,
1260 QualType DestType, APSInt &Result) {
1261 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001262 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001263 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001264
Richard Smith357362d2011-12-13 06:39:58 +00001265 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001266 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001267 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1268 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001269 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001270 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001271}
1272
Richard Smith357362d2011-12-13 06:39:58 +00001273static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1274 QualType SrcType, QualType DestType,
1275 APFloat &Result) {
1276 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001277 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001278 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1279 APFloat::rmNearestTiesToEven, &ignored)
1280 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001281 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001282 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001283}
1284
Richard Smith911e1422012-01-30 22:27:01 +00001285static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1286 QualType DestType, QualType SrcType,
1287 APSInt &Value) {
1288 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001289 APSInt Result = Value;
1290 // Figure out if this is a truncate, extend or noop cast.
1291 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001292 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001293 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001294 return Result;
1295}
1296
Richard Smith357362d2011-12-13 06:39:58 +00001297static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1298 QualType SrcType, const APSInt &Value,
1299 QualType DestType, APFloat &Result) {
1300 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1301 if (Result.convertFromAPInt(Value, Value.isSigned(),
1302 APFloat::rmNearestTiesToEven)
1303 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001304 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001305 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001306}
1307
Eli Friedman803acb32011-12-22 03:51:45 +00001308static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1309 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001310 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001311 if (!Evaluate(SVal, Info, E))
1312 return false;
1313 if (SVal.isInt()) {
1314 Res = SVal.getInt();
1315 return true;
1316 }
1317 if (SVal.isFloat()) {
1318 Res = SVal.getFloat().bitcastToAPInt();
1319 return true;
1320 }
1321 if (SVal.isVector()) {
1322 QualType VecTy = E->getType();
1323 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1324 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1325 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1326 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1327 Res = llvm::APInt::getNullValue(VecSize);
1328 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1329 APValue &Elt = SVal.getVectorElt(i);
1330 llvm::APInt EltAsInt;
1331 if (Elt.isInt()) {
1332 EltAsInt = Elt.getInt();
1333 } else if (Elt.isFloat()) {
1334 EltAsInt = Elt.getFloat().bitcastToAPInt();
1335 } else {
1336 // Don't try to handle vectors of anything other than int or float
1337 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001338 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001339 return false;
1340 }
1341 unsigned BaseEltSize = EltAsInt.getBitWidth();
1342 if (BigEndian)
1343 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1344 else
1345 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1346 }
1347 return true;
1348 }
1349 // Give up if the input isn't an int, float, or vector. For example, we
1350 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001351 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001352 return false;
1353}
1354
Richard Smith43e77732013-05-07 04:50:00 +00001355/// Perform the given integer operation, which is known to need at most BitWidth
1356/// bits, and check for overflow in the original type (if that type was not an
1357/// unsigned type).
1358template<typename Operation>
1359static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1360 const APSInt &LHS, const APSInt &RHS,
1361 unsigned BitWidth, Operation Op) {
1362 if (LHS.isUnsigned())
1363 return Op(LHS, RHS);
1364
1365 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1366 APSInt Result = Value.trunc(LHS.getBitWidth());
1367 if (Result.extend(BitWidth) != Value) {
1368 if (Info.getIntOverflowCheckMode())
1369 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1370 diag::warn_integer_constant_overflow)
1371 << Result.toString(10) << E->getType();
1372 else
1373 HandleOverflow(Info, E, Value, E->getType());
1374 }
1375 return Result;
1376}
1377
1378/// Perform the given binary integer operation.
1379static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1380 BinaryOperatorKind Opcode, APSInt RHS,
1381 APSInt &Result) {
1382 switch (Opcode) {
1383 default:
1384 Info.Diag(E);
1385 return false;
1386 case BO_Mul:
1387 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1388 std::multiplies<APSInt>());
1389 return true;
1390 case BO_Add:
1391 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1392 std::plus<APSInt>());
1393 return true;
1394 case BO_Sub:
1395 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1396 std::minus<APSInt>());
1397 return true;
1398 case BO_And: Result = LHS & RHS; return true;
1399 case BO_Xor: Result = LHS ^ RHS; return true;
1400 case BO_Or: Result = LHS | RHS; return true;
1401 case BO_Div:
1402 case BO_Rem:
1403 if (RHS == 0) {
1404 Info.Diag(E, diag::note_expr_divide_by_zero);
1405 return false;
1406 }
1407 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1408 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1409 LHS.isSigned() && LHS.isMinSignedValue())
1410 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1411 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1412 return true;
1413 case BO_Shl: {
1414 if (Info.getLangOpts().OpenCL)
1415 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1416 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1417 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1418 RHS.isUnsigned());
1419 else if (RHS.isSigned() && RHS.isNegative()) {
1420 // During constant-folding, a negative shift is an opposite shift. Such
1421 // a shift is not a constant expression.
1422 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1423 RHS = -RHS;
1424 goto shift_right;
1425 }
1426 shift_left:
1427 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1428 // the shifted type.
1429 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1430 if (SA != RHS) {
1431 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1432 << RHS << E->getType() << LHS.getBitWidth();
1433 } else if (LHS.isSigned()) {
1434 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1435 // operand, and must not overflow the corresponding unsigned type.
1436 if (LHS.isNegative())
1437 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1438 else if (LHS.countLeadingZeros() < SA)
1439 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1440 }
1441 Result = LHS << SA;
1442 return true;
1443 }
1444 case BO_Shr: {
1445 if (Info.getLangOpts().OpenCL)
1446 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1447 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1448 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1449 RHS.isUnsigned());
1450 else if (RHS.isSigned() && RHS.isNegative()) {
1451 // During constant-folding, a negative shift is an opposite shift. Such a
1452 // shift is not a constant expression.
1453 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1454 RHS = -RHS;
1455 goto shift_left;
1456 }
1457 shift_right:
1458 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1459 // shifted type.
1460 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1461 if (SA != RHS)
1462 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1463 << RHS << E->getType() << LHS.getBitWidth();
1464 Result = LHS >> SA;
1465 return true;
1466 }
1467
1468 case BO_LT: Result = LHS < RHS; return true;
1469 case BO_GT: Result = LHS > RHS; return true;
1470 case BO_LE: Result = LHS <= RHS; return true;
1471 case BO_GE: Result = LHS >= RHS; return true;
1472 case BO_EQ: Result = LHS == RHS; return true;
1473 case BO_NE: Result = LHS != RHS; return true;
1474 }
1475}
1476
Richard Smith861b5b52013-05-07 23:34:45 +00001477/// Perform the given binary floating-point operation, in-place, on LHS.
1478static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1479 APFloat &LHS, BinaryOperatorKind Opcode,
1480 const APFloat &RHS) {
1481 switch (Opcode) {
1482 default:
1483 Info.Diag(E);
1484 return false;
1485 case BO_Mul:
1486 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1487 break;
1488 case BO_Add:
1489 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1490 break;
1491 case BO_Sub:
1492 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1493 break;
1494 case BO_Div:
1495 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1496 break;
1497 }
1498
1499 if (LHS.isInfinity() || LHS.isNaN())
1500 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1501 return true;
1502}
1503
Richard Smitha8105bc2012-01-06 16:39:00 +00001504/// Cast an lvalue referring to a base subobject to a derived class, by
1505/// truncating the lvalue's path to the given length.
1506static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1507 const RecordDecl *TruncatedType,
1508 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001509 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001510
1511 // Check we actually point to a derived class object.
1512 if (TruncatedElements == D.Entries.size())
1513 return true;
1514 assert(TruncatedElements >= D.MostDerivedPathLength &&
1515 "not casting to a derived class");
1516 if (!Result.checkSubobject(Info, E, CSK_Derived))
1517 return false;
1518
1519 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001520 const RecordDecl *RD = TruncatedType;
1521 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001522 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001523 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1524 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001525 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001526 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001527 else
Richard Smithd62306a2011-11-10 06:34:14 +00001528 Result.Offset -= Layout.getBaseClassOffset(Base);
1529 RD = Base;
1530 }
Richard Smith027bf112011-11-17 22:56:20 +00001531 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001532 return true;
1533}
1534
John McCalld7bca762012-05-01 00:38:49 +00001535static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001536 const CXXRecordDecl *Derived,
1537 const CXXRecordDecl *Base,
1538 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001539 if (!RL) {
1540 if (Derived->isInvalidDecl()) return false;
1541 RL = &Info.Ctx.getASTRecordLayout(Derived);
1542 }
1543
Richard Smithd62306a2011-11-10 06:34:14 +00001544 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001545 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001546 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001547}
1548
Richard Smitha8105bc2012-01-06 16:39:00 +00001549static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001550 const CXXRecordDecl *DerivedDecl,
1551 const CXXBaseSpecifier *Base) {
1552 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1553
John McCalld7bca762012-05-01 00:38:49 +00001554 if (!Base->isVirtual())
1555 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001556
Richard Smitha8105bc2012-01-06 16:39:00 +00001557 SubobjectDesignator &D = Obj.Designator;
1558 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001559 return false;
1560
Richard Smitha8105bc2012-01-06 16:39:00 +00001561 // Extract most-derived object and corresponding type.
1562 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1563 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1564 return false;
1565
1566 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001567 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001568 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1569 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001570 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001571 return true;
1572}
1573
Richard Smith84401042013-06-03 05:03:02 +00001574static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1575 QualType Type, LValue &Result) {
1576 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1577 PathE = E->path_end();
1578 PathI != PathE; ++PathI) {
1579 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1580 *PathI))
1581 return false;
1582 Type = (*PathI)->getType();
1583 }
1584 return true;
1585}
1586
Richard Smithd62306a2011-11-10 06:34:14 +00001587/// Update LVal to refer to the given field, which must be a member of the type
1588/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001589static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001590 const FieldDecl *FD,
1591 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001592 if (!RL) {
1593 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001594 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001595 }
Richard Smithd62306a2011-11-10 06:34:14 +00001596
1597 unsigned I = FD->getFieldIndex();
1598 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001599 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001600 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001601}
1602
Richard Smith1b78b3d2012-01-25 22:15:11 +00001603/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001604static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001605 LValue &LVal,
1606 const IndirectFieldDecl *IFD) {
1607 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1608 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001609 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1610 return false;
1611 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001612}
1613
Richard Smithd62306a2011-11-10 06:34:14 +00001614/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001615static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1616 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001617 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1618 // extension.
1619 if (Type->isVoidType() || Type->isFunctionType()) {
1620 Size = CharUnits::One();
1621 return true;
1622 }
1623
1624 if (!Type->isConstantSizeType()) {
1625 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001626 // FIXME: Better diagnostic.
1627 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001628 return false;
1629 }
1630
1631 Size = Info.Ctx.getTypeSizeInChars(Type);
1632 return true;
1633}
1634
1635/// Update a pointer value to model pointer arithmetic.
1636/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001637/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001638/// \param LVal - The pointer value to be updated.
1639/// \param EltTy - The pointee type represented by LVal.
1640/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001641static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1642 LValue &LVal, QualType EltTy,
1643 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001644 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001645 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001646 return false;
1647
1648 // Compute the new offset in the appropriate width.
1649 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001650 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001651 return true;
1652}
1653
Richard Smith66c96992012-02-18 22:04:06 +00001654/// Update an lvalue to refer to a component of a complex number.
1655/// \param Info - Information about the ongoing evaluation.
1656/// \param LVal - The lvalue to be updated.
1657/// \param EltTy - The complex number's component type.
1658/// \param Imag - False for the real component, true for the imaginary.
1659static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1660 LValue &LVal, QualType EltTy,
1661 bool Imag) {
1662 if (Imag) {
1663 CharUnits SizeOfComponent;
1664 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1665 return false;
1666 LVal.Offset += SizeOfComponent;
1667 }
1668 LVal.addComplex(Info, E, EltTy, Imag);
1669 return true;
1670}
1671
Richard Smith27908702011-10-24 17:54:18 +00001672/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001673///
1674/// \param Info Information about the ongoing evaluation.
1675/// \param E An expression to be used when printing diagnostics.
1676/// \param VD The variable whose initializer should be obtained.
1677/// \param Frame The frame in which the variable was created. Must be null
1678/// if this variable is not local to the evaluation.
1679/// \param Result Filled in with a pointer to the value of the variable.
1680static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1681 const VarDecl *VD, CallStackFrame *Frame,
1682 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001683 // If this is a parameter to an active constexpr function call, perform
1684 // argument substitution.
1685 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001686 // Assume arguments of a potential constant expression are unknown
1687 // constant expressions.
1688 if (Info.CheckingPotentialConstantExpression)
1689 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001690 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001691 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001692 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001693 }
Richard Smith3229b742013-05-05 21:17:10 +00001694 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001695 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001696 }
Richard Smith27908702011-10-24 17:54:18 +00001697
Richard Smithd9f663b2013-04-22 15:31:51 +00001698 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001699 if (Frame) {
1700 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001701 // If we've carried on past an unevaluatable local variable initializer,
1702 // we can't go any further. This can happen during potential constant
1703 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001704 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001705 }
1706
Richard Smithd0b4dd62011-12-19 06:19:21 +00001707 // Dig out the initializer, and use the declaration which it's attached to.
1708 const Expr *Init = VD->getAnyInitializer(VD);
1709 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001710 // If we're checking a potential constant expression, the variable could be
1711 // initialized later.
1712 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001713 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001714 return false;
1715 }
1716
Richard Smithd62306a2011-11-10 06:34:14 +00001717 // If we're currently evaluating the initializer of this declaration, use that
1718 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001719 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001720 Result = Info.EvaluatingDeclValue;
1721 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001722 }
1723
Richard Smithcecf1842011-11-01 21:06:14 +00001724 // Never evaluate the initializer of a weak variable. We can't be sure that
1725 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001726 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001727 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001728 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001729 }
Richard Smithcecf1842011-11-01 21:06:14 +00001730
Richard Smithd0b4dd62011-12-19 06:19:21 +00001731 // Check that we can fold the initializer. In C++, we will have already done
1732 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001733 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001734 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001735 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001736 Notes.size() + 1) << VD;
1737 Info.Note(VD->getLocation(), diag::note_declared_at);
1738 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001739 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001740 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001741 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001742 Notes.size() + 1) << VD;
1743 Info.Note(VD->getLocation(), diag::note_declared_at);
1744 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 }
Richard Smith27908702011-10-24 17:54:18 +00001746
Richard Smith3229b742013-05-05 21:17:10 +00001747 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001748 return true;
Richard Smith27908702011-10-24 17:54:18 +00001749}
1750
Richard Smith11562c52011-10-28 17:51:58 +00001751static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001752 Qualifiers Quals = T.getQualifiers();
1753 return Quals.hasConst() && !Quals.hasVolatile();
1754}
1755
Richard Smithe97cbd72011-11-11 04:05:33 +00001756/// Get the base index of the given base class within an APValue representing
1757/// the given derived class.
1758static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1759 const CXXRecordDecl *Base) {
1760 Base = Base->getCanonicalDecl();
1761 unsigned Index = 0;
1762 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1763 E = Derived->bases_end(); I != E; ++I, ++Index) {
1764 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1765 return Index;
1766 }
1767
1768 llvm_unreachable("base class missing from derived class's bases list");
1769}
1770
Richard Smith3da88fa2013-04-26 14:36:30 +00001771/// Extract the value of a character from a string literal.
1772static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1773 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001774 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001775 const StringLiteral *S = cast<StringLiteral>(Lit);
1776 const ConstantArrayType *CAT =
1777 Info.Ctx.getAsConstantArrayType(S->getType());
1778 assert(CAT && "string literal isn't an array");
1779 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001780 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001781
1782 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001783 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001784 if (Index < S->getLength())
1785 Value = S->getCodeUnit(Index);
1786 return Value;
1787}
1788
Richard Smith3da88fa2013-04-26 14:36:30 +00001789// Expand a string literal into an array of characters.
1790static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1791 APValue &Result) {
1792 const StringLiteral *S = cast<StringLiteral>(Lit);
1793 const ConstantArrayType *CAT =
1794 Info.Ctx.getAsConstantArrayType(S->getType());
1795 assert(CAT && "string literal isn't an array");
1796 QualType CharType = CAT->getElementType();
1797 assert(CharType->isIntegerType() && "unexpected character type");
1798
1799 unsigned Elts = CAT->getSize().getZExtValue();
1800 Result = APValue(APValue::UninitArray(),
1801 std::min(S->getLength(), Elts), Elts);
1802 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1803 CharType->isUnsignedIntegerType());
1804 if (Result.hasArrayFiller())
1805 Result.getArrayFiller() = APValue(Value);
1806 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1807 Value = S->getCodeUnit(I);
1808 Result.getArrayInitializedElt(I) = APValue(Value);
1809 }
1810}
1811
1812// Expand an array so that it has more than Index filled elements.
1813static void expandArray(APValue &Array, unsigned Index) {
1814 unsigned Size = Array.getArraySize();
1815 assert(Index < Size);
1816
1817 // Always at least double the number of elements for which we store a value.
1818 unsigned OldElts = Array.getArrayInitializedElts();
1819 unsigned NewElts = std::max(Index+1, OldElts * 2);
1820 NewElts = std::min(Size, std::max(NewElts, 8u));
1821
1822 // Copy the data across.
1823 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1824 for (unsigned I = 0; I != OldElts; ++I)
1825 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1826 for (unsigned I = OldElts; I != NewElts; ++I)
1827 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1828 if (NewValue.hasArrayFiller())
1829 NewValue.getArrayFiller() = Array.getArrayFiller();
1830 Array.swap(NewValue);
1831}
1832
Richard Smith861b5b52013-05-07 23:34:45 +00001833/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001834enum AccessKinds {
1835 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001836 AK_Assign,
1837 AK_Increment,
1838 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001839};
1840
Richard Smith3229b742013-05-05 21:17:10 +00001841/// A handle to a complete object (an object that is not a subobject of
1842/// another object).
1843struct CompleteObject {
1844 /// The value of the complete object.
1845 APValue *Value;
1846 /// The type of the complete object.
1847 QualType Type;
1848
1849 CompleteObject() : Value(0) {}
1850 CompleteObject(APValue *Value, QualType Type)
1851 : Value(Value), Type(Type) {
1852 assert(Value && "missing value for complete object");
1853 }
1854
David Blaikie7d170102013-05-15 07:37:26 +00001855 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001856};
1857
Richard Smith3da88fa2013-04-26 14:36:30 +00001858/// Find the designated sub-object of an rvalue.
1859template<typename SubobjectHandler>
1860typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001861findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001862 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001863 if (Sub.Invalid)
1864 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001865 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001866 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001867 if (Info.getLangOpts().CPlusPlus11)
1868 Info.Diag(E, diag::note_constexpr_access_past_end)
1869 << handler.AccessKind;
1870 else
1871 Info.Diag(E);
1872 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001873 }
Richard Smith6804be52011-11-11 08:28:03 +00001874 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001875 return handler.found(*Obj.Value, Obj.Type);
1876 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001877 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001878 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001879
Richard Smith3229b742013-05-05 21:17:10 +00001880 APValue *O = Obj.Value;
1881 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001882 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001883 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001884 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001885 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001886 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001887 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001888 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001889 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001890 // Note, it should not be possible to form a pointer with a valid
1891 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001892 if (Info.getLangOpts().CPlusPlus11)
1893 Info.Diag(E, diag::note_constexpr_access_past_end)
1894 << handler.AccessKind;
1895 else
1896 Info.Diag(E);
1897 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001898 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001899
1900 ObjType = CAT->getElementType();
1901
Richard Smith14a94132012-02-17 03:35:37 +00001902 // An array object is represented as either an Array APValue or as an
1903 // LValue which refers to a string literal.
1904 if (O->isLValue()) {
1905 assert(I == N - 1 && "extracting subobject of character?");
1906 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001907 if (handler.AccessKind != AK_Read)
1908 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1909 *O);
1910 else
1911 return handler.foundString(*O, ObjType, Index);
1912 }
1913
1914 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001915 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001916 else if (handler.AccessKind != AK_Read) {
1917 expandArray(*O, Index);
1918 O = &O->getArrayInitializedElt(Index);
1919 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001920 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001921 } else if (ObjType->isAnyComplexType()) {
1922 // Next subobject is a complex number.
1923 uint64_t Index = Sub.Entries[I].ArrayIndex;
1924 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001925 if (Info.getLangOpts().CPlusPlus11)
1926 Info.Diag(E, diag::note_constexpr_access_past_end)
1927 << handler.AccessKind;
1928 else
1929 Info.Diag(E);
1930 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001931 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001932
1933 bool WasConstQualified = ObjType.isConstQualified();
1934 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1935 if (WasConstQualified)
1936 ObjType.addConst();
1937
Richard Smith66c96992012-02-18 22:04:06 +00001938 assert(I == N - 1 && "extracting subobject of scalar?");
1939 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001940 return handler.found(Index ? O->getComplexIntImag()
1941 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001942 } else {
1943 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001944 return handler.found(Index ? O->getComplexFloatImag()
1945 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001946 }
Richard Smithd62306a2011-11-10 06:34:14 +00001947 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001948 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001949 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001950 << Field;
1951 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001952 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001953 }
1954
Richard Smithd62306a2011-11-10 06:34:14 +00001955 // Next subobject is a class, struct or union field.
1956 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1957 if (RD->isUnion()) {
1958 const FieldDecl *UnionField = O->getUnionField();
1959 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001960 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1962 << handler.AccessKind << Field << !UnionField << UnionField;
1963 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001964 }
Richard Smithd62306a2011-11-10 06:34:14 +00001965 O = &O->getUnionValue();
1966 } else
1967 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001968
1969 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001970 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001971 if (WasConstQualified && !Field->isMutable())
1972 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001973
1974 if (ObjType.isVolatileQualified()) {
1975 if (Info.getLangOpts().CPlusPlus) {
1976 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001977 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1978 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001979 Info.Note(Field->getLocation(), diag::note_declared_at);
1980 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001981 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001982 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001983 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001984 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001985 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001986 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001987 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1988 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1989 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001990
1991 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001992 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001993 if (WasConstQualified)
1994 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001995 }
Richard Smithd62306a2011-11-10 06:34:14 +00001996
Richard Smithf57d8cb2011-12-09 22:58:01 +00001997 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001998 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001999 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2000 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002001 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002002 }
2003
Richard Smith3da88fa2013-04-26 14:36:30 +00002004 return handler.found(*O, ObjType);
2005}
2006
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002007namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002008struct ExtractSubobjectHandler {
2009 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002010 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002011
2012 static const AccessKinds AccessKind = AK_Read;
2013
2014 typedef bool result_type;
2015 bool failed() { return false; }
2016 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002017 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002018 return true;
2019 }
2020 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002021 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002022 return true;
2023 }
2024 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002025 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002026 return true;
2027 }
2028 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002029 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002030 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2031 return true;
2032 }
2033};
Richard Smith3229b742013-05-05 21:17:10 +00002034} // end anonymous namespace
2035
Richard Smith3da88fa2013-04-26 14:36:30 +00002036const AccessKinds ExtractSubobjectHandler::AccessKind;
2037
2038/// Extract the designated sub-object of an rvalue.
2039static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002040 const CompleteObject &Obj,
2041 const SubobjectDesignator &Sub,
2042 APValue &Result) {
2043 ExtractSubobjectHandler Handler = { Info, Result };
2044 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002045}
2046
Richard Smith3229b742013-05-05 21:17:10 +00002047namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002048struct ModifySubobjectHandler {
2049 EvalInfo &Info;
2050 APValue &NewVal;
2051 const Expr *E;
2052
2053 typedef bool result_type;
2054 static const AccessKinds AccessKind = AK_Assign;
2055
2056 bool checkConst(QualType QT) {
2057 // Assigning to a const object has undefined behavior.
2058 if (QT.isConstQualified()) {
2059 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2060 return false;
2061 }
2062 return true;
2063 }
2064
2065 bool failed() { return false; }
2066 bool found(APValue &Subobj, QualType SubobjType) {
2067 if (!checkConst(SubobjType))
2068 return false;
2069 // We've been given ownership of NewVal, so just swap it in.
2070 Subobj.swap(NewVal);
2071 return true;
2072 }
2073 bool found(APSInt &Value, QualType SubobjType) {
2074 if (!checkConst(SubobjType))
2075 return false;
2076 if (!NewVal.isInt()) {
2077 // Maybe trying to write a cast pointer value into a complex?
2078 Info.Diag(E);
2079 return false;
2080 }
2081 Value = NewVal.getInt();
2082 return true;
2083 }
2084 bool found(APFloat &Value, QualType SubobjType) {
2085 if (!checkConst(SubobjType))
2086 return false;
2087 Value = NewVal.getFloat();
2088 return true;
2089 }
2090 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2091 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2092 }
2093};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002094} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002095
Richard Smith3229b742013-05-05 21:17:10 +00002096const AccessKinds ModifySubobjectHandler::AccessKind;
2097
Richard Smith3da88fa2013-04-26 14:36:30 +00002098/// Update the designated sub-object of an rvalue to the given value.
2099static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002100 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002101 const SubobjectDesignator &Sub,
2102 APValue &NewVal) {
2103 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002104 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002105}
2106
Richard Smith84f6dcf2012-02-02 01:16:57 +00002107/// Find the position where two subobject designators diverge, or equivalently
2108/// the length of the common initial subsequence.
2109static unsigned FindDesignatorMismatch(QualType ObjType,
2110 const SubobjectDesignator &A,
2111 const SubobjectDesignator &B,
2112 bool &WasArrayIndex) {
2113 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2114 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002115 if (!ObjType.isNull() &&
2116 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002117 // Next subobject is an array element.
2118 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2119 WasArrayIndex = true;
2120 return I;
2121 }
Richard Smith66c96992012-02-18 22:04:06 +00002122 if (ObjType->isAnyComplexType())
2123 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2124 else
2125 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002126 } else {
2127 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2128 WasArrayIndex = false;
2129 return I;
2130 }
2131 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2132 // Next subobject is a field.
2133 ObjType = FD->getType();
2134 else
2135 // Next subobject is a base class.
2136 ObjType = QualType();
2137 }
2138 }
2139 WasArrayIndex = false;
2140 return I;
2141}
2142
2143/// Determine whether the given subobject designators refer to elements of the
2144/// same array object.
2145static bool AreElementsOfSameArray(QualType ObjType,
2146 const SubobjectDesignator &A,
2147 const SubobjectDesignator &B) {
2148 if (A.Entries.size() != B.Entries.size())
2149 return false;
2150
2151 bool IsArray = A.MostDerivedArraySize != 0;
2152 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2153 // A is a subobject of the array element.
2154 return false;
2155
2156 // If A (and B) designates an array element, the last entry will be the array
2157 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2158 // of length 1' case, and the entire path must match.
2159 bool WasArrayIndex;
2160 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2161 return CommonLength >= A.Entries.size() - IsArray;
2162}
2163
Richard Smith3229b742013-05-05 21:17:10 +00002164/// Find the complete object to which an LValue refers.
2165CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2166 const LValue &LVal, QualType LValType) {
2167 if (!LVal.Base) {
2168 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2169 return CompleteObject();
2170 }
2171
2172 CallStackFrame *Frame = 0;
2173 if (LVal.CallIndex) {
2174 Frame = Info.getCallFrame(LVal.CallIndex);
2175 if (!Frame) {
2176 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2177 << AK << LVal.Base.is<const ValueDecl*>();
2178 NoteLValueLocation(Info, LVal.Base);
2179 return CompleteObject();
2180 }
Richard Smith3229b742013-05-05 21:17:10 +00002181 }
2182
2183 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2184 // is not a constant expression (even if the object is non-volatile). We also
2185 // apply this rule to C++98, in order to conform to the expected 'volatile'
2186 // semantics.
2187 if (LValType.isVolatileQualified()) {
2188 if (Info.getLangOpts().CPlusPlus)
2189 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2190 << AK << LValType;
2191 else
2192 Info.Diag(E);
2193 return CompleteObject();
2194 }
2195
2196 // Compute value storage location and type of base object.
2197 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002198 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002199
2200 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2201 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2202 // In C++11, constexpr, non-volatile variables initialized with constant
2203 // expressions are constant expressions too. Inside constexpr functions,
2204 // parameters are constant expressions even if they're non-const.
2205 // In C++1y, objects local to a constant expression (those with a Frame) are
2206 // both readable and writable inside constant expressions.
2207 // In C, such things can also be folded, although they are not ICEs.
2208 const VarDecl *VD = dyn_cast<VarDecl>(D);
2209 if (VD) {
2210 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2211 VD = VDef;
2212 }
2213 if (!VD || VD->isInvalidDecl()) {
2214 Info.Diag(E);
2215 return CompleteObject();
2216 }
2217
2218 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002219 if (BaseType.isVolatileQualified()) {
2220 if (Info.getLangOpts().CPlusPlus) {
2221 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2222 << AK << 1 << VD;
2223 Info.Note(VD->getLocation(), diag::note_declared_at);
2224 } else {
2225 Info.Diag(E);
2226 }
2227 return CompleteObject();
2228 }
2229
2230 // Unless we're looking at a local variable or argument in a constexpr call,
2231 // the variable we're reading must be const.
2232 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002233 if (Info.getLangOpts().CPlusPlus1y &&
2234 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2235 // OK, we can read and modify an object if we're in the process of
2236 // evaluating its initializer, because its lifetime began in this
2237 // evaluation.
2238 } else if (AK != AK_Read) {
2239 // All the remaining cases only permit reading.
2240 Info.Diag(E, diag::note_constexpr_modify_global);
2241 return CompleteObject();
2242 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002243 // OK, we can read this variable.
2244 } else if (BaseType->isIntegralOrEnumerationType()) {
2245 if (!BaseType.isConstQualified()) {
2246 if (Info.getLangOpts().CPlusPlus) {
2247 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2248 Info.Note(VD->getLocation(), diag::note_declared_at);
2249 } else {
2250 Info.Diag(E);
2251 }
2252 return CompleteObject();
2253 }
2254 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2255 // We support folding of const floating-point types, in order to make
2256 // static const data members of such types (supported as an extension)
2257 // more useful.
2258 if (Info.getLangOpts().CPlusPlus11) {
2259 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2260 Info.Note(VD->getLocation(), diag::note_declared_at);
2261 } else {
2262 Info.CCEDiag(E);
2263 }
2264 } else {
2265 // FIXME: Allow folding of values of any literal type in all languages.
2266 if (Info.getLangOpts().CPlusPlus11) {
2267 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2268 Info.Note(VD->getLocation(), diag::note_declared_at);
2269 } else {
2270 Info.Diag(E);
2271 }
2272 return CompleteObject();
2273 }
2274 }
2275
2276 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2277 return CompleteObject();
2278 } else {
2279 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2280
2281 if (!Frame) {
2282 Info.Diag(E);
2283 return CompleteObject();
2284 }
2285
Richard Smith3229b742013-05-05 21:17:10 +00002286 BaseVal = &Frame->Temporaries[Base];
2287
2288 // Volatile temporary objects cannot be accessed in constant expressions.
2289 if (BaseType.isVolatileQualified()) {
2290 if (Info.getLangOpts().CPlusPlus) {
2291 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2292 << AK << 0;
2293 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2294 } else {
2295 Info.Diag(E);
2296 }
2297 return CompleteObject();
2298 }
2299 }
2300
Richard Smith7525ff62013-05-09 07:14:00 +00002301 // During the construction of an object, it is not yet 'const'.
2302 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2303 // and this doesn't do quite the right thing for const subobjects of the
2304 // object under construction.
2305 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2306 BaseType = Info.Ctx.getCanonicalType(BaseType);
2307 BaseType.removeLocalConst();
2308 }
2309
Richard Smith3229b742013-05-05 21:17:10 +00002310 // In C++1y, we can't safely access any mutable state when checking a
2311 // potential constant expression.
2312 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2313 Info.CheckingPotentialConstantExpression)
2314 return CompleteObject();
2315
2316 return CompleteObject(BaseVal, BaseType);
2317}
2318
Richard Smith243ef902013-05-05 23:31:59 +00002319/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2320/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2321/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002322///
2323/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002324/// \param Conv - The expression for which we are performing the conversion.
2325/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002326/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2327/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002328/// \param LVal - The glvalue on which we are attempting to perform this action.
2329/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002330static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002331 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002332 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002333 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002334 return false;
2335
Richard Smith3229b742013-05-05 21:17:10 +00002336 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002337 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002338 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2339 !Type.isVolatileQualified()) {
2340 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2341 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2342 // initializer until now for such expressions. Such an expression can't be
2343 // an ICE in C, so this only matters for fold.
2344 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2345 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002346 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002347 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002348 }
Richard Smith3229b742013-05-05 21:17:10 +00002349 APValue Lit;
2350 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2351 return false;
2352 CompleteObject LitObj(&Lit, Base->getType());
2353 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2354 } else if (isa<StringLiteral>(Base)) {
2355 // We represent a string literal array as an lvalue pointing at the
2356 // corresponding expression, rather than building an array of chars.
2357 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2358 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2359 CompleteObject StrObj(&Str, Base->getType());
2360 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002361 }
Richard Smith11562c52011-10-28 17:51:58 +00002362 }
2363
Richard Smith3229b742013-05-05 21:17:10 +00002364 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2365 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002366}
2367
2368/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002369static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002370 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002371 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002372 return false;
2373
Richard Smith3229b742013-05-05 21:17:10 +00002374 if (!Info.getLangOpts().CPlusPlus1y) {
2375 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002376 return false;
2377 }
2378
Richard Smith3229b742013-05-05 21:17:10 +00002379 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2380 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002381}
2382
Richard Smith243ef902013-05-05 23:31:59 +00002383static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2384 return T->isSignedIntegerType() &&
2385 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2386}
2387
2388namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002389struct CompoundAssignSubobjectHandler {
2390 EvalInfo &Info;
2391 const Expr *E;
2392 QualType PromotedLHSType;
2393 BinaryOperatorKind Opcode;
2394 const APValue &RHS;
2395
2396 static const AccessKinds AccessKind = AK_Assign;
2397
2398 typedef bool result_type;
2399
2400 bool checkConst(QualType QT) {
2401 // Assigning to a const object has undefined behavior.
2402 if (QT.isConstQualified()) {
2403 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2404 return false;
2405 }
2406 return true;
2407 }
2408
2409 bool failed() { return false; }
2410 bool found(APValue &Subobj, QualType SubobjType) {
2411 switch (Subobj.getKind()) {
2412 case APValue::Int:
2413 return found(Subobj.getInt(), SubobjType);
2414 case APValue::Float:
2415 return found(Subobj.getFloat(), SubobjType);
2416 case APValue::ComplexInt:
2417 case APValue::ComplexFloat:
2418 // FIXME: Implement complex compound assignment.
2419 Info.Diag(E);
2420 return false;
2421 case APValue::LValue:
2422 return foundPointer(Subobj, SubobjType);
2423 default:
2424 // FIXME: can this happen?
2425 Info.Diag(E);
2426 return false;
2427 }
2428 }
2429 bool found(APSInt &Value, QualType SubobjType) {
2430 if (!checkConst(SubobjType))
2431 return false;
2432
2433 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2434 // We don't support compound assignment on integer-cast-to-pointer
2435 // values.
2436 Info.Diag(E);
2437 return false;
2438 }
2439
2440 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2441 SubobjType, Value);
2442 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2443 return false;
2444 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2445 return true;
2446 }
2447 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002448 return checkConst(SubobjType) &&
2449 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2450 Value) &&
2451 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2452 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002453 }
2454 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2455 if (!checkConst(SubobjType))
2456 return false;
2457
2458 QualType PointeeType;
2459 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2460 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002461
2462 if (PointeeType.isNull() || !RHS.isInt() ||
2463 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002464 Info.Diag(E);
2465 return false;
2466 }
2467
Richard Smith861b5b52013-05-07 23:34:45 +00002468 int64_t Offset = getExtValue(RHS.getInt());
2469 if (Opcode == BO_Sub)
2470 Offset = -Offset;
2471
2472 LValue LVal;
2473 LVal.setFrom(Info.Ctx, Subobj);
2474 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2475 return false;
2476 LVal.moveInto(Subobj);
2477 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002478 }
2479 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2480 llvm_unreachable("shouldn't encounter string elements here");
2481 }
2482};
2483} // end anonymous namespace
2484
2485const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2486
2487/// Perform a compound assignment of LVal <op>= RVal.
2488static bool handleCompoundAssignment(
2489 EvalInfo &Info, const Expr *E,
2490 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2491 BinaryOperatorKind Opcode, const APValue &RVal) {
2492 if (LVal.Designator.Invalid)
2493 return false;
2494
2495 if (!Info.getLangOpts().CPlusPlus1y) {
2496 Info.Diag(E);
2497 return false;
2498 }
2499
2500 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2501 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2502 RVal };
2503 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2504}
2505
2506namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002507struct IncDecSubobjectHandler {
2508 EvalInfo &Info;
2509 const Expr *E;
2510 AccessKinds AccessKind;
2511 APValue *Old;
2512
2513 typedef bool result_type;
2514
2515 bool checkConst(QualType QT) {
2516 // Assigning to a const object has undefined behavior.
2517 if (QT.isConstQualified()) {
2518 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2519 return false;
2520 }
2521 return true;
2522 }
2523
2524 bool failed() { return false; }
2525 bool found(APValue &Subobj, QualType SubobjType) {
2526 // Stash the old value. Also clear Old, so we don't clobber it later
2527 // if we're post-incrementing a complex.
2528 if (Old) {
2529 *Old = Subobj;
2530 Old = 0;
2531 }
2532
2533 switch (Subobj.getKind()) {
2534 case APValue::Int:
2535 return found(Subobj.getInt(), SubobjType);
2536 case APValue::Float:
2537 return found(Subobj.getFloat(), SubobjType);
2538 case APValue::ComplexInt:
2539 return found(Subobj.getComplexIntReal(),
2540 SubobjType->castAs<ComplexType>()->getElementType()
2541 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2542 case APValue::ComplexFloat:
2543 return found(Subobj.getComplexFloatReal(),
2544 SubobjType->castAs<ComplexType>()->getElementType()
2545 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2546 case APValue::LValue:
2547 return foundPointer(Subobj, SubobjType);
2548 default:
2549 // FIXME: can this happen?
2550 Info.Diag(E);
2551 return false;
2552 }
2553 }
2554 bool found(APSInt &Value, QualType SubobjType) {
2555 if (!checkConst(SubobjType))
2556 return false;
2557
2558 if (!SubobjType->isIntegerType()) {
2559 // We don't support increment / decrement on integer-cast-to-pointer
2560 // values.
2561 Info.Diag(E);
2562 return false;
2563 }
2564
2565 if (Old) *Old = APValue(Value);
2566
2567 // bool arithmetic promotes to int, and the conversion back to bool
2568 // doesn't reduce mod 2^n, so special-case it.
2569 if (SubobjType->isBooleanType()) {
2570 if (AccessKind == AK_Increment)
2571 Value = 1;
2572 else
2573 Value = !Value;
2574 return true;
2575 }
2576
2577 bool WasNegative = Value.isNegative();
2578 if (AccessKind == AK_Increment) {
2579 ++Value;
2580
2581 if (!WasNegative && Value.isNegative() &&
2582 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2583 APSInt ActualValue(Value, /*IsUnsigned*/true);
2584 HandleOverflow(Info, E, ActualValue, SubobjType);
2585 }
2586 } else {
2587 --Value;
2588
2589 if (WasNegative && !Value.isNegative() &&
2590 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2591 unsigned BitWidth = Value.getBitWidth();
2592 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2593 ActualValue.setBit(BitWidth);
2594 HandleOverflow(Info, E, ActualValue, SubobjType);
2595 }
2596 }
2597 return true;
2598 }
2599 bool found(APFloat &Value, QualType SubobjType) {
2600 if (!checkConst(SubobjType))
2601 return false;
2602
2603 if (Old) *Old = APValue(Value);
2604
2605 APFloat One(Value.getSemantics(), 1);
2606 if (AccessKind == AK_Increment)
2607 Value.add(One, APFloat::rmNearestTiesToEven);
2608 else
2609 Value.subtract(One, APFloat::rmNearestTiesToEven);
2610 return true;
2611 }
2612 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2613 if (!checkConst(SubobjType))
2614 return false;
2615
2616 QualType PointeeType;
2617 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2618 PointeeType = PT->getPointeeType();
2619 else {
2620 Info.Diag(E);
2621 return false;
2622 }
2623
2624 LValue LVal;
2625 LVal.setFrom(Info.Ctx, Subobj);
2626 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2627 AccessKind == AK_Increment ? 1 : -1))
2628 return false;
2629 LVal.moveInto(Subobj);
2630 return true;
2631 }
2632 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2633 llvm_unreachable("shouldn't encounter string elements here");
2634 }
2635};
2636} // end anonymous namespace
2637
2638/// Perform an increment or decrement on LVal.
2639static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2640 QualType LValType, bool IsIncrement, APValue *Old) {
2641 if (LVal.Designator.Invalid)
2642 return false;
2643
2644 if (!Info.getLangOpts().CPlusPlus1y) {
2645 Info.Diag(E);
2646 return false;
2647 }
2648
2649 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2650 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2651 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2652 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2653}
2654
Richard Smithe97cbd72011-11-11 04:05:33 +00002655/// Build an lvalue for the object argument of a member function call.
2656static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2657 LValue &This) {
2658 if (Object->getType()->isPointerType())
2659 return EvaluatePointer(Object, This, Info);
2660
2661 if (Object->isGLValue())
2662 return EvaluateLValue(Object, This, Info);
2663
Richard Smithd9f663b2013-04-22 15:31:51 +00002664 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002665 return EvaluateTemporary(Object, This, Info);
2666
2667 return false;
2668}
2669
2670/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2671/// lvalue referring to the result.
2672///
2673/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002674/// \param LV - An lvalue referring to the base of the member pointer.
2675/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002676/// \param IncludeMember - Specifies whether the member itself is included in
2677/// the resulting LValue subobject designator. This is not possible when
2678/// creating a bound member function.
2679/// \return The field or method declaration to which the member pointer refers,
2680/// or 0 if evaluation fails.
2681static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002682 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002683 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002684 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002685 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002686 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002687 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002688 return 0;
2689
2690 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2691 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002692 if (!MemPtr.getDecl()) {
2693 // FIXME: Specific diagnostic.
2694 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002695 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002696 }
Richard Smith253c2a32012-01-27 01:14:48 +00002697
Richard Smith027bf112011-11-17 22:56:20 +00002698 if (MemPtr.isDerivedMember()) {
2699 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002700 // The end of the derived-to-base path for the base object must match the
2701 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002702 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002703 LV.Designator.Entries.size()) {
2704 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002705 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002706 }
Richard Smith027bf112011-11-17 22:56:20 +00002707 unsigned PathLengthToMember =
2708 LV.Designator.Entries.size() - MemPtr.Path.size();
2709 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2710 const CXXRecordDecl *LVDecl = getAsBaseClass(
2711 LV.Designator.Entries[PathLengthToMember + I]);
2712 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002713 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2714 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002715 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002716 }
Richard Smith027bf112011-11-17 22:56:20 +00002717 }
2718
2719 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002720 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002721 PathLengthToMember))
2722 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002723 } else if (!MemPtr.Path.empty()) {
2724 // Extend the LValue path with the member pointer's path.
2725 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2726 MemPtr.Path.size() + IncludeMember);
2727
2728 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002729 if (const PointerType *PT = LVType->getAs<PointerType>())
2730 LVType = PT->getPointeeType();
2731 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2732 assert(RD && "member pointer access on non-class-type expression");
2733 // The first class in the path is that of the lvalue.
2734 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2735 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002736 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002737 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002738 RD = Base;
2739 }
2740 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002741 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2742 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002743 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002744 }
2745
2746 // Add the member. Note that we cannot build bound member functions here.
2747 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002748 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002749 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002750 return 0;
2751 } else if (const IndirectFieldDecl *IFD =
2752 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002753 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002754 return 0;
2755 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002756 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002757 }
Richard Smith027bf112011-11-17 22:56:20 +00002758 }
2759
2760 return MemPtr.getDecl();
2761}
2762
Richard Smith84401042013-06-03 05:03:02 +00002763static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2764 const BinaryOperator *BO,
2765 LValue &LV,
2766 bool IncludeMember = true) {
2767 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2768
2769 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2770 if (Info.keepEvaluatingAfterFailure()) {
2771 MemberPtr MemPtr;
2772 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2773 }
2774 return 0;
2775 }
2776
2777 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2778 BO->getRHS(), IncludeMember);
2779}
2780
Richard Smith027bf112011-11-17 22:56:20 +00002781/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2782/// the provided lvalue, which currently refers to the base object.
2783static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2784 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002785 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002786 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002787 return false;
2788
Richard Smitha8105bc2012-01-06 16:39:00 +00002789 QualType TargetQT = E->getType();
2790 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2791 TargetQT = PT->getPointeeType();
2792
2793 // Check this cast lands within the final derived-to-base subobject path.
2794 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002795 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002796 << D.MostDerivedType << TargetQT;
2797 return false;
2798 }
2799
Richard Smith027bf112011-11-17 22:56:20 +00002800 // Check the type of the final cast. We don't need to check the path,
2801 // since a cast can only be formed if the path is unique.
2802 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002803 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2804 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002805 if (NewEntriesSize == D.MostDerivedPathLength)
2806 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2807 else
Richard Smith027bf112011-11-17 22:56:20 +00002808 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002809 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002810 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002811 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002812 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002813 }
Richard Smith027bf112011-11-17 22:56:20 +00002814
2815 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002816 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002817}
2818
Mike Stump876387b2009-10-27 22:09:17 +00002819namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002820enum EvalStmtResult {
2821 /// Evaluation failed.
2822 ESR_Failed,
2823 /// Hit a 'return' statement.
2824 ESR_Returned,
2825 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002826 ESR_Succeeded,
2827 /// Hit a 'continue' statement.
2828 ESR_Continue,
2829 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002830 ESR_Break,
2831 /// Still scanning for 'case' or 'default' statement.
2832 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002833};
2834}
2835
Richard Smithd9f663b2013-04-22 15:31:51 +00002836static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2837 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2838 // We don't need to evaluate the initializer for a static local.
2839 if (!VD->hasLocalStorage())
2840 return true;
2841
2842 LValue Result;
2843 Result.set(VD, Info.CurrentCall->Index);
2844 APValue &Val = Info.CurrentCall->Temporaries[VD];
2845
2846 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2847 // Wipe out any partially-computed value, to allow tracking that this
2848 // evaluation failed.
2849 Val = APValue();
2850 return false;
2851 }
2852 }
2853
2854 return true;
2855}
2856
Richard Smith4e18ca52013-05-06 05:56:11 +00002857/// Evaluate a condition (either a variable declaration or an expression).
2858static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2859 const Expr *Cond, bool &Result) {
2860 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2861 return false;
2862 return EvaluateAsBooleanCondition(Cond, Result, Info);
2863}
2864
2865static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002866 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002867
2868/// Evaluate the body of a loop, and translate the result as appropriate.
2869static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002870 const Stmt *Body,
2871 const SwitchCase *Case = 0) {
2872 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002873 case ESR_Break:
2874 return ESR_Succeeded;
2875 case ESR_Succeeded:
2876 case ESR_Continue:
2877 return ESR_Continue;
2878 case ESR_Failed:
2879 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002880 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002881 return ESR;
2882 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002883 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002884}
2885
Richard Smith496ddcf2013-05-12 17:32:42 +00002886/// Evaluate a switch statement.
2887static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2888 const SwitchStmt *SS) {
2889 // Evaluate the switch condition.
2890 if (SS->getConditionVariable() &&
2891 !EvaluateDecl(Info, SS->getConditionVariable()))
2892 return ESR_Failed;
2893 APSInt Value;
2894 if (!EvaluateInteger(SS->getCond(), Value, Info))
2895 return ESR_Failed;
2896
2897 // Find the switch case corresponding to the value of the condition.
2898 // FIXME: Cache this lookup.
2899 const SwitchCase *Found = 0;
2900 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2901 SC = SC->getNextSwitchCase()) {
2902 if (isa<DefaultStmt>(SC)) {
2903 Found = SC;
2904 continue;
2905 }
2906
2907 const CaseStmt *CS = cast<CaseStmt>(SC);
2908 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2909 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2910 : LHS;
2911 if (LHS <= Value && Value <= RHS) {
2912 Found = SC;
2913 break;
2914 }
2915 }
2916
2917 if (!Found)
2918 return ESR_Succeeded;
2919
2920 // Search the switch body for the switch case and evaluate it from there.
2921 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2922 case ESR_Break:
2923 return ESR_Succeeded;
2924 case ESR_Succeeded:
2925 case ESR_Continue:
2926 case ESR_Failed:
2927 case ESR_Returned:
2928 return ESR;
2929 case ESR_CaseNotFound:
Richard Smith496ddcf2013-05-12 17:32:42 +00002930 llvm_unreachable("couldn't find switch case");
2931 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002932 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002933}
2934
Richard Smith254a73d2011-10-28 22:34:42 +00002935// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002936static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002937 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002938 if (!Info.nextStep(S))
2939 return ESR_Failed;
2940
Richard Smith496ddcf2013-05-12 17:32:42 +00002941 // If we're hunting down a 'case' or 'default' label, recurse through
2942 // substatements until we hit the label.
2943 if (Case) {
2944 // FIXME: We don't start the lifetime of objects whose initialization we
2945 // jump over. However, such objects must be of class type with a trivial
2946 // default constructor that initialize all subobjects, so must be empty,
2947 // so this almost never matters.
2948 switch (S->getStmtClass()) {
2949 case Stmt::CompoundStmtClass:
2950 // FIXME: Precompute which substatement of a compound statement we
2951 // would jump to, and go straight there rather than performing a
2952 // linear scan each time.
2953 case Stmt::LabelStmtClass:
2954 case Stmt::AttributedStmtClass:
2955 case Stmt::DoStmtClass:
2956 break;
2957
2958 case Stmt::CaseStmtClass:
2959 case Stmt::DefaultStmtClass:
2960 if (Case == S)
2961 Case = 0;
2962 break;
2963
2964 case Stmt::IfStmtClass: {
2965 // FIXME: Precompute which side of an 'if' we would jump to, and go
2966 // straight there rather than scanning both sides.
2967 const IfStmt *IS = cast<IfStmt>(S);
2968 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
2969 if (ESR != ESR_CaseNotFound || !IS->getElse())
2970 return ESR;
2971 return EvaluateStmt(Result, Info, IS->getElse(), Case);
2972 }
2973
2974 case Stmt::WhileStmtClass: {
2975 EvalStmtResult ESR =
2976 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
2977 if (ESR != ESR_Continue)
2978 return ESR;
2979 break;
2980 }
2981
2982 case Stmt::ForStmtClass: {
2983 const ForStmt *FS = cast<ForStmt>(S);
2984 EvalStmtResult ESR =
2985 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
2986 if (ESR != ESR_Continue)
2987 return ESR;
2988 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2989 return ESR_Failed;
2990 break;
2991 }
2992
2993 case Stmt::DeclStmtClass:
2994 // FIXME: If the variable has initialization that can't be jumped over,
2995 // bail out of any immediately-surrounding compound-statement too.
2996 default:
2997 return ESR_CaseNotFound;
2998 }
2999 }
3000
Richard Smithd9f663b2013-04-22 15:31:51 +00003001 // FIXME: Mark all temporaries in the current frame as destroyed at
3002 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00003003 switch (S->getStmtClass()) {
3004 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003005 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003006 // Don't bother evaluating beyond an expression-statement which couldn't
3007 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00003008 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003009 return ESR_Failed;
3010 return ESR_Succeeded;
3011 }
3012
3013 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003014 return ESR_Failed;
3015
3016 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003017 return ESR_Succeeded;
3018
Richard Smithd9f663b2013-04-22 15:31:51 +00003019 case Stmt::DeclStmtClass: {
3020 const DeclStmt *DS = cast<DeclStmt>(S);
3021 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3022 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
3023 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3024 return ESR_Failed;
3025 return ESR_Succeeded;
3026 }
3027
Richard Smith357362d2011-12-13 06:39:58 +00003028 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003029 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00003030 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003031 return ESR_Failed;
3032 return ESR_Returned;
3033 }
Richard Smith254a73d2011-10-28 22:34:42 +00003034
3035 case Stmt::CompoundStmtClass: {
3036 const CompoundStmt *CS = cast<CompoundStmt>(S);
3037 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3038 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003039 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3040 if (ESR == ESR_Succeeded)
3041 Case = 0;
3042 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003043 return ESR;
3044 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003045 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003046 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003047
3048 case Stmt::IfStmtClass: {
3049 const IfStmt *IS = cast<IfStmt>(S);
3050
3051 // Evaluate the condition, as either a var decl or as an expression.
3052 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003053 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003054 return ESR_Failed;
3055
3056 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3057 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3058 if (ESR != ESR_Succeeded)
3059 return ESR;
3060 }
3061 return ESR_Succeeded;
3062 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003063
3064 case Stmt::WhileStmtClass: {
3065 const WhileStmt *WS = cast<WhileStmt>(S);
3066 while (true) {
3067 bool Continue;
3068 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3069 Continue))
3070 return ESR_Failed;
3071 if (!Continue)
3072 break;
3073
3074 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3075 if (ESR != ESR_Continue)
3076 return ESR;
3077 }
3078 return ESR_Succeeded;
3079 }
3080
3081 case Stmt::DoStmtClass: {
3082 const DoStmt *DS = cast<DoStmt>(S);
3083 bool Continue;
3084 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003085 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003086 if (ESR != ESR_Continue)
3087 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003088 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003089
3090 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3091 return ESR_Failed;
3092 } while (Continue);
3093 return ESR_Succeeded;
3094 }
3095
3096 case Stmt::ForStmtClass: {
3097 const ForStmt *FS = cast<ForStmt>(S);
3098 if (FS->getInit()) {
3099 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3100 if (ESR != ESR_Succeeded)
3101 return ESR;
3102 }
3103 while (true) {
3104 bool Continue = true;
3105 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3106 FS->getCond(), Continue))
3107 return ESR_Failed;
3108 if (!Continue)
3109 break;
3110
3111 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3112 if (ESR != ESR_Continue)
3113 return ESR;
3114
3115 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3116 return ESR_Failed;
3117 }
3118 return ESR_Succeeded;
3119 }
3120
Richard Smith896e0d72013-05-06 06:51:17 +00003121 case Stmt::CXXForRangeStmtClass: {
3122 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3123
3124 // Initialize the __range variable.
3125 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3126 if (ESR != ESR_Succeeded)
3127 return ESR;
3128
3129 // Create the __begin and __end iterators.
3130 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3131 if (ESR != ESR_Succeeded)
3132 return ESR;
3133
3134 while (true) {
3135 // Condition: __begin != __end.
3136 bool Continue = true;
3137 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3138 return ESR_Failed;
3139 if (!Continue)
3140 break;
3141
3142 // User's variable declaration, initialized by *__begin.
3143 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3144 if (ESR != ESR_Succeeded)
3145 return ESR;
3146
3147 // Loop body.
3148 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3149 if (ESR != ESR_Continue)
3150 return ESR;
3151
3152 // Increment: ++__begin
3153 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3154 return ESR_Failed;
3155 }
3156
3157 return ESR_Succeeded;
3158 }
3159
Richard Smith496ddcf2013-05-12 17:32:42 +00003160 case Stmt::SwitchStmtClass:
3161 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3162
Richard Smith4e18ca52013-05-06 05:56:11 +00003163 case Stmt::ContinueStmtClass:
3164 return ESR_Continue;
3165
3166 case Stmt::BreakStmtClass:
3167 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003168
3169 case Stmt::LabelStmtClass:
3170 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3171
3172 case Stmt::AttributedStmtClass:
3173 // As a general principle, C++11 attributes can be ignored without
3174 // any semantic impact.
3175 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3176 Case);
3177
3178 case Stmt::CaseStmtClass:
3179 case Stmt::DefaultStmtClass:
3180 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003181 }
3182}
3183
Richard Smithcc36f692011-12-22 02:22:31 +00003184/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3185/// default constructor. If so, we'll fold it whether or not it's marked as
3186/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3187/// so we need special handling.
3188static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003189 const CXXConstructorDecl *CD,
3190 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003191 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3192 return false;
3193
Richard Smith66e05fe2012-01-18 05:21:49 +00003194 // Value-initialization does not call a trivial default constructor, so such a
3195 // call is a core constant expression whether or not the constructor is
3196 // constexpr.
3197 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003198 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003199 // FIXME: If DiagDecl is an implicitly-declared special member function,
3200 // we should be much more explicit about why it's not constexpr.
3201 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3202 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3203 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003204 } else {
3205 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3206 }
3207 }
3208 return true;
3209}
3210
Richard Smith357362d2011-12-13 06:39:58 +00003211/// CheckConstexprFunction - Check that a function can be called in a constant
3212/// expression.
3213static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3214 const FunctionDecl *Declaration,
3215 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003216 // Potential constant expressions can contain calls to declared, but not yet
3217 // defined, constexpr functions.
3218 if (Info.CheckingPotentialConstantExpression && !Definition &&
3219 Declaration->isConstexpr())
3220 return false;
3221
Richard Smith0838f3a2013-05-14 05:18:44 +00003222 // Bail out with no diagnostic if the function declaration itself is invalid.
3223 // We will have produced a relevant diagnostic while parsing it.
3224 if (Declaration->isInvalidDecl())
3225 return false;
3226
Richard Smith357362d2011-12-13 06:39:58 +00003227 // Can we evaluate this function call?
3228 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3229 return true;
3230
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003231 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003232 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003233 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3234 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003235 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3236 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3237 << DiagDecl;
3238 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3239 } else {
3240 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3241 }
3242 return false;
3243}
3244
Richard Smithd62306a2011-11-10 06:34:14 +00003245namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003246typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003247}
3248
3249/// EvaluateArgs - Evaluate the arguments to a function call.
3250static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3251 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003252 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003253 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003254 I != E; ++I) {
3255 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3256 // If we're checking for a potential constant expression, evaluate all
3257 // initializers even if some of them fail.
3258 if (!Info.keepEvaluatingAfterFailure())
3259 return false;
3260 Success = false;
3261 }
3262 }
3263 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003264}
3265
Richard Smith254a73d2011-10-28 22:34:42 +00003266/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003267static bool HandleFunctionCall(SourceLocation CallLoc,
3268 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003269 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003270 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003271 ArgVector ArgValues(Args.size());
3272 if (!EvaluateArgs(Args, ArgValues, Info))
3273 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003274
Richard Smith253c2a32012-01-27 01:14:48 +00003275 if (!Info.CheckCallLimit(CallLoc))
3276 return false;
3277
3278 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003279
3280 // For a trivial copy or move assignment, perform an APValue copy. This is
3281 // essential for unions, where the operations performed by the assignment
3282 // operator cannot be represented as statements.
3283 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3284 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3285 assert(This &&
3286 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3287 LValue RHS;
3288 RHS.setFrom(Info.Ctx, ArgValues[0]);
3289 APValue RHSValue;
3290 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3291 RHS, RHSValue))
3292 return false;
3293 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3294 RHSValue))
3295 return false;
3296 This->moveInto(Result);
3297 return true;
3298 }
3299
Richard Smithd9f663b2013-04-22 15:31:51 +00003300 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003301 if (ESR == ESR_Succeeded) {
3302 if (Callee->getResultType()->isVoidType())
3303 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003304 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003305 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003306 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003307}
3308
Richard Smithd62306a2011-11-10 06:34:14 +00003309/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003310static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003311 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003312 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003313 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003314 ArgVector ArgValues(Args.size());
3315 if (!EvaluateArgs(Args, ArgValues, Info))
3316 return false;
3317
Richard Smith253c2a32012-01-27 01:14:48 +00003318 if (!Info.CheckCallLimit(CallLoc))
3319 return false;
3320
Richard Smith3607ffe2012-02-13 03:54:03 +00003321 const CXXRecordDecl *RD = Definition->getParent();
3322 if (RD->getNumVBases()) {
3323 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3324 return false;
3325 }
3326
Richard Smith253c2a32012-01-27 01:14:48 +00003327 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003328
3329 // If it's a delegating constructor, just delegate.
3330 if (Definition->isDelegatingConstructor()) {
3331 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003332 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3333 return false;
3334 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003335 }
3336
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003337 // For a trivial copy or move constructor, perform an APValue copy. This is
3338 // essential for unions, where the operations performed by the constructor
3339 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003340 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003341 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3342 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003343 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003344 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003345 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003346 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003347 }
3348
3349 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003350 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003351 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3352 std::distance(RD->field_begin(), RD->field_end()));
3353
John McCalld7bca762012-05-01 00:38:49 +00003354 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003355 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3356
Richard Smith253c2a32012-01-27 01:14:48 +00003357 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003358 unsigned BasesSeen = 0;
3359#ifndef NDEBUG
3360 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3361#endif
3362 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3363 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003364 LValue Subobject = This;
3365 APValue *Value = &Result;
3366
3367 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003368 if ((*I)->isBaseInitializer()) {
3369 QualType BaseType((*I)->getBaseClass(), 0);
3370#ifndef NDEBUG
3371 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003372 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003373 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3374 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3375 "base class initializers not in expected order");
3376 ++BaseIt;
3377#endif
John McCalld7bca762012-05-01 00:38:49 +00003378 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3379 BaseType->getAsCXXRecordDecl(), &Layout))
3380 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003381 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003382 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003383 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3384 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003385 if (RD->isUnion()) {
3386 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003387 Value = &Result.getUnionValue();
3388 } else {
3389 Value = &Result.getStructField(FD->getFieldIndex());
3390 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003391 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003392 // Walk the indirect field decl's chain to find the object to initialize,
3393 // and make sure we've initialized every step along it.
3394 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3395 CE = IFD->chain_end();
3396 C != CE; ++C) {
3397 FieldDecl *FD = cast<FieldDecl>(*C);
3398 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3399 // Switch the union field if it differs. This happens if we had
3400 // preceding zero-initialization, and we're now initializing a union
3401 // subobject other than the first.
3402 // FIXME: In this case, the values of the other subobjects are
3403 // specified, since zero-initialization sets all padding bits to zero.
3404 if (Value->isUninit() ||
3405 (Value->isUnion() && Value->getUnionField() != FD)) {
3406 if (CD->isUnion())
3407 *Value = APValue(FD);
3408 else
3409 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3410 std::distance(CD->field_begin(), CD->field_end()));
3411 }
John McCalld7bca762012-05-01 00:38:49 +00003412 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3413 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003414 if (CD->isUnion())
3415 Value = &Value->getUnionValue();
3416 else
3417 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003418 }
Richard Smithd62306a2011-11-10 06:34:14 +00003419 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003420 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003421 }
Richard Smith253c2a32012-01-27 01:14:48 +00003422
Richard Smith7525ff62013-05-09 07:14:00 +00003423 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003424 // If we're checking for a potential constant expression, evaluate all
3425 // initializers even if some of them fail.
3426 if (!Info.keepEvaluatingAfterFailure())
3427 return false;
3428 Success = false;
3429 }
Richard Smithd62306a2011-11-10 06:34:14 +00003430 }
3431
Richard Smithd9f663b2013-04-22 15:31:51 +00003432 return Success &&
3433 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003434}
3435
Eli Friedman9a156e52008-11-12 09:44:48 +00003436//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003437// Generic Evaluation
3438//===----------------------------------------------------------------------===//
3439namespace {
3440
Richard Smithf57d8cb2011-12-09 22:58:01 +00003441// FIXME: RetTy is always bool. Remove it.
3442template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003443class ExprEvaluatorBase
3444 : public ConstStmtVisitor<Derived, RetTy> {
3445private:
Richard Smith2e312c82012-03-03 22:46:17 +00003446 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003447 return static_cast<Derived*>(this)->Success(V, E);
3448 }
Richard Smithfddd3842011-12-30 21:15:51 +00003449 RetTy DerivedZeroInitialization(const Expr *E) {
3450 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003451 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003452
Richard Smith17100ba2012-02-16 02:46:34 +00003453 // Check whether a conditional operator with a non-constant condition is a
3454 // potential constant expression. If neither arm is a potential constant
3455 // expression, then the conditional operator is not either.
3456 template<typename ConditionalOperator>
3457 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3458 assert(Info.CheckingPotentialConstantExpression);
3459
3460 // Speculatively evaluate both arms.
3461 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003462 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003463 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3464
3465 StmtVisitorTy::Visit(E->getFalseExpr());
3466 if (Diag.empty())
3467 return;
3468
3469 Diag.clear();
3470 StmtVisitorTy::Visit(E->getTrueExpr());
3471 if (Diag.empty())
3472 return;
3473 }
3474
3475 Error(E, diag::note_constexpr_conditional_never_const);
3476 }
3477
3478
3479 template<typename ConditionalOperator>
3480 bool HandleConditionalOperator(const ConditionalOperator *E) {
3481 bool BoolResult;
3482 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3483 if (Info.CheckingPotentialConstantExpression)
3484 CheckPotentialConstantConditional(E);
3485 return false;
3486 }
3487
3488 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3489 return StmtVisitorTy::Visit(EvalExpr);
3490 }
3491
Peter Collingbournee9200682011-05-13 03:29:01 +00003492protected:
3493 EvalInfo &Info;
3494 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3495 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3496
Richard Smith92b1ce02011-12-12 09:28:41 +00003497 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003498 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003499 }
3500
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003501 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3502
3503public:
3504 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3505
3506 EvalInfo &getEvalInfo() { return Info; }
3507
Richard Smithf57d8cb2011-12-09 22:58:01 +00003508 /// Report an evaluation error. This should only be called when an error is
3509 /// first discovered. When propagating an error, just return false.
3510 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003511 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003512 return false;
3513 }
3514 bool Error(const Expr *E) {
3515 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3516 }
3517
Peter Collingbournee9200682011-05-13 03:29:01 +00003518 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003519 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003520 }
3521 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003522 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003523 }
3524
3525 RetTy VisitParenExpr(const ParenExpr *E)
3526 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3527 RetTy VisitUnaryExtension(const UnaryOperator *E)
3528 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3529 RetTy VisitUnaryPlus(const UnaryOperator *E)
3530 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3531 RetTy VisitChooseExpr(const ChooseExpr *E)
3532 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3533 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3534 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003535 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3536 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003537 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3538 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003539 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3540 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003541 // We cannot create any objects for which cleanups are required, so there is
3542 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3543 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3544 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003545
Richard Smith6d6ecc32011-12-12 12:46:16 +00003546 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3547 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3548 return static_cast<Derived*>(this)->VisitCastExpr(E);
3549 }
3550 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3551 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3552 return static_cast<Derived*>(this)->VisitCastExpr(E);
3553 }
3554
Richard Smith027bf112011-11-17 22:56:20 +00003555 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3556 switch (E->getOpcode()) {
3557 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003558 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003559
3560 case BO_Comma:
3561 VisitIgnoredValue(E->getLHS());
3562 return StmtVisitorTy::Visit(E->getRHS());
3563
3564 case BO_PtrMemD:
3565 case BO_PtrMemI: {
3566 LValue Obj;
3567 if (!HandleMemberPointerAccess(Info, E, Obj))
3568 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003569 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003570 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003571 return false;
3572 return DerivedSuccess(Result, E);
3573 }
3574 }
3575 }
3576
Peter Collingbournee9200682011-05-13 03:29:01 +00003577 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003578 // Evaluate and cache the common expression. We treat it as a temporary,
3579 // even though it's not quite the same thing.
3580 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3581 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003582 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003583
Richard Smith17100ba2012-02-16 02:46:34 +00003584 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003585 }
3586
3587 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003588 bool IsBcpCall = false;
3589 // If the condition (ignoring parens) is a __builtin_constant_p call,
3590 // the result is a constant expression if it can be folded without
3591 // side-effects. This is an important GNU extension. See GCC PR38377
3592 // for discussion.
3593 if (const CallExpr *CallCE =
3594 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3595 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3596 IsBcpCall = true;
3597
3598 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3599 // constant expression; we can't check whether it's potentially foldable.
3600 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3601 return false;
3602
3603 FoldConstant Fold(Info);
3604
Richard Smith17100ba2012-02-16 02:46:34 +00003605 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003606 return false;
3607
3608 if (IsBcpCall)
3609 Fold.Fold(Info);
3610
3611 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003612 }
3613
3614 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003615 APValue &Value = Info.CurrentCall->Temporaries[E];
3616 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003617 const Expr *Source = E->getSourceExpr();
3618 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003619 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003620 if (Source == E) { // sanity checking.
3621 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003622 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003623 }
3624 return StmtVisitorTy::Visit(Source);
3625 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003626 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003627 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003628
Richard Smith254a73d2011-10-28 22:34:42 +00003629 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003630 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003631 QualType CalleeType = Callee->getType();
3632
Richard Smith254a73d2011-10-28 22:34:42 +00003633 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003634 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003635 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003636 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003637
Richard Smithe97cbd72011-11-11 04:05:33 +00003638 // Extract function decl and 'this' pointer from the callee.
3639 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003640 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003641 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3642 // Explicit bound member calls, such as x.f() or p->g();
3643 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003644 return false;
3645 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003646 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003647 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003648 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3649 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003650 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3651 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003652 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003653 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003654 return Error(Callee);
3655
3656 FD = dyn_cast<FunctionDecl>(Member);
3657 if (!FD)
3658 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003659 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003660 LValue Call;
3661 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003662 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003663
Richard Smitha8105bc2012-01-06 16:39:00 +00003664 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003665 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003666 FD = dyn_cast_or_null<FunctionDecl>(
3667 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003668 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003669 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003670
3671 // Overloaded operator calls to member functions are represented as normal
3672 // calls with '*this' as the first argument.
3673 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3674 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003675 // FIXME: When selecting an implicit conversion for an overloaded
3676 // operator delete, we sometimes try to evaluate calls to conversion
3677 // operators without a 'this' parameter!
3678 if (Args.empty())
3679 return Error(E);
3680
Richard Smithe97cbd72011-11-11 04:05:33 +00003681 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3682 return false;
3683 This = &ThisVal;
3684 Args = Args.slice(1);
3685 }
3686
3687 // Don't call function pointers which have been cast to some other type.
3688 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003689 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003690 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003691 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003692
Richard Smith47b34932012-02-01 02:39:43 +00003693 if (This && !This->checkSubobject(Info, E, CSK_This))
3694 return false;
3695
Richard Smith3607ffe2012-02-13 03:54:03 +00003696 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3697 // calls to such functions in constant expressions.
3698 if (This && !HasQualifier &&
3699 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3700 return Error(E, diag::note_constexpr_virtual_call);
3701
Richard Smith357362d2011-12-13 06:39:58 +00003702 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003703 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003704 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003705
Richard Smith357362d2011-12-13 06:39:58 +00003706 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003707 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3708 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003709 return false;
3710
Richard Smithb228a862012-02-15 02:18:13 +00003711 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003712 }
3713
Richard Smith11562c52011-10-28 17:51:58 +00003714 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3715 return StmtVisitorTy::Visit(E->getInitializer());
3716 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003717 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003718 if (E->getNumInits() == 0)
3719 return DerivedZeroInitialization(E);
3720 if (E->getNumInits() == 1)
3721 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003722 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003723 }
3724 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003725 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003726 }
3727 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003728 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003729 }
Richard Smith027bf112011-11-17 22:56:20 +00003730 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003731 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003732 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003733
Richard Smithd62306a2011-11-10 06:34:14 +00003734 /// A member expression where the object is a prvalue is itself a prvalue.
3735 RetTy VisitMemberExpr(const MemberExpr *E) {
3736 assert(!E->isArrow() && "missing call to bound member function?");
3737
Richard Smith2e312c82012-03-03 22:46:17 +00003738 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003739 if (!Evaluate(Val, Info, E->getBase()))
3740 return false;
3741
3742 QualType BaseTy = E->getBase()->getType();
3743
3744 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003746 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003747 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003748 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3749
Richard Smith3229b742013-05-05 21:17:10 +00003750 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003751 SubobjectDesignator Designator(BaseTy);
3752 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003753
Richard Smith3229b742013-05-05 21:17:10 +00003754 APValue Result;
3755 return extractSubobject(Info, E, Obj, Designator, Result) &&
3756 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003757 }
3758
Richard Smith11562c52011-10-28 17:51:58 +00003759 RetTy VisitCastExpr(const CastExpr *E) {
3760 switch (E->getCastKind()) {
3761 default:
3762 break;
3763
Richard Smitha23ab512013-05-23 00:30:41 +00003764 case CK_AtomicToNonAtomic: {
3765 APValue AtomicVal;
3766 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3767 return false;
3768 return DerivedSuccess(AtomicVal, E);
3769 }
3770
Richard Smith11562c52011-10-28 17:51:58 +00003771 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003772 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003773 return StmtVisitorTy::Visit(E->getSubExpr());
3774
3775 case CK_LValueToRValue: {
3776 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003777 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3778 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003779 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003780 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003781 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003782 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003783 return false;
3784 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003785 }
3786 }
3787
Richard Smithf57d8cb2011-12-09 22:58:01 +00003788 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003789 }
3790
Richard Smith243ef902013-05-05 23:31:59 +00003791 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3792 return VisitUnaryPostIncDec(UO);
3793 }
3794 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3795 return VisitUnaryPostIncDec(UO);
3796 }
3797 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3798 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3799 return Error(UO);
3800
3801 LValue LVal;
3802 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3803 return false;
3804 APValue RVal;
3805 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3806 UO->isIncrementOp(), &RVal))
3807 return false;
3808 return DerivedSuccess(RVal, UO);
3809 }
3810
Richard Smith4a678122011-10-24 18:44:57 +00003811 /// Visit a value which is evaluated, but whose value is ignored.
3812 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003813 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003814 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003815};
3816
3817}
3818
3819//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003820// Common base class for lvalue and temporary evaluation.
3821//===----------------------------------------------------------------------===//
3822namespace {
3823template<class Derived>
3824class LValueExprEvaluatorBase
3825 : public ExprEvaluatorBase<Derived, bool> {
3826protected:
3827 LValue &Result;
3828 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3829 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3830
3831 bool Success(APValue::LValueBase B) {
3832 Result.set(B);
3833 return true;
3834 }
3835
3836public:
3837 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3838 ExprEvaluatorBaseTy(Info), Result(Result) {}
3839
Richard Smith2e312c82012-03-03 22:46:17 +00003840 bool Success(const APValue &V, const Expr *E) {
3841 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003842 return true;
3843 }
Richard Smith027bf112011-11-17 22:56:20 +00003844
Richard Smith027bf112011-11-17 22:56:20 +00003845 bool VisitMemberExpr(const MemberExpr *E) {
3846 // Handle non-static data members.
3847 QualType BaseTy;
3848 if (E->isArrow()) {
3849 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3850 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003851 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003852 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003853 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003854 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3855 return false;
3856 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003857 } else {
3858 if (!this->Visit(E->getBase()))
3859 return false;
3860 BaseTy = E->getBase()->getType();
3861 }
Richard Smith027bf112011-11-17 22:56:20 +00003862
Richard Smith1b78b3d2012-01-25 22:15:11 +00003863 const ValueDecl *MD = E->getMemberDecl();
3864 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3865 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3866 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3867 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003868 if (!HandleLValueMember(this->Info, E, Result, FD))
3869 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003870 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003871 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3872 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003873 } else
3874 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003875
Richard Smith1b78b3d2012-01-25 22:15:11 +00003876 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003877 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003878 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003879 RefValue))
3880 return false;
3881 return Success(RefValue, E);
3882 }
3883 return true;
3884 }
3885
3886 bool VisitBinaryOperator(const BinaryOperator *E) {
3887 switch (E->getOpcode()) {
3888 default:
3889 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3890
3891 case BO_PtrMemD:
3892 case BO_PtrMemI:
3893 return HandleMemberPointerAccess(this->Info, E, Result);
3894 }
3895 }
3896
3897 bool VisitCastExpr(const CastExpr *E) {
3898 switch (E->getCastKind()) {
3899 default:
3900 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3901
3902 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00003903 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00003904 if (!this->Visit(E->getSubExpr()))
3905 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003906
3907 // Now figure out the necessary offset to add to the base LV to get from
3908 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00003909 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
3910 Result);
Richard Smith027bf112011-11-17 22:56:20 +00003911 }
3912 }
3913};
3914}
3915
3916//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003917// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003918//
3919// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3920// function designators (in C), decl references to void objects (in C), and
3921// temporaries (if building with -Wno-address-of-temporary).
3922//
3923// LValue evaluation produces values comprising a base expression of one of the
3924// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003925// - Declarations
3926// * VarDecl
3927// * FunctionDecl
3928// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003929// * CompoundLiteralExpr in C
3930// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003931// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003932// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003933// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003934// * ObjCEncodeExpr
3935// * AddrLabelExpr
3936// * BlockExpr
3937// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003938// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00003939// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00003940// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00003941// was evaluated, for cases where the MaterializeTemporaryExpr is missing
3942// from the AST (FIXME).
Richard Smithce40ad62011-11-12 22:28:03 +00003943// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003944//===----------------------------------------------------------------------===//
3945namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003946class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003947 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003948public:
Richard Smith027bf112011-11-17 22:56:20 +00003949 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3950 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003951
Richard Smith11562c52011-10-28 17:51:58 +00003952 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003953 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003954
Peter Collingbournee9200682011-05-13 03:29:01 +00003955 bool VisitDeclRefExpr(const DeclRefExpr *E);
3956 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003957 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003958 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3959 bool VisitMemberExpr(const MemberExpr *E);
3960 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3961 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003962 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003963 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003964 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3965 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003966 bool VisitUnaryReal(const UnaryOperator *E);
3967 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003968 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3969 return VisitUnaryPreIncDec(UO);
3970 }
3971 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3972 return VisitUnaryPreIncDec(UO);
3973 }
Richard Smith3229b742013-05-05 21:17:10 +00003974 bool VisitBinAssign(const BinaryOperator *BO);
3975 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003976
Peter Collingbournee9200682011-05-13 03:29:01 +00003977 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003978 switch (E->getCastKind()) {
3979 default:
Richard Smith027bf112011-11-17 22:56:20 +00003980 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003981
Eli Friedmance3e02a2011-10-11 00:13:24 +00003982 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003983 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003984 if (!Visit(E->getSubExpr()))
3985 return false;
3986 Result.Designator.setInvalid();
3987 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003988
Richard Smith027bf112011-11-17 22:56:20 +00003989 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003990 if (!Visit(E->getSubExpr()))
3991 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003992 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003993 }
3994 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003995};
3996} // end anonymous namespace
3997
Richard Smith11562c52011-10-28 17:51:58 +00003998/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003999/// expressions which are not glvalues, in two cases:
4000/// * function designators in C, and
4001/// * "extern void" objects
4002static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4003 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4004 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004005 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004006}
4007
Peter Collingbournee9200682011-05-13 03:29:01 +00004008bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004009 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4010 return Success(FD);
4011 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004012 return VisitVarDecl(E, VD);
4013 return Error(E);
4014}
Richard Smith733237d2011-10-24 23:14:33 +00004015
Richard Smith11562c52011-10-28 17:51:58 +00004016bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004017 CallStackFrame *Frame = 0;
4018 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4019 Frame = Info.CurrentCall;
4020
Richard Smithfec09922011-11-01 16:57:24 +00004021 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004022 if (Frame) {
4023 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004024 return true;
4025 }
Richard Smithce40ad62011-11-12 22:28:03 +00004026 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004027 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004028
Richard Smith3229b742013-05-05 21:17:10 +00004029 APValue *V;
4030 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004031 return false;
Richard Smith3229b742013-05-05 21:17:10 +00004032 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004033}
4034
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004035bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4036 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004037 // Walk through the expression to find the materialized temporary itself.
4038 SmallVector<const Expr *, 2> CommaLHSs;
4039 SmallVector<SubobjectAdjustment, 2> Adjustments;
4040 const Expr *Inner = E->GetTemporaryExpr()->
4041 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004042
Richard Smith84401042013-06-03 05:03:02 +00004043 // If we passed any comma operators, evaluate their LHSs.
4044 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4045 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4046 return false;
4047
4048 // Materialize the temporary itself.
4049 APValue *Value = &Info.CurrentCall->Temporaries[E];
Richard Smithb228a862012-02-15 02:18:13 +00004050 Result.set(E, Info.CurrentCall->Index);
Richard Smith84401042013-06-03 05:03:02 +00004051 if (!EvaluateInPlace(*Value, Info, Result, Inner))
4052 return false;
4053
4054 // Adjust our lvalue to refer to the desired subobject.
4055 QualType Type = Inner->getType();
4056 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4057 --I;
4058 switch (Adjustments[I].Kind) {
4059 case SubobjectAdjustment::DerivedToBaseAdjustment:
4060 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4061 Type, Result))
4062 return false;
4063 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4064 break;
4065
4066 case SubobjectAdjustment::FieldAdjustment:
4067 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4068 return false;
4069 Type = Adjustments[I].Field->getType();
4070 break;
4071
4072 case SubobjectAdjustment::MemberPointerAdjustment:
4073 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4074 Adjustments[I].Ptr.RHS))
4075 return false;
4076 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4077 break;
4078 }
4079 }
4080
4081 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004082}
4083
Peter Collingbournee9200682011-05-13 03:29:01 +00004084bool
4085LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004086 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4087 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4088 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004089 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004090}
4091
Richard Smith6e525142011-12-27 12:18:28 +00004092bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004093 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004094 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004095
4096 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4097 << E->getExprOperand()->getType()
4098 << E->getExprOperand()->getSourceRange();
4099 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004100}
4101
Francois Pichet0066db92012-04-16 04:08:35 +00004102bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4103 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004104}
Francois Pichet0066db92012-04-16 04:08:35 +00004105
Peter Collingbournee9200682011-05-13 03:29:01 +00004106bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004107 // Handle static data members.
4108 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4109 VisitIgnoredValue(E->getBase());
4110 return VisitVarDecl(E, VD);
4111 }
4112
Richard Smith254a73d2011-10-28 22:34:42 +00004113 // Handle static member functions.
4114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4115 if (MD->isStatic()) {
4116 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004117 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004118 }
4119 }
4120
Richard Smithd62306a2011-11-10 06:34:14 +00004121 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004122 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004123}
4124
Peter Collingbournee9200682011-05-13 03:29:01 +00004125bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004126 // FIXME: Deal with vectors as array subscript bases.
4127 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004128 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004129
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004130 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004131 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004132
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004133 APSInt Index;
4134 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004135 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004136
Richard Smith861b5b52013-05-07 23:34:45 +00004137 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4138 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004139}
Eli Friedman9a156e52008-11-12 09:44:48 +00004140
Peter Collingbournee9200682011-05-13 03:29:01 +00004141bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004142 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004143}
4144
Richard Smith66c96992012-02-18 22:04:06 +00004145bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4146 if (!Visit(E->getSubExpr()))
4147 return false;
4148 // __real is a no-op on scalar lvalues.
4149 if (E->getSubExpr()->getType()->isAnyComplexType())
4150 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4151 return true;
4152}
4153
4154bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4155 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4156 "lvalue __imag__ on scalar?");
4157 if (!Visit(E->getSubExpr()))
4158 return false;
4159 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4160 return true;
4161}
4162
Richard Smith243ef902013-05-05 23:31:59 +00004163bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4164 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004165 return Error(UO);
4166
4167 if (!this->Visit(UO->getSubExpr()))
4168 return false;
4169
Richard Smith243ef902013-05-05 23:31:59 +00004170 return handleIncDec(
4171 this->Info, UO, Result, UO->getSubExpr()->getType(),
4172 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004173}
4174
4175bool LValueExprEvaluator::VisitCompoundAssignOperator(
4176 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004177 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004178 return Error(CAO);
4179
Richard Smith3229b742013-05-05 21:17:10 +00004180 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004181
4182 // The overall lvalue result is the result of evaluating the LHS.
4183 if (!this->Visit(CAO->getLHS())) {
4184 if (Info.keepEvaluatingAfterFailure())
4185 Evaluate(RHS, this->Info, CAO->getRHS());
4186 return false;
4187 }
4188
Richard Smith3229b742013-05-05 21:17:10 +00004189 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4190 return false;
4191
Richard Smith43e77732013-05-07 04:50:00 +00004192 return handleCompoundAssignment(
4193 this->Info, CAO,
4194 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4195 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004196}
4197
4198bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004199 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4200 return Error(E);
4201
Richard Smith3229b742013-05-05 21:17:10 +00004202 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004203
4204 if (!this->Visit(E->getLHS())) {
4205 if (Info.keepEvaluatingAfterFailure())
4206 Evaluate(NewVal, this->Info, E->getRHS());
4207 return false;
4208 }
4209
Richard Smith3229b742013-05-05 21:17:10 +00004210 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4211 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004212
4213 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004214 NewVal);
4215}
4216
Eli Friedman9a156e52008-11-12 09:44:48 +00004217//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004218// Pointer Evaluation
4219//===----------------------------------------------------------------------===//
4220
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004221namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004222class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004223 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004224 LValue &Result;
4225
Peter Collingbournee9200682011-05-13 03:29:01 +00004226 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004227 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004228 return true;
4229 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004230public:
Mike Stump11289f42009-09-09 15:08:12 +00004231
John McCall45d55e42010-05-07 21:00:08 +00004232 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004233 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004234
Richard Smith2e312c82012-03-03 22:46:17 +00004235 bool Success(const APValue &V, const Expr *E) {
4236 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004237 return true;
4238 }
Richard Smithfddd3842011-12-30 21:15:51 +00004239 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004240 return Success((Expr*)0);
4241 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004242
John McCall45d55e42010-05-07 21:00:08 +00004243 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004244 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004245 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004246 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004247 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004248 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004249 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004250 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004251 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004252 bool VisitCallExpr(const CallExpr *E);
4253 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004254 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004255 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004257 }
Richard Smithd62306a2011-11-10 06:34:14 +00004258 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004259 // Can't look at 'this' when checking a potential constant expression.
4260 if (Info.CheckingPotentialConstantExpression)
4261 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004262 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004263 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004264 Result = *Info.CurrentCall->This;
4265 return true;
4266 }
John McCallc07a0c72011-02-17 10:25:35 +00004267
Eli Friedman449fe542009-03-23 04:56:01 +00004268 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004269};
Chris Lattner05706e882008-07-11 18:11:29 +00004270} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004271
John McCall45d55e42010-05-07 21:00:08 +00004272static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004273 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004274 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004275}
4276
John McCall45d55e42010-05-07 21:00:08 +00004277bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004278 if (E->getOpcode() != BO_Add &&
4279 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004280 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004281
Chris Lattner05706e882008-07-11 18:11:29 +00004282 const Expr *PExp = E->getLHS();
4283 const Expr *IExp = E->getRHS();
4284 if (IExp->getType()->isPointerType())
4285 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004286
Richard Smith253c2a32012-01-27 01:14:48 +00004287 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4288 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004289 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCall45d55e42010-05-07 21:00:08 +00004291 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004292 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004293 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004294
4295 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004296 if (E->getOpcode() == BO_Sub)
4297 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004298
Ted Kremenek28831752012-08-23 20:46:57 +00004299 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004300 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4301 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004302}
Eli Friedman9a156e52008-11-12 09:44:48 +00004303
John McCall45d55e42010-05-07 21:00:08 +00004304bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4305 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004306}
Mike Stump11289f42009-09-09 15:08:12 +00004307
Peter Collingbournee9200682011-05-13 03:29:01 +00004308bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4309 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004310
Eli Friedman847a2bc2009-12-27 05:43:15 +00004311 switch (E->getCastKind()) {
4312 default:
4313 break;
4314
John McCalle3027922010-08-25 11:45:40 +00004315 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004316 case CK_CPointerToObjCPointerCast:
4317 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004318 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004319 if (!Visit(SubExpr))
4320 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004321 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4322 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4323 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004324 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004325 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004326 if (SubExpr->getType()->isVoidPointerType())
4327 CCEDiag(E, diag::note_constexpr_invalid_cast)
4328 << 3 << SubExpr->getType();
4329 else
4330 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4331 }
Richard Smith96e0c102011-11-04 02:25:55 +00004332 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004333
Anders Carlsson18275092010-10-31 20:41:46 +00004334 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004335 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004336 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004337 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004338 if (!Result.Base && Result.Offset.isZero())
4339 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004340
Richard Smithd62306a2011-11-10 06:34:14 +00004341 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004342 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004343 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4344 castAs<PointerType>()->getPointeeType(),
4345 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004346
Richard Smith027bf112011-11-17 22:56:20 +00004347 case CK_BaseToDerived:
4348 if (!Visit(E->getSubExpr()))
4349 return false;
4350 if (!Result.Base && Result.Offset.isZero())
4351 return true;
4352 return HandleBaseToDerivedCast(Info, E, Result);
4353
Richard Smith0b0a0b62011-10-29 20:57:55 +00004354 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004355 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004356 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004357
John McCalle3027922010-08-25 11:45:40 +00004358 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004359 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4360
Richard Smith2e312c82012-03-03 22:46:17 +00004361 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004362 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004363 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004364
John McCall45d55e42010-05-07 21:00:08 +00004365 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004366 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4367 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004368 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004369 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004370 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004371 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004372 return true;
4373 } else {
4374 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004375 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004376 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004377 }
4378 }
John McCalle3027922010-08-25 11:45:40 +00004379 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004380 if (SubExpr->isGLValue()) {
4381 if (!EvaluateLValue(SubExpr, Result, Info))
4382 return false;
4383 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004384 Result.set(SubExpr, Info.CurrentCall->Index);
4385 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4386 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004387 return false;
4388 }
Richard Smith96e0c102011-11-04 02:25:55 +00004389 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004390 if (const ConstantArrayType *CAT
4391 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4392 Result.addArray(Info, E, CAT);
4393 else
4394 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004395 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004396
John McCalle3027922010-08-25 11:45:40 +00004397 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004398 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004399 }
4400
Richard Smith11562c52011-10-28 17:51:58 +00004401 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004402}
Chris Lattner05706e882008-07-11 18:11:29 +00004403
Peter Collingbournee9200682011-05-13 03:29:01 +00004404bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004405 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004406 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004407
Peter Collingbournee9200682011-05-13 03:29:01 +00004408 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004409}
Chris Lattner05706e882008-07-11 18:11:29 +00004410
4411//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004412// Member Pointer Evaluation
4413//===----------------------------------------------------------------------===//
4414
4415namespace {
4416class MemberPointerExprEvaluator
4417 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4418 MemberPtr &Result;
4419
4420 bool Success(const ValueDecl *D) {
4421 Result = MemberPtr(D);
4422 return true;
4423 }
4424public:
4425
4426 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4427 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4428
Richard Smith2e312c82012-03-03 22:46:17 +00004429 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004430 Result.setFrom(V);
4431 return true;
4432 }
Richard Smithfddd3842011-12-30 21:15:51 +00004433 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004434 return Success((const ValueDecl*)0);
4435 }
4436
4437 bool VisitCastExpr(const CastExpr *E);
4438 bool VisitUnaryAddrOf(const UnaryOperator *E);
4439};
4440} // end anonymous namespace
4441
4442static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4443 EvalInfo &Info) {
4444 assert(E->isRValue() && E->getType()->isMemberPointerType());
4445 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4446}
4447
4448bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4449 switch (E->getCastKind()) {
4450 default:
4451 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4452
4453 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004454 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004455 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004456
4457 case CK_BaseToDerivedMemberPointer: {
4458 if (!Visit(E->getSubExpr()))
4459 return false;
4460 if (E->path_empty())
4461 return true;
4462 // Base-to-derived member pointer casts store the path in derived-to-base
4463 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4464 // the wrong end of the derived->base arc, so stagger the path by one class.
4465 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4466 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4467 PathI != PathE; ++PathI) {
4468 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4469 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4470 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004471 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004472 }
4473 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4474 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004475 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004476 return true;
4477 }
4478
4479 case CK_DerivedToBaseMemberPointer:
4480 if (!Visit(E->getSubExpr()))
4481 return false;
4482 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4483 PathE = E->path_end(); PathI != PathE; ++PathI) {
4484 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4485 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4486 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004487 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004488 }
4489 return true;
4490 }
4491}
4492
4493bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4494 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4495 // member can be formed.
4496 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4497}
4498
4499//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004500// Record Evaluation
4501//===----------------------------------------------------------------------===//
4502
4503namespace {
4504 class RecordExprEvaluator
4505 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4506 const LValue &This;
4507 APValue &Result;
4508 public:
4509
4510 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4511 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4512
Richard Smith2e312c82012-03-03 22:46:17 +00004513 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004514 Result = V;
4515 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004516 }
Richard Smithfddd3842011-12-30 21:15:51 +00004517 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004518
Richard Smithe97cbd72011-11-11 04:05:33 +00004519 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004520 bool VisitInitListExpr(const InitListExpr *E);
4521 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4522 };
4523}
4524
Richard Smithfddd3842011-12-30 21:15:51 +00004525/// Perform zero-initialization on an object of non-union class type.
4526/// C++11 [dcl.init]p5:
4527/// To zero-initialize an object or reference of type T means:
4528/// [...]
4529/// -- if T is a (possibly cv-qualified) non-union class type,
4530/// each non-static data member and each base-class subobject is
4531/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004532static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4533 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004534 const LValue &This, APValue &Result) {
4535 assert(!RD->isUnion() && "Expected non-union class type");
4536 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4537 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4538 std::distance(RD->field_begin(), RD->field_end()));
4539
John McCalld7bca762012-05-01 00:38:49 +00004540 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004541 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4542
4543 if (CD) {
4544 unsigned Index = 0;
4545 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004546 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004547 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4548 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004549 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4550 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004551 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004552 Result.getStructBase(Index)))
4553 return false;
4554 }
4555 }
4556
Richard Smitha8105bc2012-01-06 16:39:00 +00004557 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4558 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004559 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004560 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004561 continue;
4562
4563 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004564 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004565 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004566
David Blaikie2d7c57e2012-04-30 02:36:29 +00004567 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004568 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004569 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004570 return false;
4571 }
4572
4573 return true;
4574}
4575
4576bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4577 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004578 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004579 if (RD->isUnion()) {
4580 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4581 // object's first non-static named data member is zero-initialized
4582 RecordDecl::field_iterator I = RD->field_begin();
4583 if (I == RD->field_end()) {
4584 Result = APValue((const FieldDecl*)0);
4585 return true;
4586 }
4587
4588 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004589 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004590 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004591 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004592 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004593 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004594 }
4595
Richard Smith5d108602012-02-17 00:44:16 +00004596 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004597 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004598 return false;
4599 }
4600
Richard Smitha8105bc2012-01-06 16:39:00 +00004601 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004602}
4603
Richard Smithe97cbd72011-11-11 04:05:33 +00004604bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4605 switch (E->getCastKind()) {
4606 default:
4607 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4608
4609 case CK_ConstructorConversion:
4610 return Visit(E->getSubExpr());
4611
4612 case CK_DerivedToBase:
4613 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004614 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004616 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004617 if (!DerivedObject.isStruct())
4618 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004619
4620 // Derived-to-base rvalue conversion: just slice off the derived part.
4621 APValue *Value = &DerivedObject;
4622 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4623 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4624 PathE = E->path_end(); PathI != PathE; ++PathI) {
4625 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4626 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4627 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4628 RD = Base;
4629 }
4630 Result = *Value;
4631 return true;
4632 }
4633 }
4634}
4635
Richard Smithd62306a2011-11-10 06:34:14 +00004636bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004637 // Cannot constant-evaluate std::initializer_list inits.
4638 if (E->initializesStdInitializerList())
4639 return false;
4640
Richard Smithd62306a2011-11-10 06:34:14 +00004641 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004642 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004643 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4644
4645 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004646 const FieldDecl *Field = E->getInitializedFieldInUnion();
4647 Result = APValue(Field);
4648 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004649 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004650
4651 // If the initializer list for a union does not contain any elements, the
4652 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004653 // FIXME: The element should be initialized from an initializer list.
4654 // Is this difference ever observable for initializer lists which
4655 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004656 ImplicitValueInitExpr VIE(Field->getType());
4657 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4658
Richard Smithd62306a2011-11-10 06:34:14 +00004659 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004660 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4661 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004662
4663 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4664 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4665 isa<CXXDefaultInitExpr>(InitExpr));
4666
Richard Smithb228a862012-02-15 02:18:13 +00004667 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004668 }
4669
4670 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4671 "initializer list for class with base classes");
4672 Result = APValue(APValue::UninitStruct(), 0,
4673 std::distance(RD->field_begin(), RD->field_end()));
4674 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004675 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004676 for (RecordDecl::field_iterator Field = RD->field_begin(),
4677 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4678 // Anonymous bit-fields are not considered members of the class for
4679 // purposes of aggregate initialization.
4680 if (Field->isUnnamedBitfield())
4681 continue;
4682
4683 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004684
Richard Smith253c2a32012-01-27 01:14:48 +00004685 bool HaveInit = ElementNo < E->getNumInits();
4686
4687 // FIXME: Diagnostics here should point to the end of the initializer
4688 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004689 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004690 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004691 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004692
4693 // Perform an implicit value-initialization for members beyond the end of
4694 // the initializer list.
4695 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004696 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004697
Richard Smith852c9db2013-04-20 22:23:05 +00004698 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4699 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4700 isa<CXXDefaultInitExpr>(Init));
4701
4702 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4703 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004704 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004705 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004706 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004707 }
4708 }
4709
Richard Smith253c2a32012-01-27 01:14:48 +00004710 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004711}
4712
4713bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4714 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004715 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4716
Richard Smithfddd3842011-12-30 21:15:51 +00004717 bool ZeroInit = E->requiresZeroInitialization();
4718 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004719 // If we've already performed zero-initialization, we're already done.
4720 if (!Result.isUninit())
4721 return true;
4722
Richard Smithfddd3842011-12-30 21:15:51 +00004723 if (ZeroInit)
4724 return ZeroInitialization(E);
4725
Richard Smithcc36f692011-12-22 02:22:31 +00004726 const CXXRecordDecl *RD = FD->getParent();
4727 if (RD->isUnion())
4728 Result = APValue((FieldDecl*)0);
4729 else
4730 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4731 std::distance(RD->field_begin(), RD->field_end()));
4732 return true;
4733 }
4734
Richard Smithd62306a2011-11-10 06:34:14 +00004735 const FunctionDecl *Definition = 0;
4736 FD->getBody(Definition);
4737
Richard Smith357362d2011-12-13 06:39:58 +00004738 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4739 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004740
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004741 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004742 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004743 if (const MaterializeTemporaryExpr *ME
4744 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4745 return Visit(ME->GetTemporaryExpr());
4746
Richard Smithfddd3842011-12-30 21:15:51 +00004747 if (ZeroInit && !ZeroInitialization(E))
4748 return false;
4749
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004750 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004751 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004752 cast<CXXConstructorDecl>(Definition), Info,
4753 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004754}
4755
4756static bool EvaluateRecord(const Expr *E, const LValue &This,
4757 APValue &Result, EvalInfo &Info) {
4758 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004759 "can't evaluate expression as a record rvalue");
4760 return RecordExprEvaluator(Info, This, Result).Visit(E);
4761}
4762
4763//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004764// Temporary Evaluation
4765//
4766// Temporaries are represented in the AST as rvalues, but generally behave like
4767// lvalues. The full-object of which the temporary is a subobject is implicitly
4768// materialized so that a reference can bind to it.
4769//===----------------------------------------------------------------------===//
4770namespace {
4771class TemporaryExprEvaluator
4772 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4773public:
4774 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4775 LValueExprEvaluatorBaseTy(Info, Result) {}
4776
4777 /// Visit an expression which constructs the value of this temporary.
4778 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004779 Result.set(E, Info.CurrentCall->Index);
4780 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004781 }
4782
4783 bool VisitCastExpr(const CastExpr *E) {
4784 switch (E->getCastKind()) {
4785 default:
4786 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4787
4788 case CK_ConstructorConversion:
4789 return VisitConstructExpr(E->getSubExpr());
4790 }
4791 }
4792 bool VisitInitListExpr(const InitListExpr *E) {
4793 return VisitConstructExpr(E);
4794 }
4795 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4796 return VisitConstructExpr(E);
4797 }
4798 bool VisitCallExpr(const CallExpr *E) {
4799 return VisitConstructExpr(E);
4800 }
4801};
4802} // end anonymous namespace
4803
4804/// Evaluate an expression of record type as a temporary.
4805static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004806 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004807 return TemporaryExprEvaluator(Info, Result).Visit(E);
4808}
4809
4810//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004811// Vector Evaluation
4812//===----------------------------------------------------------------------===//
4813
4814namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004815 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004816 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4817 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004818 public:
Mike Stump11289f42009-09-09 15:08:12 +00004819
Richard Smith2d406342011-10-22 21:10:00 +00004820 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4821 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004822
Richard Smith2d406342011-10-22 21:10:00 +00004823 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4824 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4825 // FIXME: remove this APValue copy.
4826 Result = APValue(V.data(), V.size());
4827 return true;
4828 }
Richard Smith2e312c82012-03-03 22:46:17 +00004829 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004830 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004831 Result = V;
4832 return true;
4833 }
Richard Smithfddd3842011-12-30 21:15:51 +00004834 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004835
Richard Smith2d406342011-10-22 21:10:00 +00004836 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004837 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004838 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004839 bool VisitInitListExpr(const InitListExpr *E);
4840 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004841 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004842 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004843 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004844 };
4845} // end anonymous namespace
4846
4847static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004848 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004849 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004850}
4851
Richard Smith2d406342011-10-22 21:10:00 +00004852bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4853 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004854 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004855
Richard Smith161f09a2011-12-06 22:44:34 +00004856 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004857 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004858
Eli Friedmanc757de22011-03-25 00:43:55 +00004859 switch (E->getCastKind()) {
4860 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004861 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004862 if (SETy->isIntegerType()) {
4863 APSInt IntResult;
4864 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004865 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004866 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004867 } else if (SETy->isRealFloatingType()) {
4868 APFloat F(0.0);
4869 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004870 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004871 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004872 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004873 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004874 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004875
4876 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004877 SmallVector<APValue, 4> Elts(NElts, Val);
4878 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004879 }
Eli Friedman803acb32011-12-22 03:51:45 +00004880 case CK_BitCast: {
4881 // Evaluate the operand into an APInt we can extract from.
4882 llvm::APInt SValInt;
4883 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4884 return false;
4885 // Extract the elements
4886 QualType EltTy = VTy->getElementType();
4887 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4888 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4889 SmallVector<APValue, 4> Elts;
4890 if (EltTy->isRealFloatingType()) {
4891 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004892 unsigned FloatEltSize = EltSize;
4893 if (&Sem == &APFloat::x87DoubleExtended)
4894 FloatEltSize = 80;
4895 for (unsigned i = 0; i < NElts; i++) {
4896 llvm::APInt Elt;
4897 if (BigEndian)
4898 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4899 else
4900 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004901 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004902 }
4903 } else if (EltTy->isIntegerType()) {
4904 for (unsigned i = 0; i < NElts; i++) {
4905 llvm::APInt Elt;
4906 if (BigEndian)
4907 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4908 else
4909 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4910 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4911 }
4912 } else {
4913 return Error(E);
4914 }
4915 return Success(Elts, E);
4916 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004917 default:
Richard Smith11562c52011-10-28 17:51:58 +00004918 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004919 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004920}
4921
Richard Smith2d406342011-10-22 21:10:00 +00004922bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004923VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004924 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004925 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004926 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004927
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004928 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004929 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004930
Eli Friedmanb9c71292012-01-03 23:24:20 +00004931 // The number of initializers can be less than the number of
4932 // vector elements. For OpenCL, this can be due to nested vector
4933 // initialization. For GCC compatibility, missing trailing elements
4934 // should be initialized with zeroes.
4935 unsigned CountInits = 0, CountElts = 0;
4936 while (CountElts < NumElements) {
4937 // Handle nested vector initialization.
4938 if (CountInits < NumInits
4939 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4940 APValue v;
4941 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4942 return Error(E);
4943 unsigned vlen = v.getVectorLength();
4944 for (unsigned j = 0; j < vlen; j++)
4945 Elements.push_back(v.getVectorElt(j));
4946 CountElts += vlen;
4947 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004948 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004949 if (CountInits < NumInits) {
4950 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004951 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004952 } else // trailing integer zero.
4953 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4954 Elements.push_back(APValue(sInt));
4955 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004956 } else {
4957 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004958 if (CountInits < NumInits) {
4959 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004960 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004961 } else // trailing float zero.
4962 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4963 Elements.push_back(APValue(f));
4964 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004965 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004966 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004967 }
Richard Smith2d406342011-10-22 21:10:00 +00004968 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004969}
4970
Richard Smith2d406342011-10-22 21:10:00 +00004971bool
Richard Smithfddd3842011-12-30 21:15:51 +00004972VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004973 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004974 QualType EltTy = VT->getElementType();
4975 APValue ZeroElement;
4976 if (EltTy->isIntegerType())
4977 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4978 else
4979 ZeroElement =
4980 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4981
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004982 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004983 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004984}
4985
Richard Smith2d406342011-10-22 21:10:00 +00004986bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004987 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004988 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004989}
4990
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004991//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004992// Array Evaluation
4993//===----------------------------------------------------------------------===//
4994
4995namespace {
4996 class ArrayExprEvaluator
4997 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004998 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004999 APValue &Result;
5000 public:
5001
Richard Smithd62306a2011-11-10 06:34:14 +00005002 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5003 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005004
5005 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005006 assert((V.isArray() || V.isLValue()) &&
5007 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005008 Result = V;
5009 return true;
5010 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005011
Richard Smithfddd3842011-12-30 21:15:51 +00005012 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005013 const ConstantArrayType *CAT =
5014 Info.Ctx.getAsConstantArrayType(E->getType());
5015 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005016 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005017
5018 Result = APValue(APValue::UninitArray(), 0,
5019 CAT->getSize().getZExtValue());
5020 if (!Result.hasArrayFiller()) return true;
5021
Richard Smithfddd3842011-12-30 21:15:51 +00005022 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005023 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005024 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005025 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005026 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005027 }
5028
Richard Smithf3e9e432011-11-07 09:22:26 +00005029 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005030 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005031 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5032 const LValue &Subobject,
5033 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005034 };
5035} // end anonymous namespace
5036
Richard Smithd62306a2011-11-10 06:34:14 +00005037static bool EvaluateArray(const Expr *E, const LValue &This,
5038 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005039 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005040 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005041}
5042
5043bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5044 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5045 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005046 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005047
Richard Smithca2cfbf2011-12-22 01:07:19 +00005048 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5049 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005050 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005051 LValue LV;
5052 if (!EvaluateLValue(E->getInit(0), LV, Info))
5053 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005054 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005055 LV.moveInto(Val);
5056 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005057 }
5058
Richard Smith253c2a32012-01-27 01:14:48 +00005059 bool Success = true;
5060
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005061 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5062 "zero-initialized array shouldn't have any initialized elts");
5063 APValue Filler;
5064 if (Result.isArray() && Result.hasArrayFiller())
5065 Filler = Result.getArrayFiller();
5066
Richard Smith9543c5e2013-04-22 14:44:29 +00005067 unsigned NumEltsToInit = E->getNumInits();
5068 unsigned NumElts = CAT->getSize().getZExtValue();
5069 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5070
5071 // If the initializer might depend on the array index, run it for each
5072 // array element. For now, just whitelist non-class value-initialization.
5073 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5074 NumEltsToInit = NumElts;
5075
5076 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005077
5078 // If the array was previously zero-initialized, preserve the
5079 // zero-initialized values.
5080 if (!Filler.isUninit()) {
5081 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5082 Result.getArrayInitializedElt(I) = Filler;
5083 if (Result.hasArrayFiller())
5084 Result.getArrayFiller() = Filler;
5085 }
5086
Richard Smithd62306a2011-11-10 06:34:14 +00005087 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005088 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005089 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5090 const Expr *Init =
5091 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005092 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005093 Info, Subobject, Init) ||
5094 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005095 CAT->getElementType(), 1)) {
5096 if (!Info.keepEvaluatingAfterFailure())
5097 return false;
5098 Success = false;
5099 }
Richard Smithd62306a2011-11-10 06:34:14 +00005100 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005101
Richard Smith9543c5e2013-04-22 14:44:29 +00005102 if (!Result.hasArrayFiller())
5103 return Success;
5104
5105 // If we get here, we have a trivial filler, which we can just evaluate
5106 // once and splat over the rest of the array elements.
5107 assert(FillerExpr && "no array filler for incomplete init list");
5108 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5109 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005110}
5111
Richard Smith027bf112011-11-17 22:56:20 +00005112bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005113 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5114}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005115
Richard Smith9543c5e2013-04-22 14:44:29 +00005116bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5117 const LValue &Subobject,
5118 APValue *Value,
5119 QualType Type) {
5120 bool HadZeroInit = !Value->isUninit();
5121
5122 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5123 unsigned N = CAT->getSize().getZExtValue();
5124
5125 // Preserve the array filler if we had prior zero-initialization.
5126 APValue Filler =
5127 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5128 : APValue();
5129
5130 *Value = APValue(APValue::UninitArray(), N, N);
5131
5132 if (HadZeroInit)
5133 for (unsigned I = 0; I != N; ++I)
5134 Value->getArrayInitializedElt(I) = Filler;
5135
5136 // Initialize the elements.
5137 LValue ArrayElt = Subobject;
5138 ArrayElt.addArray(Info, E, CAT);
5139 for (unsigned I = 0; I != N; ++I)
5140 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5141 CAT->getElementType()) ||
5142 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5143 CAT->getElementType(), 1))
5144 return false;
5145
5146 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005147 }
Richard Smith027bf112011-11-17 22:56:20 +00005148
Richard Smith9543c5e2013-04-22 14:44:29 +00005149 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005150 return Error(E);
5151
Richard Smith027bf112011-11-17 22:56:20 +00005152 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005153
Richard Smithfddd3842011-12-30 21:15:51 +00005154 bool ZeroInit = E->requiresZeroInitialization();
5155 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005156 if (HadZeroInit)
5157 return true;
5158
Richard Smithfddd3842011-12-30 21:15:51 +00005159 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005160 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005161 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005162 }
5163
Richard Smithcc36f692011-12-22 02:22:31 +00005164 const CXXRecordDecl *RD = FD->getParent();
5165 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005166 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005167 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005168 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005169 APValue(APValue::UninitStruct(), RD->getNumBases(),
5170 std::distance(RD->field_begin(), RD->field_end()));
5171 return true;
5172 }
5173
Richard Smith027bf112011-11-17 22:56:20 +00005174 const FunctionDecl *Definition = 0;
5175 FD->getBody(Definition);
5176
Richard Smith357362d2011-12-13 06:39:58 +00005177 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5178 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005179
Richard Smith9eae7232012-01-12 18:54:33 +00005180 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005181 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005182 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005183 return false;
5184 }
5185
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005186 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005187 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005188 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005189 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005190}
5191
Richard Smithf3e9e432011-11-07 09:22:26 +00005192//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005193// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005194//
5195// As a GNU extension, we support casting pointers to sufficiently-wide integer
5196// types and back in constant folding. Integer values are thus represented
5197// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005198//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005199
5200namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005201class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005202 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005203 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005204public:
Richard Smith2e312c82012-03-03 22:46:17 +00005205 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005206 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005207
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005208 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005209 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005210 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005211 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005212 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005213 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005214 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005215 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005216 return true;
5217 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005218 bool Success(const llvm::APSInt &SI, const Expr *E) {
5219 return Success(SI, E, Result);
5220 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005221
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005222 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005223 assert(E->getType()->isIntegralOrEnumerationType() &&
5224 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005225 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005226 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005227 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005228 Result.getInt().setIsUnsigned(
5229 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005230 return true;
5231 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005232 bool Success(const llvm::APInt &I, const Expr *E) {
5233 return Success(I, E, Result);
5234 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005235
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005236 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005237 assert(E->getType()->isIntegralOrEnumerationType() &&
5238 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005239 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005240 return true;
5241 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005242 bool Success(uint64_t Value, const Expr *E) {
5243 return Success(Value, E, Result);
5244 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005245
Ken Dyckdbc01912011-03-11 02:13:43 +00005246 bool Success(CharUnits Size, const Expr *E) {
5247 return Success(Size.getQuantity(), E);
5248 }
5249
Richard Smith2e312c82012-03-03 22:46:17 +00005250 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005251 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005252 Result = V;
5253 return true;
5254 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005255 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005256 }
Mike Stump11289f42009-09-09 15:08:12 +00005257
Richard Smithfddd3842011-12-30 21:15:51 +00005258 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005259
Peter Collingbournee9200682011-05-13 03:29:01 +00005260 //===--------------------------------------------------------------------===//
5261 // Visitor Methods
5262 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005263
Chris Lattner7174bf32008-07-12 00:38:25 +00005264 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005265 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005266 }
5267 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005268 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005269 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005270
5271 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5272 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005273 if (CheckReferencedDecl(E, E->getDecl()))
5274 return true;
5275
5276 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005277 }
5278 bool VisitMemberExpr(const MemberExpr *E) {
5279 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005280 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005281 return true;
5282 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005283
5284 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005285 }
5286
Peter Collingbournee9200682011-05-13 03:29:01 +00005287 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005288 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005289 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005290 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005291
Peter Collingbournee9200682011-05-13 03:29:01 +00005292 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005293 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005294
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005295 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005296 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005297 }
Mike Stump11289f42009-09-09 15:08:12 +00005298
Ted Kremeneke65b0862012-03-06 20:05:56 +00005299 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5300 return Success(E->getValue(), E);
5301 }
5302
Richard Smith4ce706a2011-10-11 21:43:33 +00005303 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005304 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005305 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005306 }
5307
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005308 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005309 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005310 }
5311
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005312 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5313 return Success(E->getValue(), E);
5314 }
5315
Douglas Gregor29c42f22012-02-24 07:38:34 +00005316 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5317 return Success(E->getValue(), E);
5318 }
5319
John Wiegley6242b6a2011-04-28 00:16:57 +00005320 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5321 return Success(E->getValue(), E);
5322 }
5323
John Wiegleyf9f65842011-04-25 06:54:41 +00005324 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5325 return Success(E->getValue(), E);
5326 }
5327
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005328 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005329 bool VisitUnaryImag(const UnaryOperator *E);
5330
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005331 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005332 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005333
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005334private:
Ken Dyck160146e2010-01-27 17:10:57 +00005335 CharUnits GetAlignOfExpr(const Expr *E);
5336 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005337 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005338 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005339 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005340};
Chris Lattner05706e882008-07-11 18:11:29 +00005341} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005342
Richard Smith11562c52011-10-28 17:51:58 +00005343/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5344/// produce either the integer value or a pointer.
5345///
5346/// GCC has a heinous extension which folds casts between pointer types and
5347/// pointer-sized integral types. We support this by allowing the evaluation of
5348/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5349/// Some simple arithmetic on such values is supported (they are treated much
5350/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005351static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005352 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005353 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005354 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005355}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005356
Richard Smithf57d8cb2011-12-09 22:58:01 +00005357static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005358 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005359 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005360 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005361 if (!Val.isInt()) {
5362 // FIXME: It would be better to produce the diagnostic for casting
5363 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005364 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005365 return false;
5366 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005367 Result = Val.getInt();
5368 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005369}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005370
Richard Smithf57d8cb2011-12-09 22:58:01 +00005371/// Check whether the given declaration can be directly converted to an integral
5372/// rvalue. If not, no diagnostic is produced; there are other things we can
5373/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005374bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005375 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005376 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005377 // Check for signedness/width mismatches between E type and ECD value.
5378 bool SameSign = (ECD->getInitVal().isSigned()
5379 == E->getType()->isSignedIntegerOrEnumerationType());
5380 bool SameWidth = (ECD->getInitVal().getBitWidth()
5381 == Info.Ctx.getIntWidth(E->getType()));
5382 if (SameSign && SameWidth)
5383 return Success(ECD->getInitVal(), E);
5384 else {
5385 // Get rid of mismatch (otherwise Success assertions will fail)
5386 // by computing a new value matching the type of E.
5387 llvm::APSInt Val = ECD->getInitVal();
5388 if (!SameSign)
5389 Val.setIsSigned(!ECD->getInitVal().isSigned());
5390 if (!SameWidth)
5391 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5392 return Success(Val, E);
5393 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005394 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005395 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005396}
5397
Chris Lattner86ee2862008-10-06 06:40:35 +00005398/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5399/// as GCC.
5400static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5401 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005402 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005403 enum gcc_type_class {
5404 no_type_class = -1,
5405 void_type_class, integer_type_class, char_type_class,
5406 enumeral_type_class, boolean_type_class,
5407 pointer_type_class, reference_type_class, offset_type_class,
5408 real_type_class, complex_type_class,
5409 function_type_class, method_type_class,
5410 record_type_class, union_type_class,
5411 array_type_class, string_type_class,
5412 lang_type_class
5413 };
Mike Stump11289f42009-09-09 15:08:12 +00005414
5415 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005416 // ideal, however it is what gcc does.
5417 if (E->getNumArgs() == 0)
5418 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005419
Chris Lattner86ee2862008-10-06 06:40:35 +00005420 QualType ArgTy = E->getArg(0)->getType();
5421 if (ArgTy->isVoidType())
5422 return void_type_class;
5423 else if (ArgTy->isEnumeralType())
5424 return enumeral_type_class;
5425 else if (ArgTy->isBooleanType())
5426 return boolean_type_class;
5427 else if (ArgTy->isCharType())
5428 return string_type_class; // gcc doesn't appear to use char_type_class
5429 else if (ArgTy->isIntegerType())
5430 return integer_type_class;
5431 else if (ArgTy->isPointerType())
5432 return pointer_type_class;
5433 else if (ArgTy->isReferenceType())
5434 return reference_type_class;
5435 else if (ArgTy->isRealType())
5436 return real_type_class;
5437 else if (ArgTy->isComplexType())
5438 return complex_type_class;
5439 else if (ArgTy->isFunctionType())
5440 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005441 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005442 return record_type_class;
5443 else if (ArgTy->isUnionType())
5444 return union_type_class;
5445 else if (ArgTy->isArrayType())
5446 return array_type_class;
5447 else if (ArgTy->isUnionType())
5448 return union_type_class;
5449 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005450 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005451}
5452
Richard Smith5fab0c92011-12-28 19:48:30 +00005453/// EvaluateBuiltinConstantPForLValue - Determine the result of
5454/// __builtin_constant_p when applied to the given lvalue.
5455///
5456/// An lvalue is only "constant" if it is a pointer or reference to the first
5457/// character of a string literal.
5458template<typename LValue>
5459static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005460 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005461 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5462}
5463
5464/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5465/// GCC as we can manage.
5466static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5467 QualType ArgType = Arg->getType();
5468
5469 // __builtin_constant_p always has one operand. The rules which gcc follows
5470 // are not precisely documented, but are as follows:
5471 //
5472 // - If the operand is of integral, floating, complex or enumeration type,
5473 // and can be folded to a known value of that type, it returns 1.
5474 // - If the operand and can be folded to a pointer to the first character
5475 // of a string literal (or such a pointer cast to an integral type), it
5476 // returns 1.
5477 //
5478 // Otherwise, it returns 0.
5479 //
5480 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5481 // its support for this does not currently work.
5482 if (ArgType->isIntegralOrEnumerationType()) {
5483 Expr::EvalResult Result;
5484 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5485 return false;
5486
5487 APValue &V = Result.Val;
5488 if (V.getKind() == APValue::Int)
5489 return true;
5490
5491 return EvaluateBuiltinConstantPForLValue(V);
5492 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5493 return Arg->isEvaluatable(Ctx);
5494 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5495 LValue LV;
5496 Expr::EvalStatus Status;
5497 EvalInfo Info(Ctx, Status);
5498 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5499 : EvaluatePointer(Arg, LV, Info)) &&
5500 !Status.HasSideEffects)
5501 return EvaluateBuiltinConstantPForLValue(LV);
5502 }
5503
5504 // Anything else isn't considered to be sufficiently constant.
5505 return false;
5506}
5507
John McCall95007602010-05-10 23:27:23 +00005508/// Retrieves the "underlying object type" of the given expression,
5509/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005510QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5511 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5512 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005513 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005514 } else if (const Expr *E = B.get<const Expr*>()) {
5515 if (isa<CompoundLiteralExpr>(E))
5516 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005517 }
5518
5519 return QualType();
5520}
5521
Peter Collingbournee9200682011-05-13 03:29:01 +00005522bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005523 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005524
5525 {
5526 // The operand of __builtin_object_size is never evaluated for side-effects.
5527 // If there are any, but we can determine the pointed-to object anyway, then
5528 // ignore the side-effects.
5529 SpeculativeEvaluationRAII SpeculativeEval(Info);
5530 if (!EvaluatePointer(E->getArg(0), Base, Info))
5531 return false;
5532 }
John McCall95007602010-05-10 23:27:23 +00005533
5534 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005535 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005536
Richard Smithce40ad62011-11-12 22:28:03 +00005537 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005538 if (T.isNull() ||
5539 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005540 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005541 T->isVariablyModifiedType() ||
5542 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005543 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005544
5545 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5546 CharUnits Offset = Base.getLValueOffset();
5547
5548 if (!Offset.isNegative() && Offset <= Size)
5549 Size -= Offset;
5550 else
5551 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005552 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005553}
5554
Peter Collingbournee9200682011-05-13 03:29:01 +00005555bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005556 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005557 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005558 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005559
5560 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005561 if (TryEvaluateBuiltinObjectSize(E))
5562 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005563
Richard Smith0421ce72012-08-07 04:16:51 +00005564 // If evaluating the argument has side-effects, we can't determine the size
5565 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5566 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005567 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005568 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005569 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005570 return Success(0, E);
5571 }
Mike Stump876387b2009-10-27 22:09:17 +00005572
Richard Smith01ade172012-05-23 04:13:20 +00005573 // Expression had no side effects, but we couldn't statically determine the
5574 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005575 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005576 }
5577
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005578 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005579 case Builtin::BI__builtin_bswap32:
5580 case Builtin::BI__builtin_bswap64: {
5581 APSInt Val;
5582 if (!EvaluateInteger(E->getArg(0), Val, Info))
5583 return false;
5584
5585 return Success(Val.byteSwap(), E);
5586 }
5587
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005588 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005589 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005590
Richard Smith5fab0c92011-12-28 19:48:30 +00005591 case Builtin::BI__builtin_constant_p:
5592 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005593
Chris Lattnerd545ad12009-09-23 06:06:36 +00005594 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005595 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005596 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005597 return Success(Operand, E);
5598 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005599
5600 case Builtin::BI__builtin_expect:
5601 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005602
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005603 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005604 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005605 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005606 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005607 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5608 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005609 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005610 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005611 case Builtin::BI__builtin_strlen:
5612 // As an extension, we support strlen() and __builtin_strlen() as constant
5613 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005614 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005615 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5616 // The string literal may have embedded null characters. Find the first
5617 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005618 StringRef Str = S->getString();
5619 StringRef::size_type Pos = Str.find(0);
5620 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005621 Str = Str.substr(0, Pos);
5622
5623 return Success(Str.size(), E);
5624 }
5625
Richard Smithf57d8cb2011-12-09 22:58:01 +00005626 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005627
Richard Smith01ba47d2012-04-13 00:45:38 +00005628 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005629 case Builtin::BI__atomic_is_lock_free:
5630 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005631 APSInt SizeVal;
5632 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5633 return false;
5634
5635 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5636 // of two less than the maximum inline atomic width, we know it is
5637 // lock-free. If the size isn't a power of two, or greater than the
5638 // maximum alignment where we promote atomics, we know it is not lock-free
5639 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5640 // the answer can only be determined at runtime; for example, 16-byte
5641 // atomics have lock-free implementations on some, but not all,
5642 // x86-64 processors.
5643
5644 // Check power-of-two.
5645 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005646 if (Size.isPowerOfTwo()) {
5647 // Check against inlining width.
5648 unsigned InlineWidthBits =
5649 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5650 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5651 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5652 Size == CharUnits::One() ||
5653 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5654 Expr::NPC_NeverValueDependent))
5655 // OK, we will inline appropriately-aligned operations of this size,
5656 // and _Atomic(T) is appropriately-aligned.
5657 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005658
Richard Smith01ba47d2012-04-13 00:45:38 +00005659 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5660 castAs<PointerType>()->getPointeeType();
5661 if (!PointeeType->isIncompleteType() &&
5662 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5663 // OK, we will inline operations on this object.
5664 return Success(1, E);
5665 }
5666 }
5667 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005668
Richard Smith01ba47d2012-04-13 00:45:38 +00005669 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5670 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005671 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005672 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005673}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005674
Richard Smith8b3497e2011-10-31 01:37:14 +00005675static bool HasSameBase(const LValue &A, const LValue &B) {
5676 if (!A.getLValueBase())
5677 return !B.getLValueBase();
5678 if (!B.getLValueBase())
5679 return false;
5680
Richard Smithce40ad62011-11-12 22:28:03 +00005681 if (A.getLValueBase().getOpaqueValue() !=
5682 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005683 const Decl *ADecl = GetLValueBaseDecl(A);
5684 if (!ADecl)
5685 return false;
5686 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005687 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005688 return false;
5689 }
5690
5691 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005692 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005693}
5694
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005695namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005696
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005697/// \brief Data recursive integer evaluator of certain binary operators.
5698///
5699/// We use a data recursive algorithm for binary operators so that we are able
5700/// to handle extreme cases of chained binary operators without causing stack
5701/// overflow.
5702class DataRecursiveIntBinOpEvaluator {
5703 struct EvalResult {
5704 APValue Val;
5705 bool Failed;
5706
5707 EvalResult() : Failed(false) { }
5708
5709 void swap(EvalResult &RHS) {
5710 Val.swap(RHS.Val);
5711 Failed = RHS.Failed;
5712 RHS.Failed = false;
5713 }
5714 };
5715
5716 struct Job {
5717 const Expr *E;
5718 EvalResult LHSResult; // meaningful only for binary operator expression.
5719 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5720
5721 Job() : StoredInfo(0) { }
5722 void startSpeculativeEval(EvalInfo &Info) {
5723 OldEvalStatus = Info.EvalStatus;
5724 Info.EvalStatus.Diag = 0;
5725 StoredInfo = &Info;
5726 }
5727 ~Job() {
5728 if (StoredInfo) {
5729 StoredInfo->EvalStatus = OldEvalStatus;
5730 }
5731 }
5732 private:
5733 EvalInfo *StoredInfo; // non-null if status changed.
5734 Expr::EvalStatus OldEvalStatus;
5735 };
5736
5737 SmallVector<Job, 16> Queue;
5738
5739 IntExprEvaluator &IntEval;
5740 EvalInfo &Info;
5741 APValue &FinalResult;
5742
5743public:
5744 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5745 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5746
5747 /// \brief True if \param E is a binary operator that we are going to handle
5748 /// data recursively.
5749 /// We handle binary operators that are comma, logical, or that have operands
5750 /// with integral or enumeration type.
5751 static bool shouldEnqueue(const BinaryOperator *E) {
5752 return E->getOpcode() == BO_Comma ||
5753 E->isLogicalOp() ||
5754 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5755 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005756 }
5757
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005758 bool Traverse(const BinaryOperator *E) {
5759 enqueue(E);
5760 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005761 while (!Queue.empty())
5762 process(PrevResult);
5763
5764 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005765
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005766 FinalResult.swap(PrevResult.Val);
5767 return true;
5768 }
5769
5770private:
5771 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5772 return IntEval.Success(Value, E, Result);
5773 }
5774 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5775 return IntEval.Success(Value, E, Result);
5776 }
5777 bool Error(const Expr *E) {
5778 return IntEval.Error(E);
5779 }
5780 bool Error(const Expr *E, diag::kind D) {
5781 return IntEval.Error(E, D);
5782 }
5783
5784 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5785 return Info.CCEDiag(E, D);
5786 }
5787
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005788 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5789 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005790 bool &SuppressRHSDiags);
5791
5792 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5793 const BinaryOperator *E, APValue &Result);
5794
5795 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5796 Result.Failed = !Evaluate(Result.Val, Info, E);
5797 if (Result.Failed)
5798 Result.Val = APValue();
5799 }
5800
Richard Trieuba4d0872012-03-21 23:30:30 +00005801 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005802
5803 void enqueue(const Expr *E) {
5804 E = E->IgnoreParens();
5805 Queue.resize(Queue.size()+1);
5806 Queue.back().E = E;
5807 Queue.back().Kind = Job::AnyExprKind;
5808 }
5809};
5810
5811}
5812
5813bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005814 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005815 bool &SuppressRHSDiags) {
5816 if (E->getOpcode() == BO_Comma) {
5817 // Ignore LHS but note if we could not evaluate it.
5818 if (LHSResult.Failed)
5819 Info.EvalStatus.HasSideEffects = true;
5820 return true;
5821 }
5822
5823 if (E->isLogicalOp()) {
5824 bool lhsResult;
5825 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005826 // We were able to evaluate the LHS, see if we can get away with not
5827 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005828 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005829 Success(lhsResult, E, LHSResult.Val);
5830 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005831 }
5832 } else {
5833 // Since we weren't able to evaluate the left hand side, it
5834 // must have had side effects.
5835 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005836
5837 // We can't evaluate the LHS; however, sometimes the result
5838 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5839 // Don't ignore RHS and suppress diagnostics from this arm.
5840 SuppressRHSDiags = true;
5841 }
5842
5843 return true;
5844 }
5845
5846 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5847 E->getRHS()->getType()->isIntegralOrEnumerationType());
5848
5849 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005850 return false; // Ignore RHS;
5851
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005852 return true;
5853}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005854
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005855bool DataRecursiveIntBinOpEvaluator::
5856 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5857 const BinaryOperator *E, APValue &Result) {
5858 if (E->getOpcode() == BO_Comma) {
5859 if (RHSResult.Failed)
5860 return false;
5861 Result = RHSResult.Val;
5862 return true;
5863 }
5864
5865 if (E->isLogicalOp()) {
5866 bool lhsResult, rhsResult;
5867 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5868 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5869
5870 if (LHSIsOK) {
5871 if (RHSIsOK) {
5872 if (E->getOpcode() == BO_LOr)
5873 return Success(lhsResult || rhsResult, E, Result);
5874 else
5875 return Success(lhsResult && rhsResult, E, Result);
5876 }
5877 } else {
5878 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005879 // We can't evaluate the LHS; however, sometimes the result
5880 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5881 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005882 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005883 }
5884 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005885
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005886 return false;
5887 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005888
5889 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5890 E->getRHS()->getType()->isIntegralOrEnumerationType());
5891
5892 if (LHSResult.Failed || RHSResult.Failed)
5893 return false;
5894
5895 const APValue &LHSVal = LHSResult.Val;
5896 const APValue &RHSVal = RHSResult.Val;
5897
5898 // Handle cases like (unsigned long)&a + 4.
5899 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5900 Result = LHSVal;
5901 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5902 RHSVal.getInt().getZExtValue());
5903 if (E->getOpcode() == BO_Add)
5904 Result.getLValueOffset() += AdditionalOffset;
5905 else
5906 Result.getLValueOffset() -= AdditionalOffset;
5907 return true;
5908 }
5909
5910 // Handle cases like 4 + (unsigned long)&a
5911 if (E->getOpcode() == BO_Add &&
5912 RHSVal.isLValue() && LHSVal.isInt()) {
5913 Result = RHSVal;
5914 Result.getLValueOffset() += CharUnits::fromQuantity(
5915 LHSVal.getInt().getZExtValue());
5916 return true;
5917 }
5918
5919 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5920 // Handle (intptr_t)&&A - (intptr_t)&&B.
5921 if (!LHSVal.getLValueOffset().isZero() ||
5922 !RHSVal.getLValueOffset().isZero())
5923 return false;
5924 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5925 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5926 if (!LHSExpr || !RHSExpr)
5927 return false;
5928 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5929 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5930 if (!LHSAddrExpr || !RHSAddrExpr)
5931 return false;
5932 // Make sure both labels come from the same function.
5933 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5934 RHSAddrExpr->getLabel()->getDeclContext())
5935 return false;
5936 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5937 return true;
5938 }
Richard Smith43e77732013-05-07 04:50:00 +00005939
5940 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005941 if (!LHSVal.isInt() || !RHSVal.isInt())
5942 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005943
5944 // Set up the width and signedness manually, in case it can't be deduced
5945 // from the operation we're performing.
5946 // FIXME: Don't do this in the cases where we can deduce it.
5947 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5948 E->getType()->isUnsignedIntegerOrEnumerationType());
5949 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5950 RHSVal.getInt(), Value))
5951 return false;
5952 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005953}
5954
Richard Trieuba4d0872012-03-21 23:30:30 +00005955void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005956 Job &job = Queue.back();
5957
5958 switch (job.Kind) {
5959 case Job::AnyExprKind: {
5960 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5961 if (shouldEnqueue(Bop)) {
5962 job.Kind = Job::BinOpKind;
5963 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005964 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005965 }
5966 }
5967
5968 EvaluateExpr(job.E, Result);
5969 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005970 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005971 }
5972
5973 case Job::BinOpKind: {
5974 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005975 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005976 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005977 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005978 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005979 }
5980 if (SuppressRHSDiags)
5981 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005982 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005983 job.Kind = Job::BinOpVisitedLHSKind;
5984 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005985 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005986 }
5987
5988 case Job::BinOpVisitedLHSKind: {
5989 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5990 EvalResult RHS;
5991 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005992 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005993 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005994 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005995 }
5996 }
5997
5998 llvm_unreachable("Invalid Job::Kind!");
5999}
6000
6001bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6002 if (E->isAssignmentOp())
6003 return Error(E);
6004
6005 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6006 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006007
Anders Carlssonacc79812008-11-16 07:17:21 +00006008 QualType LHSTy = E->getLHS()->getType();
6009 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006010
6011 if (LHSTy->isAnyComplexType()) {
6012 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006013 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006014
Richard Smith253c2a32012-01-27 01:14:48 +00006015 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6016 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006017 return false;
6018
Richard Smith253c2a32012-01-27 01:14:48 +00006019 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006020 return false;
6021
6022 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006023 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006024 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006025 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006026 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6027
John McCalle3027922010-08-25 11:45:40 +00006028 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006029 return Success((CR_r == APFloat::cmpEqual &&
6030 CR_i == APFloat::cmpEqual), E);
6031 else {
John McCalle3027922010-08-25 11:45:40 +00006032 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006033 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006034 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006035 CR_r == APFloat::cmpLessThan ||
6036 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006037 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006038 CR_i == APFloat::cmpLessThan ||
6039 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006040 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006041 } else {
John McCalle3027922010-08-25 11:45:40 +00006042 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006043 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6044 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6045 else {
John McCalle3027922010-08-25 11:45:40 +00006046 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006047 "Invalid compex comparison.");
6048 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6049 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6050 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006051 }
6052 }
Mike Stump11289f42009-09-09 15:08:12 +00006053
Anders Carlssonacc79812008-11-16 07:17:21 +00006054 if (LHSTy->isRealFloatingType() &&
6055 RHSTy->isRealFloatingType()) {
6056 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006057
Richard Smith253c2a32012-01-27 01:14:48 +00006058 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6059 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006060 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006061
Richard Smith253c2a32012-01-27 01:14:48 +00006062 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006063 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006064
Anders Carlssonacc79812008-11-16 07:17:21 +00006065 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006066
Anders Carlssonacc79812008-11-16 07:17:21 +00006067 switch (E->getOpcode()) {
6068 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006069 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006070 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006071 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006072 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006073 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006074 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006075 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006076 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006077 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006078 E);
John McCalle3027922010-08-25 11:45:40 +00006079 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006080 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006081 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006082 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006083 || CR == APFloat::cmpLessThan
6084 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006085 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006086 }
Mike Stump11289f42009-09-09 15:08:12 +00006087
Eli Friedmana38da572009-04-28 19:17:36 +00006088 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006089 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006090 LValue LHSValue, RHSValue;
6091
6092 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6093 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006094 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006095
Richard Smith253c2a32012-01-27 01:14:48 +00006096 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006097 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006098
Richard Smith8b3497e2011-10-31 01:37:14 +00006099 // Reject differing bases from the normal codepath; we special-case
6100 // comparisons to null.
6101 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006102 if (E->getOpcode() == BO_Sub) {
6103 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006104 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6105 return false;
6106 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006107 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006108 if (!LHSExpr || !RHSExpr)
6109 return false;
6110 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6111 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6112 if (!LHSAddrExpr || !RHSAddrExpr)
6113 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006114 // Make sure both labels come from the same function.
6115 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6116 RHSAddrExpr->getLabel()->getDeclContext())
6117 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006118 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006119 return true;
6120 }
Richard Smith83c68212011-10-31 05:11:32 +00006121 // Inequalities and subtractions between unrelated pointers have
6122 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006123 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006124 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006125 // A constant address may compare equal to the address of a symbol.
6126 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006127 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006128 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6129 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006130 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006131 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006132 // distinct addresses. In clang, the result of such a comparison is
6133 // unspecified, so it is not a constant expression. However, we do know
6134 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006135 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6136 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006137 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006138 // We can't tell whether weak symbols will end up pointing to the same
6139 // object.
6140 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006141 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006142 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006143 // (Note that clang defaults to -fmerge-all-constants, which can
6144 // lead to inconsistent results for comparisons involving the address
6145 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006146 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006147 }
Eli Friedman64004332009-03-23 04:38:34 +00006148
Richard Smith1b470412012-02-01 08:10:20 +00006149 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6150 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6151
Richard Smith84f6dcf2012-02-02 01:16:57 +00006152 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6153 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6154
John McCalle3027922010-08-25 11:45:40 +00006155 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006156 // C++11 [expr.add]p6:
6157 // Unless both pointers point to elements of the same array object, or
6158 // one past the last element of the array object, the behavior is
6159 // undefined.
6160 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6161 !AreElementsOfSameArray(getType(LHSValue.Base),
6162 LHSDesignator, RHSDesignator))
6163 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6164
Chris Lattner882bdf22010-04-20 17:13:14 +00006165 QualType Type = E->getLHS()->getType();
6166 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006167
Richard Smithd62306a2011-11-10 06:34:14 +00006168 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006169 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006170 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006171
Richard Smith1b470412012-02-01 08:10:20 +00006172 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6173 // and produce incorrect results when it overflows. Such behavior
6174 // appears to be non-conforming, but is common, so perhaps we should
6175 // assume the standard intended for such cases to be undefined behavior
6176 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006177
Richard Smith1b470412012-02-01 08:10:20 +00006178 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6179 // overflow in the final conversion to ptrdiff_t.
6180 APSInt LHS(
6181 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6182 APSInt RHS(
6183 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6184 APSInt ElemSize(
6185 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6186 APSInt TrueResult = (LHS - RHS) / ElemSize;
6187 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6188
6189 if (Result.extend(65) != TrueResult)
6190 HandleOverflow(Info, E, TrueResult, E->getType());
6191 return Success(Result, E);
6192 }
Richard Smithde21b242012-01-31 06:41:30 +00006193
6194 // C++11 [expr.rel]p3:
6195 // Pointers to void (after pointer conversions) can be compared, with a
6196 // result defined as follows: If both pointers represent the same
6197 // address or are both the null pointer value, the result is true if the
6198 // operator is <= or >= and false otherwise; otherwise the result is
6199 // unspecified.
6200 // We interpret this as applying to pointers to *cv* void.
6201 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006202 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006203 CCEDiag(E, diag::note_constexpr_void_comparison);
6204
Richard Smith84f6dcf2012-02-02 01:16:57 +00006205 // C++11 [expr.rel]p2:
6206 // - If two pointers point to non-static data members of the same object,
6207 // or to subobjects or array elements fo such members, recursively, the
6208 // pointer to the later declared member compares greater provided the
6209 // two members have the same access control and provided their class is
6210 // not a union.
6211 // [...]
6212 // - Otherwise pointer comparisons are unspecified.
6213 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6214 E->isRelationalOp()) {
6215 bool WasArrayIndex;
6216 unsigned Mismatch =
6217 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6218 RHSDesignator, WasArrayIndex);
6219 // At the point where the designators diverge, the comparison has a
6220 // specified value if:
6221 // - we are comparing array indices
6222 // - we are comparing fields of a union, or fields with the same access
6223 // Otherwise, the result is unspecified and thus the comparison is not a
6224 // constant expression.
6225 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6226 Mismatch < RHSDesignator.Entries.size()) {
6227 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6228 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6229 if (!LF && !RF)
6230 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6231 else if (!LF)
6232 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6233 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6234 << RF->getParent() << RF;
6235 else if (!RF)
6236 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6237 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6238 << LF->getParent() << LF;
6239 else if (!LF->getParent()->isUnion() &&
6240 LF->getAccess() != RF->getAccess())
6241 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6242 << LF << LF->getAccess() << RF << RF->getAccess()
6243 << LF->getParent();
6244 }
6245 }
6246
Eli Friedman6c31cb42012-04-16 04:30:08 +00006247 // The comparison here must be unsigned, and performed with the same
6248 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006249 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6250 uint64_t CompareLHS = LHSOffset.getQuantity();
6251 uint64_t CompareRHS = RHSOffset.getQuantity();
6252 assert(PtrSize <= 64 && "Unexpected pointer width");
6253 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6254 CompareLHS &= Mask;
6255 CompareRHS &= Mask;
6256
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006257 // If there is a base and this is a relational operator, we can only
6258 // compare pointers within the object in question; otherwise, the result
6259 // depends on where the object is located in memory.
6260 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6261 QualType BaseTy = getType(LHSValue.Base);
6262 if (BaseTy->isIncompleteType())
6263 return Error(E);
6264 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6265 uint64_t OffsetLimit = Size.getQuantity();
6266 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6267 return Error(E);
6268 }
6269
Richard Smith8b3497e2011-10-31 01:37:14 +00006270 switch (E->getOpcode()) {
6271 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006272 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6273 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6274 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6275 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6276 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6277 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006278 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006279 }
6280 }
Richard Smith7bb00672012-02-01 01:42:44 +00006281
6282 if (LHSTy->isMemberPointerType()) {
6283 assert(E->isEqualityOp() && "unexpected member pointer operation");
6284 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6285
6286 MemberPtr LHSValue, RHSValue;
6287
6288 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6289 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6290 return false;
6291
6292 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6293 return false;
6294
6295 // C++11 [expr.eq]p2:
6296 // If both operands are null, they compare equal. Otherwise if only one is
6297 // null, they compare unequal.
6298 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6299 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6300 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6301 }
6302
6303 // Otherwise if either is a pointer to a virtual member function, the
6304 // result is unspecified.
6305 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6306 if (MD->isVirtual())
6307 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6308 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6309 if (MD->isVirtual())
6310 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6311
6312 // Otherwise they compare equal if and only if they would refer to the
6313 // same member of the same most derived object or the same subobject if
6314 // they were dereferenced with a hypothetical object of the associated
6315 // class type.
6316 bool Equal = LHSValue == RHSValue;
6317 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6318 }
6319
Richard Smithab44d9b2012-02-14 22:35:28 +00006320 if (LHSTy->isNullPtrType()) {
6321 assert(E->isComparisonOp() && "unexpected nullptr operation");
6322 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6323 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6324 // are compared, the result is true of the operator is <=, >= or ==, and
6325 // false otherwise.
6326 BinaryOperator::Opcode Opcode = E->getOpcode();
6327 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6328 }
6329
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006330 assert((!LHSTy->isIntegralOrEnumerationType() ||
6331 !RHSTy->isIntegralOrEnumerationType()) &&
6332 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6333 // We can't continue from here for non-integral types.
6334 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006335}
6336
Ken Dyck160146e2010-01-27 17:10:57 +00006337CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006338 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6339 // result shall be the alignment of the referenced type."
6340 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6341 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006342
6343 // __alignof is defined to return the preferred alignment.
6344 return Info.Ctx.toCharUnitsFromBits(
6345 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006346}
6347
Ken Dyck160146e2010-01-27 17:10:57 +00006348CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006349 E = E->IgnoreParens();
6350
John McCall768439e2013-05-06 07:40:34 +00006351 // The kinds of expressions that we have special-case logic here for
6352 // should be kept up to date with the special checks for those
6353 // expressions in Sema.
6354
Chris Lattner68061312009-01-24 21:53:27 +00006355 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006356 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006357 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006358 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6359 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006360
Chris Lattner68061312009-01-24 21:53:27 +00006361 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006362 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6363 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006364
Chris Lattner24aeeab2009-01-24 21:09:06 +00006365 return GetAlignOfType(E->getType());
6366}
6367
6368
Peter Collingbournee190dee2011-03-11 19:24:49 +00006369/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6370/// a result as the expression's type.
6371bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6372 const UnaryExprOrTypeTraitExpr *E) {
6373 switch(E->getKind()) {
6374 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006375 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006376 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006377 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006378 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006379 }
Eli Friedman64004332009-03-23 04:38:34 +00006380
Peter Collingbournee190dee2011-03-11 19:24:49 +00006381 case UETT_VecStep: {
6382 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006383
Peter Collingbournee190dee2011-03-11 19:24:49 +00006384 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006385 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006386
Peter Collingbournee190dee2011-03-11 19:24:49 +00006387 // The vec_step built-in functions that take a 3-component
6388 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6389 if (n == 3)
6390 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006391
Peter Collingbournee190dee2011-03-11 19:24:49 +00006392 return Success(n, E);
6393 } else
6394 return Success(1, E);
6395 }
6396
6397 case UETT_SizeOf: {
6398 QualType SrcTy = E->getTypeOfArgument();
6399 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6400 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006401 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6402 SrcTy = Ref->getPointeeType();
6403
Richard Smithd62306a2011-11-10 06:34:14 +00006404 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006405 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006406 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006407 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006408 }
6409 }
6410
6411 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006412}
6413
Peter Collingbournee9200682011-05-13 03:29:01 +00006414bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006415 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006416 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006417 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006418 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006419 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006420 for (unsigned i = 0; i != n; ++i) {
6421 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6422 switch (ON.getKind()) {
6423 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006424 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006425 APSInt IdxResult;
6426 if (!EvaluateInteger(Idx, IdxResult, Info))
6427 return false;
6428 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6429 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006430 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006431 CurrentType = AT->getElementType();
6432 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6433 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006434 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006435 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006436
Douglas Gregor882211c2010-04-28 22:16:22 +00006437 case OffsetOfExpr::OffsetOfNode::Field: {
6438 FieldDecl *MemberDecl = ON.getField();
6439 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006440 if (!RT)
6441 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006442 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006443 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006444 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006445 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006446 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006447 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006448 CurrentType = MemberDecl->getType().getNonReferenceType();
6449 break;
6450 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006451
Douglas Gregor882211c2010-04-28 22:16:22 +00006452 case OffsetOfExpr::OffsetOfNode::Identifier:
6453 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006454
Douglas Gregord1702062010-04-29 00:18:15 +00006455 case OffsetOfExpr::OffsetOfNode::Base: {
6456 CXXBaseSpecifier *BaseSpec = ON.getBase();
6457 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006458 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006459
6460 // Find the layout of the class whose base we are looking into.
6461 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006462 if (!RT)
6463 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006464 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006465 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006466 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6467
6468 // Find the base class itself.
6469 CurrentType = BaseSpec->getType();
6470 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6471 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006472 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006473
6474 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006475 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006476 break;
6477 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006478 }
6479 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006480 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006481}
6482
Chris Lattnere13042c2008-07-11 19:10:17 +00006483bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006484 switch (E->getOpcode()) {
6485 default:
6486 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6487 // See C99 6.6p3.
6488 return Error(E);
6489 case UO_Extension:
6490 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6491 // If so, we could clear the diagnostic ID.
6492 return Visit(E->getSubExpr());
6493 case UO_Plus:
6494 // The result is just the value.
6495 return Visit(E->getSubExpr());
6496 case UO_Minus: {
6497 if (!Visit(E->getSubExpr()))
6498 return false;
6499 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006500 const APSInt &Value = Result.getInt();
6501 if (Value.isSigned() && Value.isMinSignedValue())
6502 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6503 E->getType());
6504 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006505 }
6506 case UO_Not: {
6507 if (!Visit(E->getSubExpr()))
6508 return false;
6509 if (!Result.isInt()) return Error(E);
6510 return Success(~Result.getInt(), E);
6511 }
6512 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006513 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006514 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006515 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006516 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006517 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006518 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006519}
Mike Stump11289f42009-09-09 15:08:12 +00006520
Chris Lattner477c4be2008-07-12 01:15:53 +00006521/// HandleCast - This is used to evaluate implicit or explicit casts where the
6522/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006523bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6524 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006525 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006526 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006527
Eli Friedmanc757de22011-03-25 00:43:55 +00006528 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006529 case CK_BaseToDerived:
6530 case CK_DerivedToBase:
6531 case CK_UncheckedDerivedToBase:
6532 case CK_Dynamic:
6533 case CK_ToUnion:
6534 case CK_ArrayToPointerDecay:
6535 case CK_FunctionToPointerDecay:
6536 case CK_NullToPointer:
6537 case CK_NullToMemberPointer:
6538 case CK_BaseToDerivedMemberPointer:
6539 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006540 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006541 case CK_ConstructorConversion:
6542 case CK_IntegralToPointer:
6543 case CK_ToVoid:
6544 case CK_VectorSplat:
6545 case CK_IntegralToFloating:
6546 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006547 case CK_CPointerToObjCPointerCast:
6548 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006549 case CK_AnyPointerToBlockPointerCast:
6550 case CK_ObjCObjectLValueCast:
6551 case CK_FloatingRealToComplex:
6552 case CK_FloatingComplexToReal:
6553 case CK_FloatingComplexCast:
6554 case CK_FloatingComplexToIntegralComplex:
6555 case CK_IntegralRealToComplex:
6556 case CK_IntegralComplexCast:
6557 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006558 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006559 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006560 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006561 llvm_unreachable("invalid cast kind for integral value");
6562
Eli Friedman9faf2f92011-03-25 19:07:11 +00006563 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006564 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006565 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006566 case CK_ARCProduceObject:
6567 case CK_ARCConsumeObject:
6568 case CK_ARCReclaimReturnedObject:
6569 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006570 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006571 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006572
Richard Smith4ef685b2012-01-17 21:17:26 +00006573 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006574 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006575 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006576 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006577 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006578
6579 case CK_MemberPointerToBoolean:
6580 case CK_PointerToBoolean:
6581 case CK_IntegralToBoolean:
6582 case CK_FloatingToBoolean:
6583 case CK_FloatingComplexToBoolean:
6584 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006585 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006586 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006587 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006588 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006589 }
6590
Eli Friedmanc757de22011-03-25 00:43:55 +00006591 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006592 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006593 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006594
Eli Friedman742421e2009-02-20 01:15:07 +00006595 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006596 // Allow casts of address-of-label differences if they are no-ops
6597 // or narrowing. (The narrowing case isn't actually guaranteed to
6598 // be constant-evaluatable except in some narrow cases which are hard
6599 // to detect here. We let it through on the assumption the user knows
6600 // what they are doing.)
6601 if (Result.isAddrLabelDiff())
6602 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006603 // Only allow casts of lvalues if they are lossless.
6604 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6605 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006606
Richard Smith911e1422012-01-30 22:27:01 +00006607 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6608 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Eli Friedmanc757de22011-03-25 00:43:55 +00006611 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006612 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6613
John McCall45d55e42010-05-07 21:00:08 +00006614 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006615 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006616 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006617
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006618 if (LV.getLValueBase()) {
6619 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006620 // FIXME: Allow a larger integer size than the pointer size, and allow
6621 // narrowing back down to pointer width in subsequent integral casts.
6622 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006623 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006624 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006625
Richard Smithcf74da72011-11-16 07:18:12 +00006626 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006627 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006628 return true;
6629 }
6630
Ken Dyck02990832010-01-15 12:37:54 +00006631 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6632 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006633 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006634 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006635
Eli Friedmanc757de22011-03-25 00:43:55 +00006636 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006637 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006638 if (!EvaluateComplex(SubExpr, C, Info))
6639 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006640 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006641 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006642
Eli Friedmanc757de22011-03-25 00:43:55 +00006643 case CK_FloatingToIntegral: {
6644 APFloat F(0.0);
6645 if (!EvaluateFloat(SubExpr, F, Info))
6646 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006647
Richard Smith357362d2011-12-13 06:39:58 +00006648 APSInt Value;
6649 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6650 return false;
6651 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006652 }
6653 }
Mike Stump11289f42009-09-09 15:08:12 +00006654
Eli Friedmanc757de22011-03-25 00:43:55 +00006655 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006656}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006657
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006658bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6659 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006660 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006661 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6662 return false;
6663 if (!LV.isComplexInt())
6664 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006665 return Success(LV.getComplexIntReal(), E);
6666 }
6667
6668 return Visit(E->getSubExpr());
6669}
6670
Eli Friedman4e7a2412009-02-27 04:45:43 +00006671bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006672 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006673 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006674 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6675 return false;
6676 if (!LV.isComplexInt())
6677 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006678 return Success(LV.getComplexIntImag(), E);
6679 }
6680
Richard Smith4a678122011-10-24 18:44:57 +00006681 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006682 return Success(0, E);
6683}
6684
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006685bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6686 return Success(E->getPackLength(), E);
6687}
6688
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006689bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6690 return Success(E->getValue(), E);
6691}
6692
Chris Lattner05706e882008-07-11 18:11:29 +00006693//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006694// Float Evaluation
6695//===----------------------------------------------------------------------===//
6696
6697namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006698class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006699 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006700 APFloat &Result;
6701public:
6702 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006703 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006704
Richard Smith2e312c82012-03-03 22:46:17 +00006705 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006706 Result = V.getFloat();
6707 return true;
6708 }
Eli Friedman24c01542008-08-22 00:06:13 +00006709
Richard Smithfddd3842011-12-30 21:15:51 +00006710 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006711 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6712 return true;
6713 }
6714
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006715 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006716
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006717 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006718 bool VisitBinaryOperator(const BinaryOperator *E);
6719 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006720 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006721
John McCallb1fb0d32010-05-07 22:08:54 +00006722 bool VisitUnaryReal(const UnaryOperator *E);
6723 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006724
Richard Smithfddd3842011-12-30 21:15:51 +00006725 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006726};
6727} // end anonymous namespace
6728
6729static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006730 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006731 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006732}
6733
Jay Foad39c79802011-01-12 09:06:06 +00006734static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006735 QualType ResultTy,
6736 const Expr *Arg,
6737 bool SNaN,
6738 llvm::APFloat &Result) {
6739 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6740 if (!S) return false;
6741
6742 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6743
6744 llvm::APInt fill;
6745
6746 // Treat empty strings as if they were zero.
6747 if (S->getString().empty())
6748 fill = llvm::APInt(32, 0);
6749 else if (S->getString().getAsInteger(0, fill))
6750 return false;
6751
6752 if (SNaN)
6753 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6754 else
6755 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6756 return true;
6757}
6758
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006759bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006760 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006761 default:
6762 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6763
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006764 case Builtin::BI__builtin_huge_val:
6765 case Builtin::BI__builtin_huge_valf:
6766 case Builtin::BI__builtin_huge_vall:
6767 case Builtin::BI__builtin_inf:
6768 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006769 case Builtin::BI__builtin_infl: {
6770 const llvm::fltSemantics &Sem =
6771 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006772 Result = llvm::APFloat::getInf(Sem);
6773 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006774 }
Mike Stump11289f42009-09-09 15:08:12 +00006775
John McCall16291492010-02-28 13:00:19 +00006776 case Builtin::BI__builtin_nans:
6777 case Builtin::BI__builtin_nansf:
6778 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006779 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6780 true, Result))
6781 return Error(E);
6782 return true;
John McCall16291492010-02-28 13:00:19 +00006783
Chris Lattner0b7282e2008-10-06 06:31:58 +00006784 case Builtin::BI__builtin_nan:
6785 case Builtin::BI__builtin_nanf:
6786 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006787 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006788 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006789 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6790 false, Result))
6791 return Error(E);
6792 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006793
6794 case Builtin::BI__builtin_fabs:
6795 case Builtin::BI__builtin_fabsf:
6796 case Builtin::BI__builtin_fabsl:
6797 if (!EvaluateFloat(E->getArg(0), Result, Info))
6798 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006799
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006800 if (Result.isNegative())
6801 Result.changeSign();
6802 return true;
6803
Mike Stump11289f42009-09-09 15:08:12 +00006804 case Builtin::BI__builtin_copysign:
6805 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006806 case Builtin::BI__builtin_copysignl: {
6807 APFloat RHS(0.);
6808 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6809 !EvaluateFloat(E->getArg(1), RHS, Info))
6810 return false;
6811 Result.copySign(RHS);
6812 return true;
6813 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006814 }
6815}
6816
John McCallb1fb0d32010-05-07 22:08:54 +00006817bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006818 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6819 ComplexValue CV;
6820 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6821 return false;
6822 Result = CV.FloatReal;
6823 return true;
6824 }
6825
6826 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006827}
6828
6829bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006830 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6831 ComplexValue CV;
6832 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6833 return false;
6834 Result = CV.FloatImag;
6835 return true;
6836 }
6837
Richard Smith4a678122011-10-24 18:44:57 +00006838 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006839 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6840 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006841 return true;
6842}
6843
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006844bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006845 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006846 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006847 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006848 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006849 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006850 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6851 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006852 Result.changeSign();
6853 return true;
6854 }
6855}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006856
Eli Friedman24c01542008-08-22 00:06:13 +00006857bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006858 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6859 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006860
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006861 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006862 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6863 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006864 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006865 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6866 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006867}
6868
6869bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6870 Result = E->getValue();
6871 return true;
6872}
6873
Peter Collingbournee9200682011-05-13 03:29:01 +00006874bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6875 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006876
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006877 switch (E->getCastKind()) {
6878 default:
Richard Smith11562c52011-10-28 17:51:58 +00006879 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006880
6881 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006882 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006883 return EvaluateInteger(SubExpr, IntResult, Info) &&
6884 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6885 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006886 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006887
6888 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006889 if (!Visit(SubExpr))
6890 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006891 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6892 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006893 }
John McCalld7646252010-11-14 08:17:51 +00006894
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006895 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006896 ComplexValue V;
6897 if (!EvaluateComplex(SubExpr, V, Info))
6898 return false;
6899 Result = V.getComplexFloatReal();
6900 return true;
6901 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006902 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006903}
6904
Eli Friedman24c01542008-08-22 00:06:13 +00006905//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006906// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006907//===----------------------------------------------------------------------===//
6908
6909namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006910class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006911 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006912 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006913
Anders Carlsson537969c2008-11-16 20:27:53 +00006914public:
John McCall93d91dc2010-05-07 17:22:02 +00006915 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006916 : ExprEvaluatorBaseTy(info), Result(Result) {}
6917
Richard Smith2e312c82012-03-03 22:46:17 +00006918 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006919 Result.setFrom(V);
6920 return true;
6921 }
Mike Stump11289f42009-09-09 15:08:12 +00006922
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006923 bool ZeroInitialization(const Expr *E);
6924
Anders Carlsson537969c2008-11-16 20:27:53 +00006925 //===--------------------------------------------------------------------===//
6926 // Visitor Methods
6927 //===--------------------------------------------------------------------===//
6928
Peter Collingbournee9200682011-05-13 03:29:01 +00006929 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006930 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006931 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006932 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006933 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006934};
6935} // end anonymous namespace
6936
John McCall93d91dc2010-05-07 17:22:02 +00006937static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6938 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006939 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006940 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006941}
6942
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006943bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006944 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006945 if (ElemTy->isRealFloatingType()) {
6946 Result.makeComplexFloat();
6947 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6948 Result.FloatReal = Zero;
6949 Result.FloatImag = Zero;
6950 } else {
6951 Result.makeComplexInt();
6952 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6953 Result.IntReal = Zero;
6954 Result.IntImag = Zero;
6955 }
6956 return true;
6957}
6958
Peter Collingbournee9200682011-05-13 03:29:01 +00006959bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6960 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006961
6962 if (SubExpr->getType()->isRealFloatingType()) {
6963 Result.makeComplexFloat();
6964 APFloat &Imag = Result.FloatImag;
6965 if (!EvaluateFloat(SubExpr, Imag, Info))
6966 return false;
6967
6968 Result.FloatReal = APFloat(Imag.getSemantics());
6969 return true;
6970 } else {
6971 assert(SubExpr->getType()->isIntegerType() &&
6972 "Unexpected imaginary literal.");
6973
6974 Result.makeComplexInt();
6975 APSInt &Imag = Result.IntImag;
6976 if (!EvaluateInteger(SubExpr, Imag, Info))
6977 return false;
6978
6979 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6980 return true;
6981 }
6982}
6983
Peter Collingbournee9200682011-05-13 03:29:01 +00006984bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006985
John McCallfcef3cf2010-12-14 17:51:41 +00006986 switch (E->getCastKind()) {
6987 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006988 case CK_BaseToDerived:
6989 case CK_DerivedToBase:
6990 case CK_UncheckedDerivedToBase:
6991 case CK_Dynamic:
6992 case CK_ToUnion:
6993 case CK_ArrayToPointerDecay:
6994 case CK_FunctionToPointerDecay:
6995 case CK_NullToPointer:
6996 case CK_NullToMemberPointer:
6997 case CK_BaseToDerivedMemberPointer:
6998 case CK_DerivedToBaseMemberPointer:
6999 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007000 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007001 case CK_ConstructorConversion:
7002 case CK_IntegralToPointer:
7003 case CK_PointerToIntegral:
7004 case CK_PointerToBoolean:
7005 case CK_ToVoid:
7006 case CK_VectorSplat:
7007 case CK_IntegralCast:
7008 case CK_IntegralToBoolean:
7009 case CK_IntegralToFloating:
7010 case CK_FloatingToIntegral:
7011 case CK_FloatingToBoolean:
7012 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007013 case CK_CPointerToObjCPointerCast:
7014 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007015 case CK_AnyPointerToBlockPointerCast:
7016 case CK_ObjCObjectLValueCast:
7017 case CK_FloatingComplexToReal:
7018 case CK_FloatingComplexToBoolean:
7019 case CK_IntegralComplexToReal:
7020 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007021 case CK_ARCProduceObject:
7022 case CK_ARCConsumeObject:
7023 case CK_ARCReclaimReturnedObject:
7024 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007025 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007026 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007027 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007028 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007029 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007030
John McCallfcef3cf2010-12-14 17:51:41 +00007031 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007032 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007033 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007034 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007035
7036 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007037 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007038 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007039 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007040
7041 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007042 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007043 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007044 return false;
7045
John McCallfcef3cf2010-12-14 17:51:41 +00007046 Result.makeComplexFloat();
7047 Result.FloatImag = APFloat(Real.getSemantics());
7048 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007049 }
7050
John McCallfcef3cf2010-12-14 17:51:41 +00007051 case CK_FloatingComplexCast: {
7052 if (!Visit(E->getSubExpr()))
7053 return false;
7054
7055 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7056 QualType From
7057 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7058
Richard Smith357362d2011-12-13 06:39:58 +00007059 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7060 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007061 }
7062
7063 case CK_FloatingComplexToIntegralComplex: {
7064 if (!Visit(E->getSubExpr()))
7065 return false;
7066
7067 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7068 QualType From
7069 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7070 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007071 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7072 To, Result.IntReal) &&
7073 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7074 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007075 }
7076
7077 case CK_IntegralRealToComplex: {
7078 APSInt &Real = Result.IntReal;
7079 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7080 return false;
7081
7082 Result.makeComplexInt();
7083 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7084 return true;
7085 }
7086
7087 case CK_IntegralComplexCast: {
7088 if (!Visit(E->getSubExpr()))
7089 return false;
7090
7091 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7092 QualType From
7093 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7094
Richard Smith911e1422012-01-30 22:27:01 +00007095 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7096 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007097 return true;
7098 }
7099
7100 case CK_IntegralComplexToFloatingComplex: {
7101 if (!Visit(E->getSubExpr()))
7102 return false;
7103
Ted Kremenek28831752012-08-23 20:46:57 +00007104 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007105 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007106 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007107 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007108 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7109 To, Result.FloatReal) &&
7110 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7111 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007112 }
7113 }
7114
7115 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007116}
7117
John McCall93d91dc2010-05-07 17:22:02 +00007118bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007119 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007120 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7121
Richard Smith253c2a32012-01-27 01:14:48 +00007122 bool LHSOK = Visit(E->getLHS());
7123 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007124 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007125
John McCall93d91dc2010-05-07 17:22:02 +00007126 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007127 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007128 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007129
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007130 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7131 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007132 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007133 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007134 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007135 if (Result.isComplexFloat()) {
7136 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7137 APFloat::rmNearestTiesToEven);
7138 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7139 APFloat::rmNearestTiesToEven);
7140 } else {
7141 Result.getComplexIntReal() += RHS.getComplexIntReal();
7142 Result.getComplexIntImag() += RHS.getComplexIntImag();
7143 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007144 break;
John McCalle3027922010-08-25 11:45:40 +00007145 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007146 if (Result.isComplexFloat()) {
7147 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7148 APFloat::rmNearestTiesToEven);
7149 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7150 APFloat::rmNearestTiesToEven);
7151 } else {
7152 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7153 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7154 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007155 break;
John McCalle3027922010-08-25 11:45:40 +00007156 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007157 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007158 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007159 APFloat &LHS_r = LHS.getComplexFloatReal();
7160 APFloat &LHS_i = LHS.getComplexFloatImag();
7161 APFloat &RHS_r = RHS.getComplexFloatReal();
7162 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007163
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007164 APFloat Tmp = LHS_r;
7165 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7166 Result.getComplexFloatReal() = Tmp;
7167 Tmp = LHS_i;
7168 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7169 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7170
7171 Tmp = LHS_r;
7172 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7173 Result.getComplexFloatImag() = Tmp;
7174 Tmp = LHS_i;
7175 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7176 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7177 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007178 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007179 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007180 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7181 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007182 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007183 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7184 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7185 }
7186 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007187 case BO_Div:
7188 if (Result.isComplexFloat()) {
7189 ComplexValue LHS = Result;
7190 APFloat &LHS_r = LHS.getComplexFloatReal();
7191 APFloat &LHS_i = LHS.getComplexFloatImag();
7192 APFloat &RHS_r = RHS.getComplexFloatReal();
7193 APFloat &RHS_i = RHS.getComplexFloatImag();
7194 APFloat &Res_r = Result.getComplexFloatReal();
7195 APFloat &Res_i = Result.getComplexFloatImag();
7196
7197 APFloat Den = RHS_r;
7198 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7199 APFloat Tmp = RHS_i;
7200 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7201 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7202
7203 Res_r = LHS_r;
7204 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7205 Tmp = LHS_i;
7206 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7207 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7208 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7209
7210 Res_i = LHS_i;
7211 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7212 Tmp = LHS_r;
7213 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7214 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7215 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7216 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007217 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7218 return Error(E, diag::note_expr_divide_by_zero);
7219
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007220 ComplexValue LHS = Result;
7221 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7222 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7223 Result.getComplexIntReal() =
7224 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7225 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7226 Result.getComplexIntImag() =
7227 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7228 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7229 }
7230 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007231 }
7232
John McCall93d91dc2010-05-07 17:22:02 +00007233 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007234}
7235
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007236bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7237 // Get the operand value into 'Result'.
7238 if (!Visit(E->getSubExpr()))
7239 return false;
7240
7241 switch (E->getOpcode()) {
7242 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007243 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007244 case UO_Extension:
7245 return true;
7246 case UO_Plus:
7247 // The result is always just the subexpr.
7248 return true;
7249 case UO_Minus:
7250 if (Result.isComplexFloat()) {
7251 Result.getComplexFloatReal().changeSign();
7252 Result.getComplexFloatImag().changeSign();
7253 }
7254 else {
7255 Result.getComplexIntReal() = -Result.getComplexIntReal();
7256 Result.getComplexIntImag() = -Result.getComplexIntImag();
7257 }
7258 return true;
7259 case UO_Not:
7260 if (Result.isComplexFloat())
7261 Result.getComplexFloatImag().changeSign();
7262 else
7263 Result.getComplexIntImag() = -Result.getComplexIntImag();
7264 return true;
7265 }
7266}
7267
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007268bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7269 if (E->getNumInits() == 2) {
7270 if (E->getType()->isComplexType()) {
7271 Result.makeComplexFloat();
7272 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7273 return false;
7274 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7275 return false;
7276 } else {
7277 Result.makeComplexInt();
7278 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7279 return false;
7280 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7281 return false;
7282 }
7283 return true;
7284 }
7285 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7286}
7287
Anders Carlsson537969c2008-11-16 20:27:53 +00007288//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007289// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7290// implicit conversion.
7291//===----------------------------------------------------------------------===//
7292
7293namespace {
7294class AtomicExprEvaluator :
7295 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7296 APValue &Result;
7297public:
7298 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7299 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7300
7301 bool Success(const APValue &V, const Expr *E) {
7302 Result = V;
7303 return true;
7304 }
7305
7306 bool ZeroInitialization(const Expr *E) {
7307 ImplicitValueInitExpr VIE(
7308 E->getType()->castAs<AtomicType>()->getValueType());
7309 return Evaluate(Result, Info, &VIE);
7310 }
7311
7312 bool VisitCastExpr(const CastExpr *E) {
7313 switch (E->getCastKind()) {
7314 default:
7315 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7316 case CK_NonAtomicToAtomic:
7317 return Evaluate(Result, Info, E->getSubExpr());
7318 }
7319 }
7320};
7321} // end anonymous namespace
7322
7323static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7324 assert(E->isRValue() && E->getType()->isAtomicType());
7325 return AtomicExprEvaluator(Info, Result).Visit(E);
7326}
7327
7328//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007329// Void expression evaluation, primarily for a cast to void on the LHS of a
7330// comma operator
7331//===----------------------------------------------------------------------===//
7332
7333namespace {
7334class VoidExprEvaluator
7335 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7336public:
7337 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7338
Richard Smith2e312c82012-03-03 22:46:17 +00007339 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007340
7341 bool VisitCastExpr(const CastExpr *E) {
7342 switch (E->getCastKind()) {
7343 default:
7344 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7345 case CK_ToVoid:
7346 VisitIgnoredValue(E->getSubExpr());
7347 return true;
7348 }
7349 }
7350};
7351} // end anonymous namespace
7352
7353static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7354 assert(E->isRValue() && E->getType()->isVoidType());
7355 return VoidExprEvaluator(Info).Visit(E);
7356}
7357
7358//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007359// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007360//===----------------------------------------------------------------------===//
7361
Richard Smith2e312c82012-03-03 22:46:17 +00007362static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007363 // In C, function designators are not lvalues, but we evaluate them as if they
7364 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007365 QualType T = E->getType();
7366 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007367 LValue LV;
7368 if (!EvaluateLValue(E, LV, Info))
7369 return false;
7370 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007371 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007372 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007373 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007374 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007375 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007376 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007377 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007378 LValue LV;
7379 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007380 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007381 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007382 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007383 llvm::APFloat F(0.0);
7384 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007385 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007386 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007387 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007388 ComplexValue C;
7389 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007390 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007391 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007392 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007393 MemberPtr P;
7394 if (!EvaluateMemberPointer(E, P, Info))
7395 return false;
7396 P.moveInto(Result);
7397 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007398 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007399 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007400 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007401 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007402 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007403 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007404 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007405 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007406 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007407 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7408 return false;
7409 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007410 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007411 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007412 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007413 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007414 if (!EvaluateVoid(E, Info))
7415 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007416 } else if (T->isAtomicType()) {
7417 if (!EvaluateAtomic(E, Result, Info))
7418 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007419 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007420 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007421 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007422 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007423 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007424 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007425 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007426
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007427 return true;
7428}
7429
Richard Smithb228a862012-02-15 02:18:13 +00007430/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7431/// cases, the in-place evaluation is essential, since later initializers for
7432/// an object can indirectly refer to subobjects which were initialized earlier.
7433static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007434 const Expr *E, bool AllowNonLiteralTypes) {
7435 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007436 return false;
7437
7438 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007439 // Evaluate arrays and record types in-place, so that later initializers can
7440 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007441 if (E->getType()->isArrayType())
7442 return EvaluateArray(E, This, Result, Info);
7443 else if (E->getType()->isRecordType())
7444 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007445 }
7446
7447 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007448 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007449}
7450
Richard Smithf57d8cb2011-12-09 22:58:01 +00007451/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7452/// lvalue-to-rvalue cast if it is an lvalue.
7453static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007454 if (!CheckLiteralType(Info, E))
7455 return false;
7456
Richard Smith2e312c82012-03-03 22:46:17 +00007457 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007458 return false;
7459
7460 if (E->isGLValue()) {
7461 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007462 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007463 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007464 return false;
7465 }
7466
Richard Smith2e312c82012-03-03 22:46:17 +00007467 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007468 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007469}
Richard Smith11562c52011-10-28 17:51:58 +00007470
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007471static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7472 const ASTContext &Ctx, bool &IsConst) {
7473 // Fast-path evaluations of integer literals, since we sometimes see files
7474 // containing vast quantities of these.
7475 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7476 Result.Val = APValue(APSInt(L->getValue(),
7477 L->getType()->isUnsignedIntegerType()));
7478 IsConst = true;
7479 return true;
7480 }
7481
7482 // FIXME: Evaluating values of large array and record types can cause
7483 // performance problems. Only do so in C++11 for now.
7484 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7485 Exp->getType()->isRecordType()) &&
7486 !Ctx.getLangOpts().CPlusPlus11) {
7487 IsConst = false;
7488 return true;
7489 }
7490 return false;
7491}
7492
7493
Richard Smith7b553f12011-10-29 00:50:52 +00007494/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007495/// any crazy technique (that has nothing to do with language standards) that
7496/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007497/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7498/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007499bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007500 bool IsConst;
7501 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7502 return IsConst;
7503
Richard Smithf57d8cb2011-12-09 22:58:01 +00007504 EvalInfo Info(Ctx, Result);
7505 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007506}
7507
Jay Foad39c79802011-01-12 09:06:06 +00007508bool Expr::EvaluateAsBooleanCondition(bool &Result,
7509 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007510 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007511 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007512 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007513}
7514
Richard Smith5fab0c92011-12-28 19:48:30 +00007515bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7516 SideEffectsKind AllowSideEffects) const {
7517 if (!getType()->isIntegralOrEnumerationType())
7518 return false;
7519
Richard Smith11562c52011-10-28 17:51:58 +00007520 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007521 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7522 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007523 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007524
Richard Smith11562c52011-10-28 17:51:58 +00007525 Result = ExprResult.Val.getInt();
7526 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007527}
7528
Jay Foad39c79802011-01-12 09:06:06 +00007529bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007530 EvalInfo Info(Ctx, Result);
7531
John McCall45d55e42010-05-07 21:00:08 +00007532 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007533 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7534 !CheckLValueConstantExpression(Info, getExprLoc(),
7535 Ctx.getLValueReferenceType(getType()), LV))
7536 return false;
7537
Richard Smith2e312c82012-03-03 22:46:17 +00007538 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007539 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007540}
7541
Richard Smithd0b4dd62011-12-19 06:19:21 +00007542bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7543 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007544 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007545 // FIXME: Evaluating initializers for large array and record types can cause
7546 // performance problems. Only do so in C++11 for now.
7547 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007548 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007549 return false;
7550
Richard Smithd0b4dd62011-12-19 06:19:21 +00007551 Expr::EvalStatus EStatus;
7552 EStatus.Diag = &Notes;
7553
7554 EvalInfo InitInfo(Ctx, EStatus);
7555 InitInfo.setEvaluatingDecl(VD, Value);
7556
7557 LValue LVal;
7558 LVal.set(VD);
7559
Richard Smithfddd3842011-12-30 21:15:51 +00007560 // C++11 [basic.start.init]p2:
7561 // Variables with static storage duration or thread storage duration shall be
7562 // zero-initialized before any other initialization takes place.
7563 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007564 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007565 !VD->getType()->isReferenceType()) {
7566 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007567 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007568 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007569 return false;
7570 }
7571
Richard Smith7525ff62013-05-09 07:14:00 +00007572 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7573 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007574 EStatus.HasSideEffects)
7575 return false;
7576
7577 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7578 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007579}
7580
Richard Smith7b553f12011-10-29 00:50:52 +00007581/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7582/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007583bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007584 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007585 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007586}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007587
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007588APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007589 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007590 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007591 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007592 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007593 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007594 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007595 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007596
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007597 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007598}
John McCall864e3962010-05-07 05:32:02 +00007599
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007600void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7601 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7602 bool IsConst;
7603 EvalResult EvalResult;
7604 EvalResult.Diag = Diags;
7605 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7606 EvalInfo Info(Ctx, EvalResult, true);
7607 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7608 }
7609}
7610
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007611 bool Expr::EvalResult::isGlobalLValue() const {
7612 assert(Val.isLValue());
7613 return IsGlobalLValue(Val.getLValueBase());
7614 }
7615
7616
John McCall864e3962010-05-07 05:32:02 +00007617/// isIntegerConstantExpr - this recursive routine will test if an expression is
7618/// an integer constant expression.
7619
7620/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7621/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007622
7623// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007624// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7625// and a (possibly null) SourceLocation indicating the location of the problem.
7626//
John McCall864e3962010-05-07 05:32:02 +00007627// Note that to reduce code duplication, this helper does no evaluation
7628// itself; the caller checks whether the expression is evaluatable, and
7629// in the rare cases where CheckICE actually cares about the evaluated
7630// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007631
Dan Gohman28ade552010-07-26 21:25:24 +00007632namespace {
7633
Richard Smith9e575da2012-12-28 13:25:52 +00007634enum ICEKind {
7635 /// This expression is an ICE.
7636 IK_ICE,
7637 /// This expression is not an ICE, but if it isn't evaluated, it's
7638 /// a legal subexpression for an ICE. This return value is used to handle
7639 /// the comma operator in C99 mode, and non-constant subexpressions.
7640 IK_ICEIfUnevaluated,
7641 /// This expression is not an ICE, and is not a legal subexpression for one.
7642 IK_NotICE
7643};
7644
John McCall864e3962010-05-07 05:32:02 +00007645struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007646 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007647 SourceLocation Loc;
7648
Richard Smith9e575da2012-12-28 13:25:52 +00007649 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007650};
7651
Dan Gohman28ade552010-07-26 21:25:24 +00007652}
7653
Richard Smith9e575da2012-12-28 13:25:52 +00007654static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7655
7656static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007657
7658static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7659 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007660 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007661 !EVResult.Val.isInt())
7662 return ICEDiag(IK_NotICE, E->getLocStart());
7663
John McCall864e3962010-05-07 05:32:02 +00007664 return NoDiag();
7665}
7666
7667static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7668 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007669 if (!E->getType()->isIntegralOrEnumerationType())
7670 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007671
7672 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007673#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007674#define STMT(Node, Base) case Expr::Node##Class:
7675#define EXPR(Node, Base)
7676#include "clang/AST/StmtNodes.inc"
7677 case Expr::PredefinedExprClass:
7678 case Expr::FloatingLiteralClass:
7679 case Expr::ImaginaryLiteralClass:
7680 case Expr::StringLiteralClass:
7681 case Expr::ArraySubscriptExprClass:
7682 case Expr::MemberExprClass:
7683 case Expr::CompoundAssignOperatorClass:
7684 case Expr::CompoundLiteralExprClass:
7685 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007686 case Expr::DesignatedInitExprClass:
7687 case Expr::ImplicitValueInitExprClass:
7688 case Expr::ParenListExprClass:
7689 case Expr::VAArgExprClass:
7690 case Expr::AddrLabelExprClass:
7691 case Expr::StmtExprClass:
7692 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007693 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007694 case Expr::CXXDynamicCastExprClass:
7695 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007696 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007697 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007698 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007699 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007700 case Expr::CXXThisExprClass:
7701 case Expr::CXXThrowExprClass:
7702 case Expr::CXXNewExprClass:
7703 case Expr::CXXDeleteExprClass:
7704 case Expr::CXXPseudoDestructorExprClass:
7705 case Expr::UnresolvedLookupExprClass:
7706 case Expr::DependentScopeDeclRefExprClass:
7707 case Expr::CXXConstructExprClass:
7708 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007709 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007710 case Expr::CXXTemporaryObjectExprClass:
7711 case Expr::CXXUnresolvedConstructExprClass:
7712 case Expr::CXXDependentScopeMemberExprClass:
7713 case Expr::UnresolvedMemberExprClass:
7714 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007715 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007716 case Expr::ObjCArrayLiteralClass:
7717 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007718 case Expr::ObjCEncodeExprClass:
7719 case Expr::ObjCMessageExprClass:
7720 case Expr::ObjCSelectorExprClass:
7721 case Expr::ObjCProtocolExprClass:
7722 case Expr::ObjCIvarRefExprClass:
7723 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007724 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007725 case Expr::ObjCIsaExprClass:
7726 case Expr::ShuffleVectorExprClass:
7727 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007728 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007729 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007730 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007731 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007732 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007733 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007734 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007735 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007736 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007737 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007738 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007739 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007740 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007741
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007742 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007743 case Expr::GNUNullExprClass:
7744 // GCC considers the GNU __null value to be an integral constant expression.
7745 return NoDiag();
7746
John McCall7c454bb2011-07-15 05:09:51 +00007747 case Expr::SubstNonTypeTemplateParmExprClass:
7748 return
7749 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7750
John McCall864e3962010-05-07 05:32:02 +00007751 case Expr::ParenExprClass:
7752 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007753 case Expr::GenericSelectionExprClass:
7754 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007755 case Expr::IntegerLiteralClass:
7756 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007757 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007758 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007759 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007760 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007761 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007762 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007763 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007764 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007765 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007766 return NoDiag();
7767 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007768 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007769 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7770 // constant expressions, but they can never be ICEs because an ICE cannot
7771 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007772 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007773 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007774 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007775 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007776 }
Richard Smith6365c912012-02-24 22:12:32 +00007777 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007778 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7779 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007780 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007781 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007782 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007783 // Parameter variables are never constants. Without this check,
7784 // getAnyInitializer() can find a default argument, which leads
7785 // to chaos.
7786 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007787 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007788
7789 // C++ 7.1.5.1p2
7790 // A variable of non-volatile const-qualified integral or enumeration
7791 // type initialized by an ICE can be used in ICEs.
7792 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007793 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007794 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007795
Richard Smithd0b4dd62011-12-19 06:19:21 +00007796 const VarDecl *VD;
7797 // Look for a declaration of this variable that has an initializer, and
7798 // check whether it is an ICE.
7799 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7800 return NoDiag();
7801 else
Richard Smith9e575da2012-12-28 13:25:52 +00007802 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007803 }
7804 }
Richard Smith9e575da2012-12-28 13:25:52 +00007805 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007806 }
John McCall864e3962010-05-07 05:32:02 +00007807 case Expr::UnaryOperatorClass: {
7808 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7809 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007810 case UO_PostInc:
7811 case UO_PostDec:
7812 case UO_PreInc:
7813 case UO_PreDec:
7814 case UO_AddrOf:
7815 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007816 // C99 6.6/3 allows increment and decrement within unevaluated
7817 // subexpressions of constant expressions, but they can never be ICEs
7818 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007819 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007820 case UO_Extension:
7821 case UO_LNot:
7822 case UO_Plus:
7823 case UO_Minus:
7824 case UO_Not:
7825 case UO_Real:
7826 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007827 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007828 }
Richard Smith9e575da2012-12-28 13:25:52 +00007829
John McCall864e3962010-05-07 05:32:02 +00007830 // OffsetOf falls through here.
7831 }
7832 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007833 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7834 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7835 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7836 // compliance: we should warn earlier for offsetof expressions with
7837 // array subscripts that aren't ICEs, and if the array subscripts
7838 // are ICEs, the value of the offsetof must be an integer constant.
7839 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007840 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007841 case Expr::UnaryExprOrTypeTraitExprClass: {
7842 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7843 if ((Exp->getKind() == UETT_SizeOf) &&
7844 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007845 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007846 return NoDiag();
7847 }
7848 case Expr::BinaryOperatorClass: {
7849 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7850 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007851 case BO_PtrMemD:
7852 case BO_PtrMemI:
7853 case BO_Assign:
7854 case BO_MulAssign:
7855 case BO_DivAssign:
7856 case BO_RemAssign:
7857 case BO_AddAssign:
7858 case BO_SubAssign:
7859 case BO_ShlAssign:
7860 case BO_ShrAssign:
7861 case BO_AndAssign:
7862 case BO_XorAssign:
7863 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007864 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7865 // constant expressions, but they can never be ICEs because an ICE cannot
7866 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007867 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007868
John McCalle3027922010-08-25 11:45:40 +00007869 case BO_Mul:
7870 case BO_Div:
7871 case BO_Rem:
7872 case BO_Add:
7873 case BO_Sub:
7874 case BO_Shl:
7875 case BO_Shr:
7876 case BO_LT:
7877 case BO_GT:
7878 case BO_LE:
7879 case BO_GE:
7880 case BO_EQ:
7881 case BO_NE:
7882 case BO_And:
7883 case BO_Xor:
7884 case BO_Or:
7885 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007886 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7887 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007888 if (Exp->getOpcode() == BO_Div ||
7889 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007890 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007891 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007892 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007893 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007894 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007895 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007896 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007897 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007898 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007899 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007900 }
7901 }
7902 }
John McCalle3027922010-08-25 11:45:40 +00007903 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007904 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007905 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7906 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007907 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7908 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007909 } else {
7910 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007911 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007912 }
7913 }
Richard Smith9e575da2012-12-28 13:25:52 +00007914 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007915 }
John McCalle3027922010-08-25 11:45:40 +00007916 case BO_LAnd:
7917 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007918 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7919 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007920 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007921 // Rare case where the RHS has a comma "side-effect"; we need
7922 // to actually check the condition to see whether the side
7923 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007924 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007925 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007926 return RHSResult;
7927 return NoDiag();
7928 }
7929
Richard Smith9e575da2012-12-28 13:25:52 +00007930 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007931 }
7932 }
7933 }
7934 case Expr::ImplicitCastExprClass:
7935 case Expr::CStyleCastExprClass:
7936 case Expr::CXXFunctionalCastExprClass:
7937 case Expr::CXXStaticCastExprClass:
7938 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007939 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007940 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007941 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007942 if (isa<ExplicitCastExpr>(E)) {
7943 if (const FloatingLiteral *FL
7944 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7945 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7946 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7947 APSInt IgnoredVal(DestWidth, !DestSigned);
7948 bool Ignored;
7949 // If the value does not fit in the destination type, the behavior is
7950 // undefined, so we are not required to treat it as a constant
7951 // expression.
7952 if (FL->getValue().convertToInteger(IgnoredVal,
7953 llvm::APFloat::rmTowardZero,
7954 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007955 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007956 return NoDiag();
7957 }
7958 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007959 switch (cast<CastExpr>(E)->getCastKind()) {
7960 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007961 case CK_AtomicToNonAtomic:
7962 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007963 case CK_NoOp:
7964 case CK_IntegralToBoolean:
7965 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007966 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007967 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007968 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007969 }
John McCall864e3962010-05-07 05:32:02 +00007970 }
John McCallc07a0c72011-02-17 10:25:35 +00007971 case Expr::BinaryConditionalOperatorClass: {
7972 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7973 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007974 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007975 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007976 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7977 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7978 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007979 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007980 return FalseResult;
7981 }
John McCall864e3962010-05-07 05:32:02 +00007982 case Expr::ConditionalOperatorClass: {
7983 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7984 // If the condition (ignoring parens) is a __builtin_constant_p call,
7985 // then only the true side is actually considered in an integer constant
7986 // expression, and it is fully evaluated. This is an important GNU
7987 // extension. See GCC PR38377 for discussion.
7988 if (const CallExpr *CallCE
7989 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007990 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7991 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007992 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007993 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007994 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007995
Richard Smithf57d8cb2011-12-09 22:58:01 +00007996 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7997 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007998
Richard Smith9e575da2012-12-28 13:25:52 +00007999 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008000 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008001 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008002 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008003 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008004 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008005 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008006 return NoDiag();
8007 // Rare case where the diagnostics depend on which side is evaluated
8008 // Note that if we get here, CondResult is 0, and at least one of
8009 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008010 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008011 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008012 return TrueResult;
8013 }
8014 case Expr::CXXDefaultArgExprClass:
8015 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008016 case Expr::CXXDefaultInitExprClass:
8017 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008018 case Expr::ChooseExprClass: {
8019 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
8020 }
8021 }
8022
David Blaikiee4d798f2012-01-20 21:50:17 +00008023 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008024}
8025
Richard Smithf57d8cb2011-12-09 22:58:01 +00008026/// Evaluate an expression as a C++11 integral constant expression.
8027static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8028 const Expr *E,
8029 llvm::APSInt *Value,
8030 SourceLocation *Loc) {
8031 if (!E->getType()->isIntegralOrEnumerationType()) {
8032 if (Loc) *Loc = E->getExprLoc();
8033 return false;
8034 }
8035
Richard Smith66e05fe2012-01-18 05:21:49 +00008036 APValue Result;
8037 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008038 return false;
8039
Richard Smith66e05fe2012-01-18 05:21:49 +00008040 assert(Result.isInt() && "pointer cast to int is not an ICE");
8041 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008042 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008043}
8044
Richard Smith92b1ce02011-12-12 09:28:41 +00008045bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008046 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008047 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8048
Richard Smith9e575da2012-12-28 13:25:52 +00008049 ICEDiag D = CheckICE(this, Ctx);
8050 if (D.Kind != IK_ICE) {
8051 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008052 return false;
8053 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008054 return true;
8055}
8056
8057bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8058 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008059 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008060 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8061
8062 if (!isIntegerConstantExpr(Ctx, Loc))
8063 return false;
8064 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008065 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008066 return true;
8067}
Richard Smith66e05fe2012-01-18 05:21:49 +00008068
Richard Smith98a0a492012-02-14 21:38:30 +00008069bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008070 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008071}
8072
Richard Smith66e05fe2012-01-18 05:21:49 +00008073bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8074 SourceLocation *Loc) const {
8075 // We support this checking in C++98 mode in order to diagnose compatibility
8076 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008077 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008078
Richard Smith98a0a492012-02-14 21:38:30 +00008079 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008080 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008081 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008082 Status.Diag = &Diags;
8083 EvalInfo Info(Ctx, Status);
8084
8085 APValue Scratch;
8086 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8087
8088 if (!Diags.empty()) {
8089 IsConstExpr = false;
8090 if (Loc) *Loc = Diags[0].first;
8091 } else if (!IsConstExpr) {
8092 // FIXME: This shouldn't happen.
8093 if (Loc) *Loc = getExprLoc();
8094 }
8095
8096 return IsConstExpr;
8097}
Richard Smith253c2a32012-01-27 01:14:48 +00008098
8099bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008100 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008101 PartialDiagnosticAt> &Diags) {
8102 // FIXME: It would be useful to check constexpr function templates, but at the
8103 // moment the constant expression evaluator cannot cope with the non-rigorous
8104 // ASTs which we build for dependent expressions.
8105 if (FD->isDependentContext())
8106 return true;
8107
8108 Expr::EvalStatus Status;
8109 Status.Diag = &Diags;
8110
8111 EvalInfo Info(FD->getASTContext(), Status);
8112 Info.CheckingPotentialConstantExpression = true;
8113
8114 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8115 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8116
Richard Smith7525ff62013-05-09 07:14:00 +00008117 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008118 // is a temporary being used as the 'this' pointer.
8119 LValue This;
8120 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008121 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008122
Richard Smith253c2a32012-01-27 01:14:48 +00008123 ArrayRef<const Expr*> Args;
8124
8125 SourceLocation Loc = FD->getLocation();
8126
Richard Smith2e312c82012-03-03 22:46:17 +00008127 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008128 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8129 // Evaluate the call as a constant initializer, to allow the construction
8130 // of objects of non-literal types.
8131 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008132 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008133 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008134 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8135 Args, FD->getBody(), Info, Scratch);
8136
8137 return Diags.empty();
8138}