blob: 72f1c21ee6544d6167f2c6084608c419211ff462 [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 Smithe6c01442013-06-05 00:46:14 +00001004 case Expr::MaterializeTemporaryExprClass:
1005 // A materialized temporary might have been lifetime-extended to static
1006 // storage duration.
1007 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001008 // A string literal has static storage duration.
1009 case Expr::StringLiteralClass:
1010 case Expr::PredefinedExprClass:
1011 case Expr::ObjCStringLiteralClass:
1012 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001013 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001014 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001015 return true;
1016 case Expr::CallExprClass:
1017 return IsStringLiteralCall(cast<CallExpr>(E));
1018 // For GCC compatibility, &&label has static storage duration.
1019 case Expr::AddrLabelExprClass:
1020 return true;
1021 // A Block literal expression may be used as the initialization value for
1022 // Block variables at global or local static scope.
1023 case Expr::BlockExprClass:
1024 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001025 case Expr::ImplicitValueInitExprClass:
1026 // FIXME:
1027 // We can never form an lvalue with an implicit value initialization as its
1028 // base through expression evaluation, so these only appear in one case: the
1029 // implicit variable declaration we invent when checking whether a constexpr
1030 // constructor can produce a constant expression. We must assume that such
1031 // an expression might be a global lvalue.
1032 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001033 }
John McCall95007602010-05-10 23:27:23 +00001034}
1035
Richard Smithb228a862012-02-15 02:18:13 +00001036static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1037 assert(Base && "no location for a null lvalue");
1038 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1039 if (VD)
1040 Info.Note(VD->getLocation(), diag::note_declared_at);
1041 else
Ted Kremenek28831752012-08-23 20:46:57 +00001042 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001043 diag::note_constexpr_temporary_here);
1044}
1045
Richard Smith80815602011-11-07 05:07:52 +00001046/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001047/// value for an address or reference constant expression. Return true if we
1048/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001049static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1050 QualType Type, const LValue &LVal) {
1051 bool IsReferenceType = Type->isReferenceType();
1052
Richard Smith357362d2011-12-13 06:39:58 +00001053 APValue::LValueBase Base = LVal.getLValueBase();
1054 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1055
Richard Smith0dea49e2012-02-18 04:58:18 +00001056 // Check that the object is a global. Note that the fake 'this' object we
1057 // manufacture when checking potential constant expressions is conservatively
1058 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001059 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001060 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001061 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001062 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1063 << IsReferenceType << !Designator.Entries.empty()
1064 << !!VD << VD;
1065 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001066 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001067 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001068 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001069 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001070 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001071 }
Richard Smithb228a862012-02-15 02:18:13 +00001072 assert((Info.CheckingPotentialConstantExpression ||
1073 LVal.getLValueCallIndex() == 0) &&
1074 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001075
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001076 // Check if this is a thread-local variable.
1077 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1078 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001079 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001080 return false;
1081 }
1082 }
1083
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 // Allow address constant expressions to be past-the-end pointers. This is
1085 // an extension: the standard requires them to point to an object.
1086 if (!IsReferenceType)
1087 return true;
1088
1089 // A reference constant expression must refer to an object.
1090 if (!Base) {
1091 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001092 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001093 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001094 }
1095
Richard Smith357362d2011-12-13 06:39:58 +00001096 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001097 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001098 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001099 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001100 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001101 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001102 }
1103
Richard Smith80815602011-11-07 05:07:52 +00001104 return true;
1105}
1106
Richard Smithfddd3842011-12-30 21:15:51 +00001107/// Check that this core constant expression is of literal type, and if not,
1108/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001109static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1110 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001112 return true;
1113
Richard Smith7525ff62013-05-09 07:14:00 +00001114 // C++1y: A constant initializer for an object o [...] may also invoke
1115 // constexpr constructors for o and its subobjects even if those objects
1116 // are of non-literal class types.
1117 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001118 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001119 return true;
1120
Richard Smithfddd3842011-12-30 21:15:51 +00001121 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001122 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001123 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001124 << E->getType();
1125 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001126 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001127 return false;
1128}
1129
Richard Smith0b0a0b62011-10-29 20:57:55 +00001130/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001131/// constant expression. If not, report an appropriate diagnostic. Does not
1132/// check that the expression is of literal type.
1133static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1134 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001135 if (Value.isUninit()) {
1136 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized) << Type;
1137 return false;
1138 }
1139
Richard Smithb228a862012-02-15 02:18:13 +00001140 // Core issue 1454: For a literal constant expression of array or class type,
1141 // each subobject of its value shall have been initialized by a constant
1142 // expression.
1143 if (Value.isArray()) {
1144 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1145 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1146 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1147 Value.getArrayInitializedElt(I)))
1148 return false;
1149 }
1150 if (!Value.hasArrayFiller())
1151 return true;
1152 return CheckConstantExpression(Info, DiagLoc, EltTy,
1153 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001154 }
Richard Smithb228a862012-02-15 02:18:13 +00001155 if (Value.isUnion() && Value.getUnionField()) {
1156 return CheckConstantExpression(Info, DiagLoc,
1157 Value.getUnionField()->getType(),
1158 Value.getUnionValue());
1159 }
1160 if (Value.isStruct()) {
1161 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1162 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1163 unsigned BaseIndex = 0;
1164 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1165 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1166 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1167 Value.getStructBase(BaseIndex)))
1168 return false;
1169 }
1170 }
1171 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1172 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001173 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1174 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001175 return false;
1176 }
1177 }
1178
1179 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001180 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001181 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001182 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1183 }
1184
1185 // Everything else is fine.
1186 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001187}
1188
Richard Smith83c68212011-10-31 05:11:32 +00001189const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001190 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001191}
1192
1193static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001194 if (Value.CallIndex)
1195 return false;
1196 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1197 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001198}
1199
Richard Smithcecf1842011-11-01 21:06:14 +00001200static bool IsWeakLValue(const LValue &Value) {
1201 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001202 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001203}
1204
Richard Smith2e312c82012-03-03 22:46:17 +00001205static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001206 // A null base expression indicates a null pointer. These are always
1207 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001208 if (!Value.getLValueBase()) {
1209 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001210 return true;
1211 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001212
Richard Smith027bf112011-11-17 22:56:20 +00001213 // We have a non-null base. These are generally known to be true, but if it's
1214 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001215 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001216 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001217 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001218}
1219
Richard Smith2e312c82012-03-03 22:46:17 +00001220static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001221 switch (Val.getKind()) {
1222 case APValue::Uninitialized:
1223 return false;
1224 case APValue::Int:
1225 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001226 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001227 case APValue::Float:
1228 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001229 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001230 case APValue::ComplexInt:
1231 Result = Val.getComplexIntReal().getBoolValue() ||
1232 Val.getComplexIntImag().getBoolValue();
1233 return true;
1234 case APValue::ComplexFloat:
1235 Result = !Val.getComplexFloatReal().isZero() ||
1236 !Val.getComplexFloatImag().isZero();
1237 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001238 case APValue::LValue:
1239 return EvalPointerValueAsBool(Val, Result);
1240 case APValue::MemberPointer:
1241 Result = Val.getMemberPointerDecl();
1242 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001243 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001244 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001245 case APValue::Struct:
1246 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001247 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001248 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001249 }
1250
Richard Smith11562c52011-10-28 17:51:58 +00001251 llvm_unreachable("unknown APValue kind");
1252}
1253
1254static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1255 EvalInfo &Info) {
1256 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001257 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001258 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001259 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001260 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001261}
1262
Richard Smith357362d2011-12-13 06:39:58 +00001263template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001264static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001265 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001266 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001267 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001268}
1269
1270static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1271 QualType SrcType, const APFloat &Value,
1272 QualType DestType, APSInt &Result) {
1273 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001274 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001275 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001276
Richard Smith357362d2011-12-13 06:39:58 +00001277 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001278 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001279 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1280 & APFloat::opInvalidOp)
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 Smith357362d2011-12-13 06:39:58 +00001285static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1286 QualType SrcType, QualType DestType,
1287 APFloat &Result) {
1288 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001289 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001290 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1291 APFloat::rmNearestTiesToEven, &ignored)
1292 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001293 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001294 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001295}
1296
Richard Smith911e1422012-01-30 22:27:01 +00001297static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1298 QualType DestType, QualType SrcType,
1299 APSInt &Value) {
1300 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001301 APSInt Result = Value;
1302 // Figure out if this is a truncate, extend or noop cast.
1303 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001304 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001305 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001306 return Result;
1307}
1308
Richard Smith357362d2011-12-13 06:39:58 +00001309static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1310 QualType SrcType, const APSInt &Value,
1311 QualType DestType, APFloat &Result) {
1312 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1313 if (Result.convertFromAPInt(Value, Value.isSigned(),
1314 APFloat::rmNearestTiesToEven)
1315 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001316 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001317 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001318}
1319
Eli Friedman803acb32011-12-22 03:51:45 +00001320static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1321 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001322 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001323 if (!Evaluate(SVal, Info, E))
1324 return false;
1325 if (SVal.isInt()) {
1326 Res = SVal.getInt();
1327 return true;
1328 }
1329 if (SVal.isFloat()) {
1330 Res = SVal.getFloat().bitcastToAPInt();
1331 return true;
1332 }
1333 if (SVal.isVector()) {
1334 QualType VecTy = E->getType();
1335 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1336 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1337 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1338 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1339 Res = llvm::APInt::getNullValue(VecSize);
1340 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1341 APValue &Elt = SVal.getVectorElt(i);
1342 llvm::APInt EltAsInt;
1343 if (Elt.isInt()) {
1344 EltAsInt = Elt.getInt();
1345 } else if (Elt.isFloat()) {
1346 EltAsInt = Elt.getFloat().bitcastToAPInt();
1347 } else {
1348 // Don't try to handle vectors of anything other than int or float
1349 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001350 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001351 return false;
1352 }
1353 unsigned BaseEltSize = EltAsInt.getBitWidth();
1354 if (BigEndian)
1355 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1356 else
1357 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1358 }
1359 return true;
1360 }
1361 // Give up if the input isn't an int, float, or vector. For example, we
1362 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001363 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001364 return false;
1365}
1366
Richard Smith43e77732013-05-07 04:50:00 +00001367/// Perform the given integer operation, which is known to need at most BitWidth
1368/// bits, and check for overflow in the original type (if that type was not an
1369/// unsigned type).
1370template<typename Operation>
1371static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1372 const APSInt &LHS, const APSInt &RHS,
1373 unsigned BitWidth, Operation Op) {
1374 if (LHS.isUnsigned())
1375 return Op(LHS, RHS);
1376
1377 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1378 APSInt Result = Value.trunc(LHS.getBitWidth());
1379 if (Result.extend(BitWidth) != Value) {
1380 if (Info.getIntOverflowCheckMode())
1381 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1382 diag::warn_integer_constant_overflow)
1383 << Result.toString(10) << E->getType();
1384 else
1385 HandleOverflow(Info, E, Value, E->getType());
1386 }
1387 return Result;
1388}
1389
1390/// Perform the given binary integer operation.
1391static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1392 BinaryOperatorKind Opcode, APSInt RHS,
1393 APSInt &Result) {
1394 switch (Opcode) {
1395 default:
1396 Info.Diag(E);
1397 return false;
1398 case BO_Mul:
1399 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1400 std::multiplies<APSInt>());
1401 return true;
1402 case BO_Add:
1403 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1404 std::plus<APSInt>());
1405 return true;
1406 case BO_Sub:
1407 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1408 std::minus<APSInt>());
1409 return true;
1410 case BO_And: Result = LHS & RHS; return true;
1411 case BO_Xor: Result = LHS ^ RHS; return true;
1412 case BO_Or: Result = LHS | RHS; return true;
1413 case BO_Div:
1414 case BO_Rem:
1415 if (RHS == 0) {
1416 Info.Diag(E, diag::note_expr_divide_by_zero);
1417 return false;
1418 }
1419 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1420 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1421 LHS.isSigned() && LHS.isMinSignedValue())
1422 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1423 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1424 return true;
1425 case BO_Shl: {
1426 if (Info.getLangOpts().OpenCL)
1427 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1428 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1429 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1430 RHS.isUnsigned());
1431 else if (RHS.isSigned() && RHS.isNegative()) {
1432 // During constant-folding, a negative shift is an opposite shift. Such
1433 // a shift is not a constant expression.
1434 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1435 RHS = -RHS;
1436 goto shift_right;
1437 }
1438 shift_left:
1439 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1440 // the shifted type.
1441 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1442 if (SA != RHS) {
1443 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1444 << RHS << E->getType() << LHS.getBitWidth();
1445 } else if (LHS.isSigned()) {
1446 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1447 // operand, and must not overflow the corresponding unsigned type.
1448 if (LHS.isNegative())
1449 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1450 else if (LHS.countLeadingZeros() < SA)
1451 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1452 }
1453 Result = LHS << SA;
1454 return true;
1455 }
1456 case BO_Shr: {
1457 if (Info.getLangOpts().OpenCL)
1458 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1459 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1460 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1461 RHS.isUnsigned());
1462 else if (RHS.isSigned() && RHS.isNegative()) {
1463 // During constant-folding, a negative shift is an opposite shift. Such a
1464 // shift is not a constant expression.
1465 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1466 RHS = -RHS;
1467 goto shift_left;
1468 }
1469 shift_right:
1470 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1471 // shifted type.
1472 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1473 if (SA != RHS)
1474 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1475 << RHS << E->getType() << LHS.getBitWidth();
1476 Result = LHS >> SA;
1477 return true;
1478 }
1479
1480 case BO_LT: Result = LHS < RHS; return true;
1481 case BO_GT: Result = LHS > RHS; return true;
1482 case BO_LE: Result = LHS <= RHS; return true;
1483 case BO_GE: Result = LHS >= RHS; return true;
1484 case BO_EQ: Result = LHS == RHS; return true;
1485 case BO_NE: Result = LHS != RHS; return true;
1486 }
1487}
1488
Richard Smith861b5b52013-05-07 23:34:45 +00001489/// Perform the given binary floating-point operation, in-place, on LHS.
1490static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1491 APFloat &LHS, BinaryOperatorKind Opcode,
1492 const APFloat &RHS) {
1493 switch (Opcode) {
1494 default:
1495 Info.Diag(E);
1496 return false;
1497 case BO_Mul:
1498 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1499 break;
1500 case BO_Add:
1501 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1502 break;
1503 case BO_Sub:
1504 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1505 break;
1506 case BO_Div:
1507 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1508 break;
1509 }
1510
1511 if (LHS.isInfinity() || LHS.isNaN())
1512 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1513 return true;
1514}
1515
Richard Smitha8105bc2012-01-06 16:39:00 +00001516/// Cast an lvalue referring to a base subobject to a derived class, by
1517/// truncating the lvalue's path to the given length.
1518static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1519 const RecordDecl *TruncatedType,
1520 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001521 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001522
1523 // Check we actually point to a derived class object.
1524 if (TruncatedElements == D.Entries.size())
1525 return true;
1526 assert(TruncatedElements >= D.MostDerivedPathLength &&
1527 "not casting to a derived class");
1528 if (!Result.checkSubobject(Info, E, CSK_Derived))
1529 return false;
1530
1531 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001532 const RecordDecl *RD = TruncatedType;
1533 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001534 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001535 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1536 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001537 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001538 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001539 else
Richard Smithd62306a2011-11-10 06:34:14 +00001540 Result.Offset -= Layout.getBaseClassOffset(Base);
1541 RD = Base;
1542 }
Richard Smith027bf112011-11-17 22:56:20 +00001543 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001544 return true;
1545}
1546
John McCalld7bca762012-05-01 00:38:49 +00001547static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001548 const CXXRecordDecl *Derived,
1549 const CXXRecordDecl *Base,
1550 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001551 if (!RL) {
1552 if (Derived->isInvalidDecl()) return false;
1553 RL = &Info.Ctx.getASTRecordLayout(Derived);
1554 }
1555
Richard Smithd62306a2011-11-10 06:34:14 +00001556 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001557 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001558 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001559}
1560
Richard Smitha8105bc2012-01-06 16:39:00 +00001561static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001562 const CXXRecordDecl *DerivedDecl,
1563 const CXXBaseSpecifier *Base) {
1564 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1565
John McCalld7bca762012-05-01 00:38:49 +00001566 if (!Base->isVirtual())
1567 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001568
Richard Smitha8105bc2012-01-06 16:39:00 +00001569 SubobjectDesignator &D = Obj.Designator;
1570 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001571 return false;
1572
Richard Smitha8105bc2012-01-06 16:39:00 +00001573 // Extract most-derived object and corresponding type.
1574 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1575 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1576 return false;
1577
1578 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001579 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001580 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1581 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001582 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001583 return true;
1584}
1585
Richard Smith84401042013-06-03 05:03:02 +00001586static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1587 QualType Type, LValue &Result) {
1588 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1589 PathE = E->path_end();
1590 PathI != PathE; ++PathI) {
1591 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1592 *PathI))
1593 return false;
1594 Type = (*PathI)->getType();
1595 }
1596 return true;
1597}
1598
Richard Smithd62306a2011-11-10 06:34:14 +00001599/// Update LVal to refer to the given field, which must be a member of the type
1600/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001601static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001602 const FieldDecl *FD,
1603 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001604 if (!RL) {
1605 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001606 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001607 }
Richard Smithd62306a2011-11-10 06:34:14 +00001608
1609 unsigned I = FD->getFieldIndex();
1610 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001611 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001612 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001613}
1614
Richard Smith1b78b3d2012-01-25 22:15:11 +00001615/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001616static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001617 LValue &LVal,
1618 const IndirectFieldDecl *IFD) {
1619 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1620 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001621 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1622 return false;
1623 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001624}
1625
Richard Smithd62306a2011-11-10 06:34:14 +00001626/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001627static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1628 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001629 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1630 // extension.
1631 if (Type->isVoidType() || Type->isFunctionType()) {
1632 Size = CharUnits::One();
1633 return true;
1634 }
1635
1636 if (!Type->isConstantSizeType()) {
1637 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001638 // FIXME: Better diagnostic.
1639 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001640 return false;
1641 }
1642
1643 Size = Info.Ctx.getTypeSizeInChars(Type);
1644 return true;
1645}
1646
1647/// Update a pointer value to model pointer arithmetic.
1648/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001649/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001650/// \param LVal - The pointer value to be updated.
1651/// \param EltTy - The pointee type represented by LVal.
1652/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001653static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1654 LValue &LVal, QualType EltTy,
1655 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001656 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001657 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001658 return false;
1659
1660 // Compute the new offset in the appropriate width.
1661 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001662 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001663 return true;
1664}
1665
Richard Smith66c96992012-02-18 22:04:06 +00001666/// Update an lvalue to refer to a component of a complex number.
1667/// \param Info - Information about the ongoing evaluation.
1668/// \param LVal - The lvalue to be updated.
1669/// \param EltTy - The complex number's component type.
1670/// \param Imag - False for the real component, true for the imaginary.
1671static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1672 LValue &LVal, QualType EltTy,
1673 bool Imag) {
1674 if (Imag) {
1675 CharUnits SizeOfComponent;
1676 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1677 return false;
1678 LVal.Offset += SizeOfComponent;
1679 }
1680 LVal.addComplex(Info, E, EltTy, Imag);
1681 return true;
1682}
1683
Richard Smith27908702011-10-24 17:54:18 +00001684/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001685///
1686/// \param Info Information about the ongoing evaluation.
1687/// \param E An expression to be used when printing diagnostics.
1688/// \param VD The variable whose initializer should be obtained.
1689/// \param Frame The frame in which the variable was created. Must be null
1690/// if this variable is not local to the evaluation.
1691/// \param Result Filled in with a pointer to the value of the variable.
1692static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1693 const VarDecl *VD, CallStackFrame *Frame,
1694 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001695 // If this is a parameter to an active constexpr function call, perform
1696 // argument substitution.
1697 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001698 // Assume arguments of a potential constant expression are unknown
1699 // constant expressions.
1700 if (Info.CheckingPotentialConstantExpression)
1701 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001702 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001703 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001704 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001705 }
Richard Smith3229b742013-05-05 21:17:10 +00001706 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001707 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001708 }
Richard Smith27908702011-10-24 17:54:18 +00001709
Richard Smithd9f663b2013-04-22 15:31:51 +00001710 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001711 if (Frame) {
1712 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001713 // If we've carried on past an unevaluatable local variable initializer,
1714 // we can't go any further. This can happen during potential constant
1715 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001716 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001717 }
1718
Richard Smithd0b4dd62011-12-19 06:19:21 +00001719 // Dig out the initializer, and use the declaration which it's attached to.
1720 const Expr *Init = VD->getAnyInitializer(VD);
1721 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001722 // If we're checking a potential constant expression, the variable could be
1723 // initialized later.
1724 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001725 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001726 return false;
1727 }
1728
Richard Smithd62306a2011-11-10 06:34:14 +00001729 // If we're currently evaluating the initializer of this declaration, use that
1730 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001731 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001732 Result = Info.EvaluatingDeclValue;
1733 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001734 }
1735
Richard Smithcecf1842011-11-01 21:06:14 +00001736 // Never evaluate the initializer of a weak variable. We can't be sure that
1737 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001738 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001739 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001740 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001741 }
Richard Smithcecf1842011-11-01 21:06:14 +00001742
Richard Smithd0b4dd62011-12-19 06:19:21 +00001743 // Check that we can fold the initializer. In C++, we will have already done
1744 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001745 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001746 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001747 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001748 Notes.size() + 1) << VD;
1749 Info.Note(VD->getLocation(), diag::note_declared_at);
1750 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001751 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001752 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001753 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001754 Notes.size() + 1) << VD;
1755 Info.Note(VD->getLocation(), diag::note_declared_at);
1756 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001757 }
Richard Smith27908702011-10-24 17:54:18 +00001758
Richard Smith3229b742013-05-05 21:17:10 +00001759 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001760 return true;
Richard Smith27908702011-10-24 17:54:18 +00001761}
1762
Richard Smith11562c52011-10-28 17:51:58 +00001763static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001764 Qualifiers Quals = T.getQualifiers();
1765 return Quals.hasConst() && !Quals.hasVolatile();
1766}
1767
Richard Smithe97cbd72011-11-11 04:05:33 +00001768/// Get the base index of the given base class within an APValue representing
1769/// the given derived class.
1770static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1771 const CXXRecordDecl *Base) {
1772 Base = Base->getCanonicalDecl();
1773 unsigned Index = 0;
1774 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1775 E = Derived->bases_end(); I != E; ++I, ++Index) {
1776 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1777 return Index;
1778 }
1779
1780 llvm_unreachable("base class missing from derived class's bases list");
1781}
1782
Richard Smith3da88fa2013-04-26 14:36:30 +00001783/// Extract the value of a character from a string literal.
1784static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1785 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001786 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001787 const StringLiteral *S = cast<StringLiteral>(Lit);
1788 const ConstantArrayType *CAT =
1789 Info.Ctx.getAsConstantArrayType(S->getType());
1790 assert(CAT && "string literal isn't an array");
1791 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001792 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001793
1794 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001795 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001796 if (Index < S->getLength())
1797 Value = S->getCodeUnit(Index);
1798 return Value;
1799}
1800
Richard Smith3da88fa2013-04-26 14:36:30 +00001801// Expand a string literal into an array of characters.
1802static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1803 APValue &Result) {
1804 const StringLiteral *S = cast<StringLiteral>(Lit);
1805 const ConstantArrayType *CAT =
1806 Info.Ctx.getAsConstantArrayType(S->getType());
1807 assert(CAT && "string literal isn't an array");
1808 QualType CharType = CAT->getElementType();
1809 assert(CharType->isIntegerType() && "unexpected character type");
1810
1811 unsigned Elts = CAT->getSize().getZExtValue();
1812 Result = APValue(APValue::UninitArray(),
1813 std::min(S->getLength(), Elts), Elts);
1814 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1815 CharType->isUnsignedIntegerType());
1816 if (Result.hasArrayFiller())
1817 Result.getArrayFiller() = APValue(Value);
1818 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1819 Value = S->getCodeUnit(I);
1820 Result.getArrayInitializedElt(I) = APValue(Value);
1821 }
1822}
1823
1824// Expand an array so that it has more than Index filled elements.
1825static void expandArray(APValue &Array, unsigned Index) {
1826 unsigned Size = Array.getArraySize();
1827 assert(Index < Size);
1828
1829 // Always at least double the number of elements for which we store a value.
1830 unsigned OldElts = Array.getArrayInitializedElts();
1831 unsigned NewElts = std::max(Index+1, OldElts * 2);
1832 NewElts = std::min(Size, std::max(NewElts, 8u));
1833
1834 // Copy the data across.
1835 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1836 for (unsigned I = 0; I != OldElts; ++I)
1837 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1838 for (unsigned I = OldElts; I != NewElts; ++I)
1839 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1840 if (NewValue.hasArrayFiller())
1841 NewValue.getArrayFiller() = Array.getArrayFiller();
1842 Array.swap(NewValue);
1843}
1844
Richard Smith861b5b52013-05-07 23:34:45 +00001845/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001846enum AccessKinds {
1847 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001848 AK_Assign,
1849 AK_Increment,
1850 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001851};
1852
Richard Smith3229b742013-05-05 21:17:10 +00001853/// A handle to a complete object (an object that is not a subobject of
1854/// another object).
1855struct CompleteObject {
1856 /// The value of the complete object.
1857 APValue *Value;
1858 /// The type of the complete object.
1859 QualType Type;
1860
1861 CompleteObject() : Value(0) {}
1862 CompleteObject(APValue *Value, QualType Type)
1863 : Value(Value), Type(Type) {
1864 assert(Value && "missing value for complete object");
1865 }
1866
David Blaikie7d170102013-05-15 07:37:26 +00001867 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001868};
1869
Richard Smith3da88fa2013-04-26 14:36:30 +00001870/// Find the designated sub-object of an rvalue.
1871template<typename SubobjectHandler>
1872typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001873findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001874 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001875 if (Sub.Invalid)
1876 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001877 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001878 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001879 if (Info.getLangOpts().CPlusPlus11)
1880 Info.Diag(E, diag::note_constexpr_access_past_end)
1881 << handler.AccessKind;
1882 else
1883 Info.Diag(E);
1884 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001885 }
Richard Smith6804be52011-11-11 08:28:03 +00001886 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001887 return handler.found(*Obj.Value, Obj.Type);
1888 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001889 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001890 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001891
Richard Smith3229b742013-05-05 21:17:10 +00001892 APValue *O = Obj.Value;
1893 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001894 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001895 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001896 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001897 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001898 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001899 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001900 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001901 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001902 // Note, it should not be possible to form a pointer with a valid
1903 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001904 if (Info.getLangOpts().CPlusPlus11)
1905 Info.Diag(E, diag::note_constexpr_access_past_end)
1906 << handler.AccessKind;
1907 else
1908 Info.Diag(E);
1909 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001910 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001911
1912 ObjType = CAT->getElementType();
1913
Richard Smith14a94132012-02-17 03:35:37 +00001914 // An array object is represented as either an Array APValue or as an
1915 // LValue which refers to a string literal.
1916 if (O->isLValue()) {
1917 assert(I == N - 1 && "extracting subobject of character?");
1918 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001919 if (handler.AccessKind != AK_Read)
1920 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1921 *O);
1922 else
1923 return handler.foundString(*O, ObjType, Index);
1924 }
1925
1926 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001927 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001928 else if (handler.AccessKind != AK_Read) {
1929 expandArray(*O, Index);
1930 O = &O->getArrayInitializedElt(Index);
1931 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001932 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001933 } else if (ObjType->isAnyComplexType()) {
1934 // Next subobject is a complex number.
1935 uint64_t Index = Sub.Entries[I].ArrayIndex;
1936 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001937 if (Info.getLangOpts().CPlusPlus11)
1938 Info.Diag(E, diag::note_constexpr_access_past_end)
1939 << handler.AccessKind;
1940 else
1941 Info.Diag(E);
1942 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001943 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001944
1945 bool WasConstQualified = ObjType.isConstQualified();
1946 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1947 if (WasConstQualified)
1948 ObjType.addConst();
1949
Richard Smith66c96992012-02-18 22:04:06 +00001950 assert(I == N - 1 && "extracting subobject of scalar?");
1951 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001952 return handler.found(Index ? O->getComplexIntImag()
1953 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001954 } else {
1955 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001956 return handler.found(Index ? O->getComplexFloatImag()
1957 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001958 }
Richard Smithd62306a2011-11-10 06:34:14 +00001959 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001960 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001961 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001962 << Field;
1963 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001964 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001965 }
1966
Richard Smithd62306a2011-11-10 06:34:14 +00001967 // Next subobject is a class, struct or union field.
1968 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1969 if (RD->isUnion()) {
1970 const FieldDecl *UnionField = O->getUnionField();
1971 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001972 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001973 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1974 << handler.AccessKind << Field << !UnionField << UnionField;
1975 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 }
Richard Smithd62306a2011-11-10 06:34:14 +00001977 O = &O->getUnionValue();
1978 } else
1979 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001980
1981 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001982 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001983 if (WasConstQualified && !Field->isMutable())
1984 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001985
1986 if (ObjType.isVolatileQualified()) {
1987 if (Info.getLangOpts().CPlusPlus) {
1988 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001989 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1990 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001991 Info.Note(Field->getLocation(), diag::note_declared_at);
1992 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001993 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001994 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001995 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001996 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001997 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001998 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001999 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2000 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2001 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002002
2003 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002004 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002005 if (WasConstQualified)
2006 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002007 }
Richard Smithd62306a2011-11-10 06:34:14 +00002008
Richard Smithf57d8cb2011-12-09 22:58:01 +00002009 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002010 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00002011 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2012 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002013 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002014 }
2015
Richard Smith3da88fa2013-04-26 14:36:30 +00002016 return handler.found(*O, ObjType);
2017}
2018
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002019namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002020struct ExtractSubobjectHandler {
2021 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002022 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002023
2024 static const AccessKinds AccessKind = AK_Read;
2025
2026 typedef bool result_type;
2027 bool failed() { return false; }
2028 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002029 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002030 return true;
2031 }
2032 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002033 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002034 return true;
2035 }
2036 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002037 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002038 return true;
2039 }
2040 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002041 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002042 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2043 return true;
2044 }
2045};
Richard Smith3229b742013-05-05 21:17:10 +00002046} // end anonymous namespace
2047
Richard Smith3da88fa2013-04-26 14:36:30 +00002048const AccessKinds ExtractSubobjectHandler::AccessKind;
2049
2050/// Extract the designated sub-object of an rvalue.
2051static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002052 const CompleteObject &Obj,
2053 const SubobjectDesignator &Sub,
2054 APValue &Result) {
2055 ExtractSubobjectHandler Handler = { Info, Result };
2056 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002057}
2058
Richard Smith3229b742013-05-05 21:17:10 +00002059namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002060struct ModifySubobjectHandler {
2061 EvalInfo &Info;
2062 APValue &NewVal;
2063 const Expr *E;
2064
2065 typedef bool result_type;
2066 static const AccessKinds AccessKind = AK_Assign;
2067
2068 bool checkConst(QualType QT) {
2069 // Assigning to a const object has undefined behavior.
2070 if (QT.isConstQualified()) {
2071 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2072 return false;
2073 }
2074 return true;
2075 }
2076
2077 bool failed() { return false; }
2078 bool found(APValue &Subobj, QualType SubobjType) {
2079 if (!checkConst(SubobjType))
2080 return false;
2081 // We've been given ownership of NewVal, so just swap it in.
2082 Subobj.swap(NewVal);
2083 return true;
2084 }
2085 bool found(APSInt &Value, QualType SubobjType) {
2086 if (!checkConst(SubobjType))
2087 return false;
2088 if (!NewVal.isInt()) {
2089 // Maybe trying to write a cast pointer value into a complex?
2090 Info.Diag(E);
2091 return false;
2092 }
2093 Value = NewVal.getInt();
2094 return true;
2095 }
2096 bool found(APFloat &Value, QualType SubobjType) {
2097 if (!checkConst(SubobjType))
2098 return false;
2099 Value = NewVal.getFloat();
2100 return true;
2101 }
2102 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2103 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2104 }
2105};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002106} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002107
Richard Smith3229b742013-05-05 21:17:10 +00002108const AccessKinds ModifySubobjectHandler::AccessKind;
2109
Richard Smith3da88fa2013-04-26 14:36:30 +00002110/// Update the designated sub-object of an rvalue to the given value.
2111static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002112 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002113 const SubobjectDesignator &Sub,
2114 APValue &NewVal) {
2115 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002116 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002117}
2118
Richard Smith84f6dcf2012-02-02 01:16:57 +00002119/// Find the position where two subobject designators diverge, or equivalently
2120/// the length of the common initial subsequence.
2121static unsigned FindDesignatorMismatch(QualType ObjType,
2122 const SubobjectDesignator &A,
2123 const SubobjectDesignator &B,
2124 bool &WasArrayIndex) {
2125 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2126 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002127 if (!ObjType.isNull() &&
2128 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002129 // Next subobject is an array element.
2130 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2131 WasArrayIndex = true;
2132 return I;
2133 }
Richard Smith66c96992012-02-18 22:04:06 +00002134 if (ObjType->isAnyComplexType())
2135 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2136 else
2137 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002138 } else {
2139 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2140 WasArrayIndex = false;
2141 return I;
2142 }
2143 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2144 // Next subobject is a field.
2145 ObjType = FD->getType();
2146 else
2147 // Next subobject is a base class.
2148 ObjType = QualType();
2149 }
2150 }
2151 WasArrayIndex = false;
2152 return I;
2153}
2154
2155/// Determine whether the given subobject designators refer to elements of the
2156/// same array object.
2157static bool AreElementsOfSameArray(QualType ObjType,
2158 const SubobjectDesignator &A,
2159 const SubobjectDesignator &B) {
2160 if (A.Entries.size() != B.Entries.size())
2161 return false;
2162
2163 bool IsArray = A.MostDerivedArraySize != 0;
2164 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2165 // A is a subobject of the array element.
2166 return false;
2167
2168 // If A (and B) designates an array element, the last entry will be the array
2169 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2170 // of length 1' case, and the entire path must match.
2171 bool WasArrayIndex;
2172 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2173 return CommonLength >= A.Entries.size() - IsArray;
2174}
2175
Richard Smith3229b742013-05-05 21:17:10 +00002176/// Find the complete object to which an LValue refers.
2177CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2178 const LValue &LVal, QualType LValType) {
2179 if (!LVal.Base) {
2180 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2181 return CompleteObject();
2182 }
2183
2184 CallStackFrame *Frame = 0;
2185 if (LVal.CallIndex) {
2186 Frame = Info.getCallFrame(LVal.CallIndex);
2187 if (!Frame) {
2188 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2189 << AK << LVal.Base.is<const ValueDecl*>();
2190 NoteLValueLocation(Info, LVal.Base);
2191 return CompleteObject();
2192 }
Richard Smith3229b742013-05-05 21:17:10 +00002193 }
2194
2195 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2196 // is not a constant expression (even if the object is non-volatile). We also
2197 // apply this rule to C++98, in order to conform to the expected 'volatile'
2198 // semantics.
2199 if (LValType.isVolatileQualified()) {
2200 if (Info.getLangOpts().CPlusPlus)
2201 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2202 << AK << LValType;
2203 else
2204 Info.Diag(E);
2205 return CompleteObject();
2206 }
2207
2208 // Compute value storage location and type of base object.
2209 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002210 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002211
2212 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2213 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2214 // In C++11, constexpr, non-volatile variables initialized with constant
2215 // expressions are constant expressions too. Inside constexpr functions,
2216 // parameters are constant expressions even if they're non-const.
2217 // In C++1y, objects local to a constant expression (those with a Frame) are
2218 // both readable and writable inside constant expressions.
2219 // In C, such things can also be folded, although they are not ICEs.
2220 const VarDecl *VD = dyn_cast<VarDecl>(D);
2221 if (VD) {
2222 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2223 VD = VDef;
2224 }
2225 if (!VD || VD->isInvalidDecl()) {
2226 Info.Diag(E);
2227 return CompleteObject();
2228 }
2229
2230 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002231 if (BaseType.isVolatileQualified()) {
2232 if (Info.getLangOpts().CPlusPlus) {
2233 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2234 << AK << 1 << VD;
2235 Info.Note(VD->getLocation(), diag::note_declared_at);
2236 } else {
2237 Info.Diag(E);
2238 }
2239 return CompleteObject();
2240 }
2241
2242 // Unless we're looking at a local variable or argument in a constexpr call,
2243 // the variable we're reading must be const.
2244 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002245 if (Info.getLangOpts().CPlusPlus1y &&
2246 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2247 // OK, we can read and modify an object if we're in the process of
2248 // evaluating its initializer, because its lifetime began in this
2249 // evaluation.
2250 } else if (AK != AK_Read) {
2251 // All the remaining cases only permit reading.
2252 Info.Diag(E, diag::note_constexpr_modify_global);
2253 return CompleteObject();
2254 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002255 // OK, we can read this variable.
2256 } else if (BaseType->isIntegralOrEnumerationType()) {
2257 if (!BaseType.isConstQualified()) {
2258 if (Info.getLangOpts().CPlusPlus) {
2259 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2260 Info.Note(VD->getLocation(), diag::note_declared_at);
2261 } else {
2262 Info.Diag(E);
2263 }
2264 return CompleteObject();
2265 }
2266 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2267 // We support folding of const floating-point types, in order to make
2268 // static const data members of such types (supported as an extension)
2269 // more useful.
2270 if (Info.getLangOpts().CPlusPlus11) {
2271 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2272 Info.Note(VD->getLocation(), diag::note_declared_at);
2273 } else {
2274 Info.CCEDiag(E);
2275 }
2276 } else {
2277 // FIXME: Allow folding of values of any literal type in all languages.
2278 if (Info.getLangOpts().CPlusPlus11) {
2279 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2280 Info.Note(VD->getLocation(), diag::note_declared_at);
2281 } else {
2282 Info.Diag(E);
2283 }
2284 return CompleteObject();
2285 }
2286 }
2287
2288 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2289 return CompleteObject();
2290 } else {
2291 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2292
2293 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002294 if (const MaterializeTemporaryExpr *MTE =
2295 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2296 assert(MTE->getStorageDuration() == SD_Static &&
2297 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002298
Richard Smithe6c01442013-06-05 00:46:14 +00002299 // Per C++1y [expr.const]p2:
2300 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2301 // - a [...] glvalue of integral or enumeration type that refers to
2302 // a non-volatile const object [...]
2303 // [...]
2304 // - a [...] glvalue of literal type that refers to a non-volatile
2305 // object whose lifetime began within the evaluation of e.
2306 //
2307 // C++11 misses the 'began within the evaluation of e' check and
2308 // instead allows all temporaries, including things like:
2309 // int &&r = 1;
2310 // int x = ++r;
2311 // constexpr int k = r;
2312 // Therefore we use the C++1y rules in C++11 too.
2313 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2314 const ValueDecl *ED = MTE->getExtendingDecl();
2315 if (!(BaseType.isConstQualified() &&
2316 BaseType->isIntegralOrEnumerationType()) &&
2317 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2318 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2319 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2320 return CompleteObject();
2321 }
2322
2323 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2324 assert(BaseVal && "got reference to unevaluated temporary");
2325 } else {
2326 Info.Diag(E);
2327 return CompleteObject();
2328 }
2329 } else {
2330 BaseVal = &Frame->Temporaries[Base];
2331 }
Richard Smith3229b742013-05-05 21:17:10 +00002332
2333 // Volatile temporary objects cannot be accessed in constant expressions.
2334 if (BaseType.isVolatileQualified()) {
2335 if (Info.getLangOpts().CPlusPlus) {
2336 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2337 << AK << 0;
2338 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2339 } else {
2340 Info.Diag(E);
2341 }
2342 return CompleteObject();
2343 }
2344 }
2345
Richard Smith7525ff62013-05-09 07:14:00 +00002346 // During the construction of an object, it is not yet 'const'.
2347 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2348 // and this doesn't do quite the right thing for const subobjects of the
2349 // object under construction.
2350 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2351 BaseType = Info.Ctx.getCanonicalType(BaseType);
2352 BaseType.removeLocalConst();
2353 }
2354
Richard Smith3229b742013-05-05 21:17:10 +00002355 // In C++1y, we can't safely access any mutable state when checking a
2356 // potential constant expression.
2357 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2358 Info.CheckingPotentialConstantExpression)
2359 return CompleteObject();
2360
2361 return CompleteObject(BaseVal, BaseType);
2362}
2363
Richard Smith243ef902013-05-05 23:31:59 +00002364/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2365/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2366/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002367///
2368/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002369/// \param Conv - The expression for which we are performing the conversion.
2370/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002371/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2372/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002373/// \param LVal - The glvalue on which we are attempting to perform this action.
2374/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002375static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002376 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002377 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002378 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002379 return false;
2380
Richard Smith3229b742013-05-05 21:17:10 +00002381 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002382 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002383 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2384 !Type.isVolatileQualified()) {
2385 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2386 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2387 // initializer until now for such expressions. Such an expression can't be
2388 // an ICE in C, so this only matters for fold.
2389 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2390 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002391 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002392 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002393 }
Richard Smith3229b742013-05-05 21:17:10 +00002394 APValue Lit;
2395 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2396 return false;
2397 CompleteObject LitObj(&Lit, Base->getType());
2398 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2399 } else if (isa<StringLiteral>(Base)) {
2400 // We represent a string literal array as an lvalue pointing at the
2401 // corresponding expression, rather than building an array of chars.
2402 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2403 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2404 CompleteObject StrObj(&Str, Base->getType());
2405 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002406 }
Richard Smith11562c52011-10-28 17:51:58 +00002407 }
2408
Richard Smith3229b742013-05-05 21:17:10 +00002409 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2410 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002411}
2412
2413/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002414static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002415 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002416 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002417 return false;
2418
Richard Smith3229b742013-05-05 21:17:10 +00002419 if (!Info.getLangOpts().CPlusPlus1y) {
2420 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002421 return false;
2422 }
2423
Richard Smith3229b742013-05-05 21:17:10 +00002424 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2425 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002426}
2427
Richard Smith243ef902013-05-05 23:31:59 +00002428static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2429 return T->isSignedIntegerType() &&
2430 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2431}
2432
2433namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002434struct CompoundAssignSubobjectHandler {
2435 EvalInfo &Info;
2436 const Expr *E;
2437 QualType PromotedLHSType;
2438 BinaryOperatorKind Opcode;
2439 const APValue &RHS;
2440
2441 static const AccessKinds AccessKind = AK_Assign;
2442
2443 typedef bool result_type;
2444
2445 bool checkConst(QualType QT) {
2446 // Assigning to a const object has undefined behavior.
2447 if (QT.isConstQualified()) {
2448 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2449 return false;
2450 }
2451 return true;
2452 }
2453
2454 bool failed() { return false; }
2455 bool found(APValue &Subobj, QualType SubobjType) {
2456 switch (Subobj.getKind()) {
2457 case APValue::Int:
2458 return found(Subobj.getInt(), SubobjType);
2459 case APValue::Float:
2460 return found(Subobj.getFloat(), SubobjType);
2461 case APValue::ComplexInt:
2462 case APValue::ComplexFloat:
2463 // FIXME: Implement complex compound assignment.
2464 Info.Diag(E);
2465 return false;
2466 case APValue::LValue:
2467 return foundPointer(Subobj, SubobjType);
2468 default:
2469 // FIXME: can this happen?
2470 Info.Diag(E);
2471 return false;
2472 }
2473 }
2474 bool found(APSInt &Value, QualType SubobjType) {
2475 if (!checkConst(SubobjType))
2476 return false;
2477
2478 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2479 // We don't support compound assignment on integer-cast-to-pointer
2480 // values.
2481 Info.Diag(E);
2482 return false;
2483 }
2484
2485 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2486 SubobjType, Value);
2487 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2488 return false;
2489 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2490 return true;
2491 }
2492 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002493 return checkConst(SubobjType) &&
2494 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2495 Value) &&
2496 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2497 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002498 }
2499 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2500 if (!checkConst(SubobjType))
2501 return false;
2502
2503 QualType PointeeType;
2504 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2505 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002506
2507 if (PointeeType.isNull() || !RHS.isInt() ||
2508 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002509 Info.Diag(E);
2510 return false;
2511 }
2512
Richard Smith861b5b52013-05-07 23:34:45 +00002513 int64_t Offset = getExtValue(RHS.getInt());
2514 if (Opcode == BO_Sub)
2515 Offset = -Offset;
2516
2517 LValue LVal;
2518 LVal.setFrom(Info.Ctx, Subobj);
2519 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2520 return false;
2521 LVal.moveInto(Subobj);
2522 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002523 }
2524 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2525 llvm_unreachable("shouldn't encounter string elements here");
2526 }
2527};
2528} // end anonymous namespace
2529
2530const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2531
2532/// Perform a compound assignment of LVal <op>= RVal.
2533static bool handleCompoundAssignment(
2534 EvalInfo &Info, const Expr *E,
2535 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2536 BinaryOperatorKind Opcode, const APValue &RVal) {
2537 if (LVal.Designator.Invalid)
2538 return false;
2539
2540 if (!Info.getLangOpts().CPlusPlus1y) {
2541 Info.Diag(E);
2542 return false;
2543 }
2544
2545 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2546 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2547 RVal };
2548 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2549}
2550
2551namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002552struct IncDecSubobjectHandler {
2553 EvalInfo &Info;
2554 const Expr *E;
2555 AccessKinds AccessKind;
2556 APValue *Old;
2557
2558 typedef bool result_type;
2559
2560 bool checkConst(QualType QT) {
2561 // Assigning to a const object has undefined behavior.
2562 if (QT.isConstQualified()) {
2563 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2564 return false;
2565 }
2566 return true;
2567 }
2568
2569 bool failed() { return false; }
2570 bool found(APValue &Subobj, QualType SubobjType) {
2571 // Stash the old value. Also clear Old, so we don't clobber it later
2572 // if we're post-incrementing a complex.
2573 if (Old) {
2574 *Old = Subobj;
2575 Old = 0;
2576 }
2577
2578 switch (Subobj.getKind()) {
2579 case APValue::Int:
2580 return found(Subobj.getInt(), SubobjType);
2581 case APValue::Float:
2582 return found(Subobj.getFloat(), SubobjType);
2583 case APValue::ComplexInt:
2584 return found(Subobj.getComplexIntReal(),
2585 SubobjType->castAs<ComplexType>()->getElementType()
2586 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2587 case APValue::ComplexFloat:
2588 return found(Subobj.getComplexFloatReal(),
2589 SubobjType->castAs<ComplexType>()->getElementType()
2590 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2591 case APValue::LValue:
2592 return foundPointer(Subobj, SubobjType);
2593 default:
2594 // FIXME: can this happen?
2595 Info.Diag(E);
2596 return false;
2597 }
2598 }
2599 bool found(APSInt &Value, QualType SubobjType) {
2600 if (!checkConst(SubobjType))
2601 return false;
2602
2603 if (!SubobjType->isIntegerType()) {
2604 // We don't support increment / decrement on integer-cast-to-pointer
2605 // values.
2606 Info.Diag(E);
2607 return false;
2608 }
2609
2610 if (Old) *Old = APValue(Value);
2611
2612 // bool arithmetic promotes to int, and the conversion back to bool
2613 // doesn't reduce mod 2^n, so special-case it.
2614 if (SubobjType->isBooleanType()) {
2615 if (AccessKind == AK_Increment)
2616 Value = 1;
2617 else
2618 Value = !Value;
2619 return true;
2620 }
2621
2622 bool WasNegative = Value.isNegative();
2623 if (AccessKind == AK_Increment) {
2624 ++Value;
2625
2626 if (!WasNegative && Value.isNegative() &&
2627 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2628 APSInt ActualValue(Value, /*IsUnsigned*/true);
2629 HandleOverflow(Info, E, ActualValue, SubobjType);
2630 }
2631 } else {
2632 --Value;
2633
2634 if (WasNegative && !Value.isNegative() &&
2635 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2636 unsigned BitWidth = Value.getBitWidth();
2637 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2638 ActualValue.setBit(BitWidth);
2639 HandleOverflow(Info, E, ActualValue, SubobjType);
2640 }
2641 }
2642 return true;
2643 }
2644 bool found(APFloat &Value, QualType SubobjType) {
2645 if (!checkConst(SubobjType))
2646 return false;
2647
2648 if (Old) *Old = APValue(Value);
2649
2650 APFloat One(Value.getSemantics(), 1);
2651 if (AccessKind == AK_Increment)
2652 Value.add(One, APFloat::rmNearestTiesToEven);
2653 else
2654 Value.subtract(One, APFloat::rmNearestTiesToEven);
2655 return true;
2656 }
2657 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2658 if (!checkConst(SubobjType))
2659 return false;
2660
2661 QualType PointeeType;
2662 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2663 PointeeType = PT->getPointeeType();
2664 else {
2665 Info.Diag(E);
2666 return false;
2667 }
2668
2669 LValue LVal;
2670 LVal.setFrom(Info.Ctx, Subobj);
2671 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2672 AccessKind == AK_Increment ? 1 : -1))
2673 return false;
2674 LVal.moveInto(Subobj);
2675 return true;
2676 }
2677 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2678 llvm_unreachable("shouldn't encounter string elements here");
2679 }
2680};
2681} // end anonymous namespace
2682
2683/// Perform an increment or decrement on LVal.
2684static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2685 QualType LValType, bool IsIncrement, APValue *Old) {
2686 if (LVal.Designator.Invalid)
2687 return false;
2688
2689 if (!Info.getLangOpts().CPlusPlus1y) {
2690 Info.Diag(E);
2691 return false;
2692 }
2693
2694 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2695 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2696 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2697 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2698}
2699
Richard Smithe97cbd72011-11-11 04:05:33 +00002700/// Build an lvalue for the object argument of a member function call.
2701static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2702 LValue &This) {
2703 if (Object->getType()->isPointerType())
2704 return EvaluatePointer(Object, This, Info);
2705
2706 if (Object->isGLValue())
2707 return EvaluateLValue(Object, This, Info);
2708
Richard Smithd9f663b2013-04-22 15:31:51 +00002709 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002710 return EvaluateTemporary(Object, This, Info);
2711
2712 return false;
2713}
2714
2715/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2716/// lvalue referring to the result.
2717///
2718/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002719/// \param LV - An lvalue referring to the base of the member pointer.
2720/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002721/// \param IncludeMember - Specifies whether the member itself is included in
2722/// the resulting LValue subobject designator. This is not possible when
2723/// creating a bound member function.
2724/// \return The field or method declaration to which the member pointer refers,
2725/// or 0 if evaluation fails.
2726static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002727 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002728 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002729 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002730 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002731 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002732 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002733 return 0;
2734
2735 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2736 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002737 if (!MemPtr.getDecl()) {
2738 // FIXME: Specific diagnostic.
2739 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002740 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002741 }
Richard Smith253c2a32012-01-27 01:14:48 +00002742
Richard Smith027bf112011-11-17 22:56:20 +00002743 if (MemPtr.isDerivedMember()) {
2744 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002745 // The end of the derived-to-base path for the base object must match the
2746 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002747 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002748 LV.Designator.Entries.size()) {
2749 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002750 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002751 }
Richard Smith027bf112011-11-17 22:56:20 +00002752 unsigned PathLengthToMember =
2753 LV.Designator.Entries.size() - MemPtr.Path.size();
2754 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2755 const CXXRecordDecl *LVDecl = getAsBaseClass(
2756 LV.Designator.Entries[PathLengthToMember + I]);
2757 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002758 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2759 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002760 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002761 }
Richard Smith027bf112011-11-17 22:56:20 +00002762 }
2763
2764 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002765 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002766 PathLengthToMember))
2767 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002768 } else if (!MemPtr.Path.empty()) {
2769 // Extend the LValue path with the member pointer's path.
2770 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2771 MemPtr.Path.size() + IncludeMember);
2772
2773 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002774 if (const PointerType *PT = LVType->getAs<PointerType>())
2775 LVType = PT->getPointeeType();
2776 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2777 assert(RD && "member pointer access on non-class-type expression");
2778 // The first class in the path is that of the lvalue.
2779 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2780 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002781 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002782 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002783 RD = Base;
2784 }
2785 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002786 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2787 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002788 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002789 }
2790
2791 // Add the member. Note that we cannot build bound member functions here.
2792 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002793 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002794 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002795 return 0;
2796 } else if (const IndirectFieldDecl *IFD =
2797 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002798 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002799 return 0;
2800 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002801 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002802 }
Richard Smith027bf112011-11-17 22:56:20 +00002803 }
2804
2805 return MemPtr.getDecl();
2806}
2807
Richard Smith84401042013-06-03 05:03:02 +00002808static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2809 const BinaryOperator *BO,
2810 LValue &LV,
2811 bool IncludeMember = true) {
2812 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2813
2814 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2815 if (Info.keepEvaluatingAfterFailure()) {
2816 MemberPtr MemPtr;
2817 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2818 }
2819 return 0;
2820 }
2821
2822 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2823 BO->getRHS(), IncludeMember);
2824}
2825
Richard Smith027bf112011-11-17 22:56:20 +00002826/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2827/// the provided lvalue, which currently refers to the base object.
2828static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2829 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002830 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002831 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002832 return false;
2833
Richard Smitha8105bc2012-01-06 16:39:00 +00002834 QualType TargetQT = E->getType();
2835 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2836 TargetQT = PT->getPointeeType();
2837
2838 // Check this cast lands within the final derived-to-base subobject path.
2839 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002840 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002841 << D.MostDerivedType << TargetQT;
2842 return false;
2843 }
2844
Richard Smith027bf112011-11-17 22:56:20 +00002845 // Check the type of the final cast. We don't need to check the path,
2846 // since a cast can only be formed if the path is unique.
2847 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002848 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2849 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002850 if (NewEntriesSize == D.MostDerivedPathLength)
2851 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2852 else
Richard Smith027bf112011-11-17 22:56:20 +00002853 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002854 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002855 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002856 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002857 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002858 }
Richard Smith027bf112011-11-17 22:56:20 +00002859
2860 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002861 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002862}
2863
Mike Stump876387b2009-10-27 22:09:17 +00002864namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002865enum EvalStmtResult {
2866 /// Evaluation failed.
2867 ESR_Failed,
2868 /// Hit a 'return' statement.
2869 ESR_Returned,
2870 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002871 ESR_Succeeded,
2872 /// Hit a 'continue' statement.
2873 ESR_Continue,
2874 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002875 ESR_Break,
2876 /// Still scanning for 'case' or 'default' statement.
2877 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002878};
2879}
2880
Richard Smithd9f663b2013-04-22 15:31:51 +00002881static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2882 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2883 // We don't need to evaluate the initializer for a static local.
2884 if (!VD->hasLocalStorage())
2885 return true;
2886
2887 LValue Result;
2888 Result.set(VD, Info.CurrentCall->Index);
2889 APValue &Val = Info.CurrentCall->Temporaries[VD];
2890
2891 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2892 // Wipe out any partially-computed value, to allow tracking that this
2893 // evaluation failed.
2894 Val = APValue();
2895 return false;
2896 }
2897 }
2898
2899 return true;
2900}
2901
Richard Smith4e18ca52013-05-06 05:56:11 +00002902/// Evaluate a condition (either a variable declaration or an expression).
2903static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2904 const Expr *Cond, bool &Result) {
2905 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2906 return false;
2907 return EvaluateAsBooleanCondition(Cond, Result, Info);
2908}
2909
2910static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002911 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002912
2913/// Evaluate the body of a loop, and translate the result as appropriate.
2914static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002915 const Stmt *Body,
2916 const SwitchCase *Case = 0) {
2917 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002918 case ESR_Break:
2919 return ESR_Succeeded;
2920 case ESR_Succeeded:
2921 case ESR_Continue:
2922 return ESR_Continue;
2923 case ESR_Failed:
2924 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002925 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002926 return ESR;
2927 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002928 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002929}
2930
Richard Smith496ddcf2013-05-12 17:32:42 +00002931/// Evaluate a switch statement.
2932static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2933 const SwitchStmt *SS) {
2934 // Evaluate the switch condition.
2935 if (SS->getConditionVariable() &&
2936 !EvaluateDecl(Info, SS->getConditionVariable()))
2937 return ESR_Failed;
2938 APSInt Value;
2939 if (!EvaluateInteger(SS->getCond(), Value, Info))
2940 return ESR_Failed;
2941
2942 // Find the switch case corresponding to the value of the condition.
2943 // FIXME: Cache this lookup.
2944 const SwitchCase *Found = 0;
2945 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2946 SC = SC->getNextSwitchCase()) {
2947 if (isa<DefaultStmt>(SC)) {
2948 Found = SC;
2949 continue;
2950 }
2951
2952 const CaseStmt *CS = cast<CaseStmt>(SC);
2953 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2954 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2955 : LHS;
2956 if (LHS <= Value && Value <= RHS) {
2957 Found = SC;
2958 break;
2959 }
2960 }
2961
2962 if (!Found)
2963 return ESR_Succeeded;
2964
2965 // Search the switch body for the switch case and evaluate it from there.
2966 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2967 case ESR_Break:
2968 return ESR_Succeeded;
2969 case ESR_Succeeded:
2970 case ESR_Continue:
2971 case ESR_Failed:
2972 case ESR_Returned:
2973 return ESR;
2974 case ESR_CaseNotFound:
Richard Smith496ddcf2013-05-12 17:32:42 +00002975 llvm_unreachable("couldn't find switch case");
2976 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002977 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002978}
2979
Richard Smith254a73d2011-10-28 22:34:42 +00002980// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002981static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002982 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002983 if (!Info.nextStep(S))
2984 return ESR_Failed;
2985
Richard Smith496ddcf2013-05-12 17:32:42 +00002986 // If we're hunting down a 'case' or 'default' label, recurse through
2987 // substatements until we hit the label.
2988 if (Case) {
2989 // FIXME: We don't start the lifetime of objects whose initialization we
2990 // jump over. However, such objects must be of class type with a trivial
2991 // default constructor that initialize all subobjects, so must be empty,
2992 // so this almost never matters.
2993 switch (S->getStmtClass()) {
2994 case Stmt::CompoundStmtClass:
2995 // FIXME: Precompute which substatement of a compound statement we
2996 // would jump to, and go straight there rather than performing a
2997 // linear scan each time.
2998 case Stmt::LabelStmtClass:
2999 case Stmt::AttributedStmtClass:
3000 case Stmt::DoStmtClass:
3001 break;
3002
3003 case Stmt::CaseStmtClass:
3004 case Stmt::DefaultStmtClass:
3005 if (Case == S)
3006 Case = 0;
3007 break;
3008
3009 case Stmt::IfStmtClass: {
3010 // FIXME: Precompute which side of an 'if' we would jump to, and go
3011 // straight there rather than scanning both sides.
3012 const IfStmt *IS = cast<IfStmt>(S);
3013 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3014 if (ESR != ESR_CaseNotFound || !IS->getElse())
3015 return ESR;
3016 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3017 }
3018
3019 case Stmt::WhileStmtClass: {
3020 EvalStmtResult ESR =
3021 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3022 if (ESR != ESR_Continue)
3023 return ESR;
3024 break;
3025 }
3026
3027 case Stmt::ForStmtClass: {
3028 const ForStmt *FS = cast<ForStmt>(S);
3029 EvalStmtResult ESR =
3030 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3031 if (ESR != ESR_Continue)
3032 return ESR;
3033 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3034 return ESR_Failed;
3035 break;
3036 }
3037
3038 case Stmt::DeclStmtClass:
3039 // FIXME: If the variable has initialization that can't be jumped over,
3040 // bail out of any immediately-surrounding compound-statement too.
3041 default:
3042 return ESR_CaseNotFound;
3043 }
3044 }
3045
Richard Smithd9f663b2013-04-22 15:31:51 +00003046 // FIXME: Mark all temporaries in the current frame as destroyed at
3047 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00003048 switch (S->getStmtClass()) {
3049 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003050 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003051 // Don't bother evaluating beyond an expression-statement which couldn't
3052 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00003053 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003054 return ESR_Failed;
3055 return ESR_Succeeded;
3056 }
3057
3058 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003059 return ESR_Failed;
3060
3061 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003062 return ESR_Succeeded;
3063
Richard Smithd9f663b2013-04-22 15:31:51 +00003064 case Stmt::DeclStmtClass: {
3065 const DeclStmt *DS = cast<DeclStmt>(S);
3066 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3067 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
3068 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3069 return ESR_Failed;
3070 return ESR_Succeeded;
3071 }
3072
Richard Smith357362d2011-12-13 06:39:58 +00003073 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003074 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00003075 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003076 return ESR_Failed;
3077 return ESR_Returned;
3078 }
Richard Smith254a73d2011-10-28 22:34:42 +00003079
3080 case Stmt::CompoundStmtClass: {
3081 const CompoundStmt *CS = cast<CompoundStmt>(S);
3082 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3083 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003084 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3085 if (ESR == ESR_Succeeded)
3086 Case = 0;
3087 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003088 return ESR;
3089 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003090 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003091 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003092
3093 case Stmt::IfStmtClass: {
3094 const IfStmt *IS = cast<IfStmt>(S);
3095
3096 // Evaluate the condition, as either a var decl or as an expression.
3097 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003098 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003099 return ESR_Failed;
3100
3101 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3102 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3103 if (ESR != ESR_Succeeded)
3104 return ESR;
3105 }
3106 return ESR_Succeeded;
3107 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003108
3109 case Stmt::WhileStmtClass: {
3110 const WhileStmt *WS = cast<WhileStmt>(S);
3111 while (true) {
3112 bool Continue;
3113 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3114 Continue))
3115 return ESR_Failed;
3116 if (!Continue)
3117 break;
3118
3119 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3120 if (ESR != ESR_Continue)
3121 return ESR;
3122 }
3123 return ESR_Succeeded;
3124 }
3125
3126 case Stmt::DoStmtClass: {
3127 const DoStmt *DS = cast<DoStmt>(S);
3128 bool Continue;
3129 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003130 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003131 if (ESR != ESR_Continue)
3132 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003133 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003134
3135 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3136 return ESR_Failed;
3137 } while (Continue);
3138 return ESR_Succeeded;
3139 }
3140
3141 case Stmt::ForStmtClass: {
3142 const ForStmt *FS = cast<ForStmt>(S);
3143 if (FS->getInit()) {
3144 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3145 if (ESR != ESR_Succeeded)
3146 return ESR;
3147 }
3148 while (true) {
3149 bool Continue = true;
3150 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3151 FS->getCond(), Continue))
3152 return ESR_Failed;
3153 if (!Continue)
3154 break;
3155
3156 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3157 if (ESR != ESR_Continue)
3158 return ESR;
3159
3160 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3161 return ESR_Failed;
3162 }
3163 return ESR_Succeeded;
3164 }
3165
Richard Smith896e0d72013-05-06 06:51:17 +00003166 case Stmt::CXXForRangeStmtClass: {
3167 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3168
3169 // Initialize the __range variable.
3170 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3171 if (ESR != ESR_Succeeded)
3172 return ESR;
3173
3174 // Create the __begin and __end iterators.
3175 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3176 if (ESR != ESR_Succeeded)
3177 return ESR;
3178
3179 while (true) {
3180 // Condition: __begin != __end.
3181 bool Continue = true;
3182 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3183 return ESR_Failed;
3184 if (!Continue)
3185 break;
3186
3187 // User's variable declaration, initialized by *__begin.
3188 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3189 if (ESR != ESR_Succeeded)
3190 return ESR;
3191
3192 // Loop body.
3193 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3194 if (ESR != ESR_Continue)
3195 return ESR;
3196
3197 // Increment: ++__begin
3198 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3199 return ESR_Failed;
3200 }
3201
3202 return ESR_Succeeded;
3203 }
3204
Richard Smith496ddcf2013-05-12 17:32:42 +00003205 case Stmt::SwitchStmtClass:
3206 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3207
Richard Smith4e18ca52013-05-06 05:56:11 +00003208 case Stmt::ContinueStmtClass:
3209 return ESR_Continue;
3210
3211 case Stmt::BreakStmtClass:
3212 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003213
3214 case Stmt::LabelStmtClass:
3215 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3216
3217 case Stmt::AttributedStmtClass:
3218 // As a general principle, C++11 attributes can be ignored without
3219 // any semantic impact.
3220 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3221 Case);
3222
3223 case Stmt::CaseStmtClass:
3224 case Stmt::DefaultStmtClass:
3225 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003226 }
3227}
3228
Richard Smithcc36f692011-12-22 02:22:31 +00003229/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3230/// default constructor. If so, we'll fold it whether or not it's marked as
3231/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3232/// so we need special handling.
3233static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003234 const CXXConstructorDecl *CD,
3235 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003236 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3237 return false;
3238
Richard Smith66e05fe2012-01-18 05:21:49 +00003239 // Value-initialization does not call a trivial default constructor, so such a
3240 // call is a core constant expression whether or not the constructor is
3241 // constexpr.
3242 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003243 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003244 // FIXME: If DiagDecl is an implicitly-declared special member function,
3245 // we should be much more explicit about why it's not constexpr.
3246 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3247 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3248 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003249 } else {
3250 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3251 }
3252 }
3253 return true;
3254}
3255
Richard Smith357362d2011-12-13 06:39:58 +00003256/// CheckConstexprFunction - Check that a function can be called in a constant
3257/// expression.
3258static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3259 const FunctionDecl *Declaration,
3260 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003261 // Potential constant expressions can contain calls to declared, but not yet
3262 // defined, constexpr functions.
3263 if (Info.CheckingPotentialConstantExpression && !Definition &&
3264 Declaration->isConstexpr())
3265 return false;
3266
Richard Smith0838f3a2013-05-14 05:18:44 +00003267 // Bail out with no diagnostic if the function declaration itself is invalid.
3268 // We will have produced a relevant diagnostic while parsing it.
3269 if (Declaration->isInvalidDecl())
3270 return false;
3271
Richard Smith357362d2011-12-13 06:39:58 +00003272 // Can we evaluate this function call?
3273 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3274 return true;
3275
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003276 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003277 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003278 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3279 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003280 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3281 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3282 << DiagDecl;
3283 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3284 } else {
3285 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3286 }
3287 return false;
3288}
3289
Richard Smithd62306a2011-11-10 06:34:14 +00003290namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003291typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003292}
3293
3294/// EvaluateArgs - Evaluate the arguments to a function call.
3295static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3296 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003297 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003298 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003299 I != E; ++I) {
3300 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3301 // If we're checking for a potential constant expression, evaluate all
3302 // initializers even if some of them fail.
3303 if (!Info.keepEvaluatingAfterFailure())
3304 return false;
3305 Success = false;
3306 }
3307 }
3308 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003309}
3310
Richard Smith254a73d2011-10-28 22:34:42 +00003311/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003312static bool HandleFunctionCall(SourceLocation CallLoc,
3313 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003314 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003315 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003316 ArgVector ArgValues(Args.size());
3317 if (!EvaluateArgs(Args, ArgValues, Info))
3318 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003319
Richard Smith253c2a32012-01-27 01:14:48 +00003320 if (!Info.CheckCallLimit(CallLoc))
3321 return false;
3322
3323 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003324
3325 // For a trivial copy or move assignment, perform an APValue copy. This is
3326 // essential for unions, where the operations performed by the assignment
3327 // operator cannot be represented as statements.
3328 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3329 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3330 assert(This &&
3331 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3332 LValue RHS;
3333 RHS.setFrom(Info.Ctx, ArgValues[0]);
3334 APValue RHSValue;
3335 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3336 RHS, RHSValue))
3337 return false;
3338 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3339 RHSValue))
3340 return false;
3341 This->moveInto(Result);
3342 return true;
3343 }
3344
Richard Smithd9f663b2013-04-22 15:31:51 +00003345 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003346 if (ESR == ESR_Succeeded) {
3347 if (Callee->getResultType()->isVoidType())
3348 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003349 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003350 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003351 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003352}
3353
Richard Smithd62306a2011-11-10 06:34:14 +00003354/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003355static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003356 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003357 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003358 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003359 ArgVector ArgValues(Args.size());
3360 if (!EvaluateArgs(Args, ArgValues, Info))
3361 return false;
3362
Richard Smith253c2a32012-01-27 01:14:48 +00003363 if (!Info.CheckCallLimit(CallLoc))
3364 return false;
3365
Richard Smith3607ffe2012-02-13 03:54:03 +00003366 const CXXRecordDecl *RD = Definition->getParent();
3367 if (RD->getNumVBases()) {
3368 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3369 return false;
3370 }
3371
Richard Smith253c2a32012-01-27 01:14:48 +00003372 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003373
3374 // If it's a delegating constructor, just delegate.
3375 if (Definition->isDelegatingConstructor()) {
3376 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003377 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3378 return false;
3379 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003380 }
3381
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003382 // For a trivial copy or move constructor, perform an APValue copy. This is
3383 // essential for unions, where the operations performed by the constructor
3384 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003385 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003386 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3387 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003388 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003389 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003390 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003391 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003392 }
3393
3394 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003395 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003396 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3397 std::distance(RD->field_begin(), RD->field_end()));
3398
John McCalld7bca762012-05-01 00:38:49 +00003399 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003400 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3401
Richard Smith253c2a32012-01-27 01:14:48 +00003402 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003403 unsigned BasesSeen = 0;
3404#ifndef NDEBUG
3405 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3406#endif
3407 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3408 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003409 LValue Subobject = This;
3410 APValue *Value = &Result;
3411
3412 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003413 if ((*I)->isBaseInitializer()) {
3414 QualType BaseType((*I)->getBaseClass(), 0);
3415#ifndef NDEBUG
3416 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003417 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003418 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3419 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3420 "base class initializers not in expected order");
3421 ++BaseIt;
3422#endif
John McCalld7bca762012-05-01 00:38:49 +00003423 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3424 BaseType->getAsCXXRecordDecl(), &Layout))
3425 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003426 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003427 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003428 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3429 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003430 if (RD->isUnion()) {
3431 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003432 Value = &Result.getUnionValue();
3433 } else {
3434 Value = &Result.getStructField(FD->getFieldIndex());
3435 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003436 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003437 // Walk the indirect field decl's chain to find the object to initialize,
3438 // and make sure we've initialized every step along it.
3439 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3440 CE = IFD->chain_end();
3441 C != CE; ++C) {
3442 FieldDecl *FD = cast<FieldDecl>(*C);
3443 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3444 // Switch the union field if it differs. This happens if we had
3445 // preceding zero-initialization, and we're now initializing a union
3446 // subobject other than the first.
3447 // FIXME: In this case, the values of the other subobjects are
3448 // specified, since zero-initialization sets all padding bits to zero.
3449 if (Value->isUninit() ||
3450 (Value->isUnion() && Value->getUnionField() != FD)) {
3451 if (CD->isUnion())
3452 *Value = APValue(FD);
3453 else
3454 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3455 std::distance(CD->field_begin(), CD->field_end()));
3456 }
John McCalld7bca762012-05-01 00:38:49 +00003457 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3458 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003459 if (CD->isUnion())
3460 Value = &Value->getUnionValue();
3461 else
3462 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003463 }
Richard Smithd62306a2011-11-10 06:34:14 +00003464 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003465 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003466 }
Richard Smith253c2a32012-01-27 01:14:48 +00003467
Richard Smith7525ff62013-05-09 07:14:00 +00003468 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003469 // If we're checking for a potential constant expression, evaluate all
3470 // initializers even if some of them fail.
3471 if (!Info.keepEvaluatingAfterFailure())
3472 return false;
3473 Success = false;
3474 }
Richard Smithd62306a2011-11-10 06:34:14 +00003475 }
3476
Richard Smithd9f663b2013-04-22 15:31:51 +00003477 return Success &&
3478 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003479}
3480
Eli Friedman9a156e52008-11-12 09:44:48 +00003481//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003482// Generic Evaluation
3483//===----------------------------------------------------------------------===//
3484namespace {
3485
Richard Smithf57d8cb2011-12-09 22:58:01 +00003486// FIXME: RetTy is always bool. Remove it.
3487template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003488class ExprEvaluatorBase
3489 : public ConstStmtVisitor<Derived, RetTy> {
3490private:
Richard Smith2e312c82012-03-03 22:46:17 +00003491 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003492 return static_cast<Derived*>(this)->Success(V, E);
3493 }
Richard Smithfddd3842011-12-30 21:15:51 +00003494 RetTy DerivedZeroInitialization(const Expr *E) {
3495 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003496 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003497
Richard Smith17100ba2012-02-16 02:46:34 +00003498 // Check whether a conditional operator with a non-constant condition is a
3499 // potential constant expression. If neither arm is a potential constant
3500 // expression, then the conditional operator is not either.
3501 template<typename ConditionalOperator>
3502 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3503 assert(Info.CheckingPotentialConstantExpression);
3504
3505 // Speculatively evaluate both arms.
3506 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003507 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003508 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3509
3510 StmtVisitorTy::Visit(E->getFalseExpr());
3511 if (Diag.empty())
3512 return;
3513
3514 Diag.clear();
3515 StmtVisitorTy::Visit(E->getTrueExpr());
3516 if (Diag.empty())
3517 return;
3518 }
3519
3520 Error(E, diag::note_constexpr_conditional_never_const);
3521 }
3522
3523
3524 template<typename ConditionalOperator>
3525 bool HandleConditionalOperator(const ConditionalOperator *E) {
3526 bool BoolResult;
3527 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3528 if (Info.CheckingPotentialConstantExpression)
3529 CheckPotentialConstantConditional(E);
3530 return false;
3531 }
3532
3533 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3534 return StmtVisitorTy::Visit(EvalExpr);
3535 }
3536
Peter Collingbournee9200682011-05-13 03:29:01 +00003537protected:
3538 EvalInfo &Info;
3539 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3540 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3541
Richard Smith92b1ce02011-12-12 09:28:41 +00003542 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003543 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003544 }
3545
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003546 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3547
3548public:
3549 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3550
3551 EvalInfo &getEvalInfo() { return Info; }
3552
Richard Smithf57d8cb2011-12-09 22:58:01 +00003553 /// Report an evaluation error. This should only be called when an error is
3554 /// first discovered. When propagating an error, just return false.
3555 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003556 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003557 return false;
3558 }
3559 bool Error(const Expr *E) {
3560 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3561 }
3562
Peter Collingbournee9200682011-05-13 03:29:01 +00003563 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003564 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003565 }
3566 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003567 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003568 }
3569
3570 RetTy VisitParenExpr(const ParenExpr *E)
3571 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3572 RetTy VisitUnaryExtension(const UnaryOperator *E)
3573 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3574 RetTy VisitUnaryPlus(const UnaryOperator *E)
3575 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3576 RetTy VisitChooseExpr(const ChooseExpr *E)
3577 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3578 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3579 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003580 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3581 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003582 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3583 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003584 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3585 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003586 // We cannot create any objects for which cleanups are required, so there is
3587 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3588 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3589 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003590
Richard Smith6d6ecc32011-12-12 12:46:16 +00003591 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3592 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3593 return static_cast<Derived*>(this)->VisitCastExpr(E);
3594 }
3595 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3596 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3597 return static_cast<Derived*>(this)->VisitCastExpr(E);
3598 }
3599
Richard Smith027bf112011-11-17 22:56:20 +00003600 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3601 switch (E->getOpcode()) {
3602 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003603 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003604
3605 case BO_Comma:
3606 VisitIgnoredValue(E->getLHS());
3607 return StmtVisitorTy::Visit(E->getRHS());
3608
3609 case BO_PtrMemD:
3610 case BO_PtrMemI: {
3611 LValue Obj;
3612 if (!HandleMemberPointerAccess(Info, E, Obj))
3613 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003614 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003615 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003616 return false;
3617 return DerivedSuccess(Result, E);
3618 }
3619 }
3620 }
3621
Peter Collingbournee9200682011-05-13 03:29:01 +00003622 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003623 // Evaluate and cache the common expression. We treat it as a temporary,
3624 // even though it's not quite the same thing.
3625 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3626 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003627 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003628
Richard Smith17100ba2012-02-16 02:46:34 +00003629 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003630 }
3631
3632 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003633 bool IsBcpCall = false;
3634 // If the condition (ignoring parens) is a __builtin_constant_p call,
3635 // the result is a constant expression if it can be folded without
3636 // side-effects. This is an important GNU extension. See GCC PR38377
3637 // for discussion.
3638 if (const CallExpr *CallCE =
3639 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3640 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3641 IsBcpCall = true;
3642
3643 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3644 // constant expression; we can't check whether it's potentially foldable.
3645 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3646 return false;
3647
3648 FoldConstant Fold(Info);
3649
Richard Smith17100ba2012-02-16 02:46:34 +00003650 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003651 return false;
3652
3653 if (IsBcpCall)
3654 Fold.Fold(Info);
3655
3656 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003657 }
3658
3659 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003660 APValue &Value = Info.CurrentCall->Temporaries[E];
3661 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003662 const Expr *Source = E->getSourceExpr();
3663 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003664 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003665 if (Source == E) { // sanity checking.
3666 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003667 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003668 }
3669 return StmtVisitorTy::Visit(Source);
3670 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003671 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003672 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003673
Richard Smith254a73d2011-10-28 22:34:42 +00003674 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003675 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003676 QualType CalleeType = Callee->getType();
3677
Richard Smith254a73d2011-10-28 22:34:42 +00003678 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003679 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003680 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003681 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003682
Richard Smithe97cbd72011-11-11 04:05:33 +00003683 // Extract function decl and 'this' pointer from the callee.
3684 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003685 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3687 // Explicit bound member calls, such as x.f() or p->g();
3688 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003689 return false;
3690 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003691 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003692 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003693 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3694 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003695 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3696 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003697 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003698 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003699 return Error(Callee);
3700
3701 FD = dyn_cast<FunctionDecl>(Member);
3702 if (!FD)
3703 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003704 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003705 LValue Call;
3706 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003707 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003708
Richard Smitha8105bc2012-01-06 16:39:00 +00003709 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003710 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003711 FD = dyn_cast_or_null<FunctionDecl>(
3712 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003713 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003714 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003715
3716 // Overloaded operator calls to member functions are represented as normal
3717 // calls with '*this' as the first argument.
3718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3719 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003720 // FIXME: When selecting an implicit conversion for an overloaded
3721 // operator delete, we sometimes try to evaluate calls to conversion
3722 // operators without a 'this' parameter!
3723 if (Args.empty())
3724 return Error(E);
3725
Richard Smithe97cbd72011-11-11 04:05:33 +00003726 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3727 return false;
3728 This = &ThisVal;
3729 Args = Args.slice(1);
3730 }
3731
3732 // Don't call function pointers which have been cast to some other type.
3733 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003734 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003735 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003736 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003737
Richard Smith47b34932012-02-01 02:39:43 +00003738 if (This && !This->checkSubobject(Info, E, CSK_This))
3739 return false;
3740
Richard Smith3607ffe2012-02-13 03:54:03 +00003741 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3742 // calls to such functions in constant expressions.
3743 if (This && !HasQualifier &&
3744 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3745 return Error(E, diag::note_constexpr_virtual_call);
3746
Richard Smith357362d2011-12-13 06:39:58 +00003747 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003748 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003749 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003750
Richard Smith357362d2011-12-13 06:39:58 +00003751 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003752 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3753 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003754 return false;
3755
Richard Smithb228a862012-02-15 02:18:13 +00003756 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003757 }
3758
Richard Smith11562c52011-10-28 17:51:58 +00003759 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3760 return StmtVisitorTy::Visit(E->getInitializer());
3761 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003762 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003763 if (E->getNumInits() == 0)
3764 return DerivedZeroInitialization(E);
3765 if (E->getNumInits() == 1)
3766 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003767 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003768 }
3769 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003770 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003771 }
3772 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003773 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003774 }
Richard Smith027bf112011-11-17 22:56:20 +00003775 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003776 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003777 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003778
Richard Smithd62306a2011-11-10 06:34:14 +00003779 /// A member expression where the object is a prvalue is itself a prvalue.
3780 RetTy VisitMemberExpr(const MemberExpr *E) {
3781 assert(!E->isArrow() && "missing call to bound member function?");
3782
Richard Smith2e312c82012-03-03 22:46:17 +00003783 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003784 if (!Evaluate(Val, Info, E->getBase()))
3785 return false;
3786
3787 QualType BaseTy = E->getBase()->getType();
3788
3789 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003790 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003791 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003792 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003793 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3794
Richard Smith3229b742013-05-05 21:17:10 +00003795 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003796 SubobjectDesignator Designator(BaseTy);
3797 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003798
Richard Smith3229b742013-05-05 21:17:10 +00003799 APValue Result;
3800 return extractSubobject(Info, E, Obj, Designator, Result) &&
3801 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003802 }
3803
Richard Smith11562c52011-10-28 17:51:58 +00003804 RetTy VisitCastExpr(const CastExpr *E) {
3805 switch (E->getCastKind()) {
3806 default:
3807 break;
3808
Richard Smitha23ab512013-05-23 00:30:41 +00003809 case CK_AtomicToNonAtomic: {
3810 APValue AtomicVal;
3811 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3812 return false;
3813 return DerivedSuccess(AtomicVal, E);
3814 }
3815
Richard Smith11562c52011-10-28 17:51:58 +00003816 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003817 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003818 return StmtVisitorTy::Visit(E->getSubExpr());
3819
3820 case CK_LValueToRValue: {
3821 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3823 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003824 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003825 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003826 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003827 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003828 return false;
3829 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003830 }
3831 }
3832
Richard Smithf57d8cb2011-12-09 22:58:01 +00003833 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003834 }
3835
Richard Smith243ef902013-05-05 23:31:59 +00003836 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3837 return VisitUnaryPostIncDec(UO);
3838 }
3839 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3840 return VisitUnaryPostIncDec(UO);
3841 }
3842 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3843 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3844 return Error(UO);
3845
3846 LValue LVal;
3847 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3848 return false;
3849 APValue RVal;
3850 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3851 UO->isIncrementOp(), &RVal))
3852 return false;
3853 return DerivedSuccess(RVal, UO);
3854 }
3855
Richard Smith4a678122011-10-24 18:44:57 +00003856 /// Visit a value which is evaluated, but whose value is ignored.
3857 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003858 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003859 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003860};
3861
3862}
3863
3864//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003865// Common base class for lvalue and temporary evaluation.
3866//===----------------------------------------------------------------------===//
3867namespace {
3868template<class Derived>
3869class LValueExprEvaluatorBase
3870 : public ExprEvaluatorBase<Derived, bool> {
3871protected:
3872 LValue &Result;
3873 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3874 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3875
3876 bool Success(APValue::LValueBase B) {
3877 Result.set(B);
3878 return true;
3879 }
3880
3881public:
3882 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3883 ExprEvaluatorBaseTy(Info), Result(Result) {}
3884
Richard Smith2e312c82012-03-03 22:46:17 +00003885 bool Success(const APValue &V, const Expr *E) {
3886 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003887 return true;
3888 }
Richard Smith027bf112011-11-17 22:56:20 +00003889
Richard Smith027bf112011-11-17 22:56:20 +00003890 bool VisitMemberExpr(const MemberExpr *E) {
3891 // Handle non-static data members.
3892 QualType BaseTy;
3893 if (E->isArrow()) {
3894 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3895 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003896 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003897 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003898 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003899 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3900 return false;
3901 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003902 } else {
3903 if (!this->Visit(E->getBase()))
3904 return false;
3905 BaseTy = E->getBase()->getType();
3906 }
Richard Smith027bf112011-11-17 22:56:20 +00003907
Richard Smith1b78b3d2012-01-25 22:15:11 +00003908 const ValueDecl *MD = E->getMemberDecl();
3909 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3910 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3911 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3912 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003913 if (!HandleLValueMember(this->Info, E, Result, FD))
3914 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003915 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003916 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3917 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003918 } else
3919 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003920
Richard Smith1b78b3d2012-01-25 22:15:11 +00003921 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003922 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003923 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003924 RefValue))
3925 return false;
3926 return Success(RefValue, E);
3927 }
3928 return true;
3929 }
3930
3931 bool VisitBinaryOperator(const BinaryOperator *E) {
3932 switch (E->getOpcode()) {
3933 default:
3934 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3935
3936 case BO_PtrMemD:
3937 case BO_PtrMemI:
3938 return HandleMemberPointerAccess(this->Info, E, Result);
3939 }
3940 }
3941
3942 bool VisitCastExpr(const CastExpr *E) {
3943 switch (E->getCastKind()) {
3944 default:
3945 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3946
3947 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00003948 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00003949 if (!this->Visit(E->getSubExpr()))
3950 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003951
3952 // Now figure out the necessary offset to add to the base LV to get from
3953 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00003954 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
3955 Result);
Richard Smith027bf112011-11-17 22:56:20 +00003956 }
3957 }
3958};
3959}
3960
3961//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003962// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003963//
3964// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3965// function designators (in C), decl references to void objects (in C), and
3966// temporaries (if building with -Wno-address-of-temporary).
3967//
3968// LValue evaluation produces values comprising a base expression of one of the
3969// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003970// - Declarations
3971// * VarDecl
3972// * FunctionDecl
3973// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003974// * CompoundLiteralExpr in C
3975// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003976// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003977// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003978// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003979// * ObjCEncodeExpr
3980// * AddrLabelExpr
3981// * BlockExpr
3982// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003983// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00003984// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00003985// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00003986// was evaluated, for cases where the MaterializeTemporaryExpr is missing
3987// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00003988// * A MaterializeTemporaryExpr that has static storage duration, with no
3989// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00003990// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003991//===----------------------------------------------------------------------===//
3992namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003993class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003994 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003995public:
Richard Smith027bf112011-11-17 22:56:20 +00003996 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3997 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003998
Richard Smith11562c52011-10-28 17:51:58 +00003999 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004000 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004001
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 bool VisitDeclRefExpr(const DeclRefExpr *E);
4003 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004004 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004005 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4006 bool VisitMemberExpr(const MemberExpr *E);
4007 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4008 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004009 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004010 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004011 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4012 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004013 bool VisitUnaryReal(const UnaryOperator *E);
4014 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004015 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4016 return VisitUnaryPreIncDec(UO);
4017 }
4018 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4019 return VisitUnaryPreIncDec(UO);
4020 }
Richard Smith3229b742013-05-05 21:17:10 +00004021 bool VisitBinAssign(const BinaryOperator *BO);
4022 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004023
Peter Collingbournee9200682011-05-13 03:29:01 +00004024 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004025 switch (E->getCastKind()) {
4026 default:
Richard Smith027bf112011-11-17 22:56:20 +00004027 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004028
Eli Friedmance3e02a2011-10-11 00:13:24 +00004029 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004030 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004031 if (!Visit(E->getSubExpr()))
4032 return false;
4033 Result.Designator.setInvalid();
4034 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004035
Richard Smith027bf112011-11-17 22:56:20 +00004036 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004037 if (!Visit(E->getSubExpr()))
4038 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004039 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004040 }
4041 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004042};
4043} // end anonymous namespace
4044
Richard Smith11562c52011-10-28 17:51:58 +00004045/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004046/// expressions which are not glvalues, in two cases:
4047/// * function designators in C, and
4048/// * "extern void" objects
4049static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4050 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4051 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004052 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004053}
4054
Peter Collingbournee9200682011-05-13 03:29:01 +00004055bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004056 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4057 return Success(FD);
4058 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004059 return VisitVarDecl(E, VD);
4060 return Error(E);
4061}
Richard Smith733237d2011-10-24 23:14:33 +00004062
Richard Smith11562c52011-10-28 17:51:58 +00004063bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004064 CallStackFrame *Frame = 0;
4065 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4066 Frame = Info.CurrentCall;
4067
Richard Smithfec09922011-11-01 16:57:24 +00004068 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004069 if (Frame) {
4070 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004071 return true;
4072 }
Richard Smithce40ad62011-11-12 22:28:03 +00004073 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004074 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004075
Richard Smith3229b742013-05-05 21:17:10 +00004076 APValue *V;
4077 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004078 return false;
Richard Smith3229b742013-05-05 21:17:10 +00004079 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004080}
4081
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004082bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4083 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004084 // Walk through the expression to find the materialized temporary itself.
4085 SmallVector<const Expr *, 2> CommaLHSs;
4086 SmallVector<SubobjectAdjustment, 2> Adjustments;
4087 const Expr *Inner = E->GetTemporaryExpr()->
4088 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004089
Richard Smith84401042013-06-03 05:03:02 +00004090 // If we passed any comma operators, evaluate their LHSs.
4091 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4092 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4093 return false;
4094
Richard Smithe6c01442013-06-05 00:46:14 +00004095 // A materialized temporary with static storage duration can appear within the
4096 // result of a constant expression evaluation, so we need to preserve its
4097 // value for use outside this evaluation.
4098 APValue *Value;
4099 if (E->getStorageDuration() == SD_Static) {
4100 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004101 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004102 Result.set(E);
4103 } else {
4104 Value = &Info.CurrentCall->Temporaries[E];
4105 Result.set(E, Info.CurrentCall->Index);
4106 }
4107
Richard Smithea4ad5d2013-06-06 08:19:16 +00004108 QualType Type = Inner->getType();
4109
Richard Smith84401042013-06-03 05:03:02 +00004110 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004111 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4112 (E->getStorageDuration() == SD_Static &&
4113 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4114 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004115 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004116 }
Richard Smith84401042013-06-03 05:03:02 +00004117
4118 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004119 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4120 --I;
4121 switch (Adjustments[I].Kind) {
4122 case SubobjectAdjustment::DerivedToBaseAdjustment:
4123 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4124 Type, Result))
4125 return false;
4126 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4127 break;
4128
4129 case SubobjectAdjustment::FieldAdjustment:
4130 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4131 return false;
4132 Type = Adjustments[I].Field->getType();
4133 break;
4134
4135 case SubobjectAdjustment::MemberPointerAdjustment:
4136 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4137 Adjustments[I].Ptr.RHS))
4138 return false;
4139 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4140 break;
4141 }
4142 }
4143
4144 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004145}
4146
Peter Collingbournee9200682011-05-13 03:29:01 +00004147bool
4148LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004149 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4150 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4151 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004152 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004153}
4154
Richard Smith6e525142011-12-27 12:18:28 +00004155bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004156 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004157 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004158
4159 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4160 << E->getExprOperand()->getType()
4161 << E->getExprOperand()->getSourceRange();
4162 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004163}
4164
Francois Pichet0066db92012-04-16 04:08:35 +00004165bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4166 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004167}
Francois Pichet0066db92012-04-16 04:08:35 +00004168
Peter Collingbournee9200682011-05-13 03:29:01 +00004169bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004170 // Handle static data members.
4171 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4172 VisitIgnoredValue(E->getBase());
4173 return VisitVarDecl(E, VD);
4174 }
4175
Richard Smith254a73d2011-10-28 22:34:42 +00004176 // Handle static member functions.
4177 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4178 if (MD->isStatic()) {
4179 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004180 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004181 }
4182 }
4183
Richard Smithd62306a2011-11-10 06:34:14 +00004184 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004185 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004186}
4187
Peter Collingbournee9200682011-05-13 03:29:01 +00004188bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004189 // FIXME: Deal with vectors as array subscript bases.
4190 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004192
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004193 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004194 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004195
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004196 APSInt Index;
4197 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004198 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004199
Richard Smith861b5b52013-05-07 23:34:45 +00004200 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4201 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004202}
Eli Friedman9a156e52008-11-12 09:44:48 +00004203
Peter Collingbournee9200682011-05-13 03:29:01 +00004204bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004205 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004206}
4207
Richard Smith66c96992012-02-18 22:04:06 +00004208bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4209 if (!Visit(E->getSubExpr()))
4210 return false;
4211 // __real is a no-op on scalar lvalues.
4212 if (E->getSubExpr()->getType()->isAnyComplexType())
4213 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4214 return true;
4215}
4216
4217bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4218 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4219 "lvalue __imag__ on scalar?");
4220 if (!Visit(E->getSubExpr()))
4221 return false;
4222 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4223 return true;
4224}
4225
Richard Smith243ef902013-05-05 23:31:59 +00004226bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4227 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004228 return Error(UO);
4229
4230 if (!this->Visit(UO->getSubExpr()))
4231 return false;
4232
Richard Smith243ef902013-05-05 23:31:59 +00004233 return handleIncDec(
4234 this->Info, UO, Result, UO->getSubExpr()->getType(),
4235 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004236}
4237
4238bool LValueExprEvaluator::VisitCompoundAssignOperator(
4239 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004240 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004241 return Error(CAO);
4242
Richard Smith3229b742013-05-05 21:17:10 +00004243 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004244
4245 // The overall lvalue result is the result of evaluating the LHS.
4246 if (!this->Visit(CAO->getLHS())) {
4247 if (Info.keepEvaluatingAfterFailure())
4248 Evaluate(RHS, this->Info, CAO->getRHS());
4249 return false;
4250 }
4251
Richard Smith3229b742013-05-05 21:17:10 +00004252 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4253 return false;
4254
Richard Smith43e77732013-05-07 04:50:00 +00004255 return handleCompoundAssignment(
4256 this->Info, CAO,
4257 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4258 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004259}
4260
4261bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004262 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4263 return Error(E);
4264
Richard Smith3229b742013-05-05 21:17:10 +00004265 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004266
4267 if (!this->Visit(E->getLHS())) {
4268 if (Info.keepEvaluatingAfterFailure())
4269 Evaluate(NewVal, this->Info, E->getRHS());
4270 return false;
4271 }
4272
Richard Smith3229b742013-05-05 21:17:10 +00004273 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4274 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004275
4276 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004277 NewVal);
4278}
4279
Eli Friedman9a156e52008-11-12 09:44:48 +00004280//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004281// Pointer Evaluation
4282//===----------------------------------------------------------------------===//
4283
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004284namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004285class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004286 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004287 LValue &Result;
4288
Peter Collingbournee9200682011-05-13 03:29:01 +00004289 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004290 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004291 return true;
4292 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004293public:
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall45d55e42010-05-07 21:00:08 +00004295 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004296 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004297
Richard Smith2e312c82012-03-03 22:46:17 +00004298 bool Success(const APValue &V, const Expr *E) {
4299 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004300 return true;
4301 }
Richard Smithfddd3842011-12-30 21:15:51 +00004302 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004303 return Success((Expr*)0);
4304 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004305
John McCall45d55e42010-05-07 21:00:08 +00004306 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004307 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004308 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004309 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004310 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004311 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004312 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004313 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004314 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004315 bool VisitCallExpr(const CallExpr *E);
4316 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004317 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004318 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004319 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004320 }
Richard Smithd62306a2011-11-10 06:34:14 +00004321 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004322 // Can't look at 'this' when checking a potential constant expression.
4323 if (Info.CheckingPotentialConstantExpression)
4324 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004325 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004326 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004327 Result = *Info.CurrentCall->This;
4328 return true;
4329 }
John McCallc07a0c72011-02-17 10:25:35 +00004330
Eli Friedman449fe542009-03-23 04:56:01 +00004331 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004332};
Chris Lattner05706e882008-07-11 18:11:29 +00004333} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004334
John McCall45d55e42010-05-07 21:00:08 +00004335static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004336 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004337 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004338}
4339
John McCall45d55e42010-05-07 21:00:08 +00004340bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004341 if (E->getOpcode() != BO_Add &&
4342 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004343 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004344
Chris Lattner05706e882008-07-11 18:11:29 +00004345 const Expr *PExp = E->getLHS();
4346 const Expr *IExp = E->getRHS();
4347 if (IExp->getType()->isPointerType())
4348 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004349
Richard Smith253c2a32012-01-27 01:14:48 +00004350 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4351 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004352 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004353
John McCall45d55e42010-05-07 21:00:08 +00004354 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004355 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004356 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004357
4358 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004359 if (E->getOpcode() == BO_Sub)
4360 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004361
Ted Kremenek28831752012-08-23 20:46:57 +00004362 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004363 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4364 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004365}
Eli Friedman9a156e52008-11-12 09:44:48 +00004366
John McCall45d55e42010-05-07 21:00:08 +00004367bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4368 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004369}
Mike Stump11289f42009-09-09 15:08:12 +00004370
Peter Collingbournee9200682011-05-13 03:29:01 +00004371bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4372 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004373
Eli Friedman847a2bc2009-12-27 05:43:15 +00004374 switch (E->getCastKind()) {
4375 default:
4376 break;
4377
John McCalle3027922010-08-25 11:45:40 +00004378 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004379 case CK_CPointerToObjCPointerCast:
4380 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004381 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004382 if (!Visit(SubExpr))
4383 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004384 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4385 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4386 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004387 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004388 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004389 if (SubExpr->getType()->isVoidPointerType())
4390 CCEDiag(E, diag::note_constexpr_invalid_cast)
4391 << 3 << SubExpr->getType();
4392 else
4393 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4394 }
Richard Smith96e0c102011-11-04 02:25:55 +00004395 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004396
Anders Carlsson18275092010-10-31 20:41:46 +00004397 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004398 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004399 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004400 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004401 if (!Result.Base && Result.Offset.isZero())
4402 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004403
Richard Smithd62306a2011-11-10 06:34:14 +00004404 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004405 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004406 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4407 castAs<PointerType>()->getPointeeType(),
4408 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004409
Richard Smith027bf112011-11-17 22:56:20 +00004410 case CK_BaseToDerived:
4411 if (!Visit(E->getSubExpr()))
4412 return false;
4413 if (!Result.Base && Result.Offset.isZero())
4414 return true;
4415 return HandleBaseToDerivedCast(Info, E, Result);
4416
Richard Smith0b0a0b62011-10-29 20:57:55 +00004417 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004418 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004419 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004420
John McCalle3027922010-08-25 11:45:40 +00004421 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004422 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4423
Richard Smith2e312c82012-03-03 22:46:17 +00004424 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004425 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004426 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004427
John McCall45d55e42010-05-07 21:00:08 +00004428 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004429 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4430 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004431 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004432 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004433 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004434 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004435 return true;
4436 } else {
4437 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004438 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004439 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004440 }
4441 }
John McCalle3027922010-08-25 11:45:40 +00004442 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004443 if (SubExpr->isGLValue()) {
4444 if (!EvaluateLValue(SubExpr, Result, Info))
4445 return false;
4446 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004447 Result.set(SubExpr, Info.CurrentCall->Index);
4448 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4449 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004450 return false;
4451 }
Richard Smith96e0c102011-11-04 02:25:55 +00004452 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004453 if (const ConstantArrayType *CAT
4454 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4455 Result.addArray(Info, E, CAT);
4456 else
4457 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004458 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004459
John McCalle3027922010-08-25 11:45:40 +00004460 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004461 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004462 }
4463
Richard Smith11562c52011-10-28 17:51:58 +00004464 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004465}
Chris Lattner05706e882008-07-11 18:11:29 +00004466
Peter Collingbournee9200682011-05-13 03:29:01 +00004467bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004468 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004469 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004470
Peter Collingbournee9200682011-05-13 03:29:01 +00004471 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004472}
Chris Lattner05706e882008-07-11 18:11:29 +00004473
4474//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004475// Member Pointer Evaluation
4476//===----------------------------------------------------------------------===//
4477
4478namespace {
4479class MemberPointerExprEvaluator
4480 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4481 MemberPtr &Result;
4482
4483 bool Success(const ValueDecl *D) {
4484 Result = MemberPtr(D);
4485 return true;
4486 }
4487public:
4488
4489 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4490 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4491
Richard Smith2e312c82012-03-03 22:46:17 +00004492 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004493 Result.setFrom(V);
4494 return true;
4495 }
Richard Smithfddd3842011-12-30 21:15:51 +00004496 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004497 return Success((const ValueDecl*)0);
4498 }
4499
4500 bool VisitCastExpr(const CastExpr *E);
4501 bool VisitUnaryAddrOf(const UnaryOperator *E);
4502};
4503} // end anonymous namespace
4504
4505static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4506 EvalInfo &Info) {
4507 assert(E->isRValue() && E->getType()->isMemberPointerType());
4508 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4509}
4510
4511bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4512 switch (E->getCastKind()) {
4513 default:
4514 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4515
4516 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004517 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004518 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004519
4520 case CK_BaseToDerivedMemberPointer: {
4521 if (!Visit(E->getSubExpr()))
4522 return false;
4523 if (E->path_empty())
4524 return true;
4525 // Base-to-derived member pointer casts store the path in derived-to-base
4526 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4527 // the wrong end of the derived->base arc, so stagger the path by one class.
4528 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4529 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4530 PathI != PathE; ++PathI) {
4531 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4532 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4533 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004534 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004535 }
4536 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4537 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004538 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004539 return true;
4540 }
4541
4542 case CK_DerivedToBaseMemberPointer:
4543 if (!Visit(E->getSubExpr()))
4544 return false;
4545 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4546 PathE = E->path_end(); PathI != PathE; ++PathI) {
4547 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4548 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4549 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004550 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004551 }
4552 return true;
4553 }
4554}
4555
4556bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4557 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4558 // member can be formed.
4559 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4560}
4561
4562//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004563// Record Evaluation
4564//===----------------------------------------------------------------------===//
4565
4566namespace {
4567 class RecordExprEvaluator
4568 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4569 const LValue &This;
4570 APValue &Result;
4571 public:
4572
4573 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4574 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4575
Richard Smith2e312c82012-03-03 22:46:17 +00004576 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004577 Result = V;
4578 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004579 }
Richard Smithfddd3842011-12-30 21:15:51 +00004580 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004581
Richard Smithe97cbd72011-11-11 04:05:33 +00004582 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004583 bool VisitInitListExpr(const InitListExpr *E);
4584 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004585 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004586 };
4587}
4588
Richard Smithfddd3842011-12-30 21:15:51 +00004589/// Perform zero-initialization on an object of non-union class type.
4590/// C++11 [dcl.init]p5:
4591/// To zero-initialize an object or reference of type T means:
4592/// [...]
4593/// -- if T is a (possibly cv-qualified) non-union class type,
4594/// each non-static data member and each base-class subobject is
4595/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004596static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4597 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004598 const LValue &This, APValue &Result) {
4599 assert(!RD->isUnion() && "Expected non-union class type");
4600 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4601 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4602 std::distance(RD->field_begin(), RD->field_end()));
4603
John McCalld7bca762012-05-01 00:38:49 +00004604 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004605 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4606
4607 if (CD) {
4608 unsigned Index = 0;
4609 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004610 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004611 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4612 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004613 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4614 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004615 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004616 Result.getStructBase(Index)))
4617 return false;
4618 }
4619 }
4620
Richard Smitha8105bc2012-01-06 16:39:00 +00004621 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4622 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004623 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004624 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004625 continue;
4626
4627 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004628 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004629 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004630
David Blaikie2d7c57e2012-04-30 02:36:29 +00004631 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004632 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004633 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004634 return false;
4635 }
4636
4637 return true;
4638}
4639
4640bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4641 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004642 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004643 if (RD->isUnion()) {
4644 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4645 // object's first non-static named data member is zero-initialized
4646 RecordDecl::field_iterator I = RD->field_begin();
4647 if (I == RD->field_end()) {
4648 Result = APValue((const FieldDecl*)0);
4649 return true;
4650 }
4651
4652 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004653 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004654 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004655 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004656 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004657 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004658 }
4659
Richard Smith5d108602012-02-17 00:44:16 +00004660 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004661 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004662 return false;
4663 }
4664
Richard Smitha8105bc2012-01-06 16:39:00 +00004665 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004666}
4667
Richard Smithe97cbd72011-11-11 04:05:33 +00004668bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4669 switch (E->getCastKind()) {
4670 default:
4671 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4672
4673 case CK_ConstructorConversion:
4674 return Visit(E->getSubExpr());
4675
4676 case CK_DerivedToBase:
4677 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004678 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004679 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004681 if (!DerivedObject.isStruct())
4682 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004683
4684 // Derived-to-base rvalue conversion: just slice off the derived part.
4685 APValue *Value = &DerivedObject;
4686 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4687 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4688 PathE = E->path_end(); PathI != PathE; ++PathI) {
4689 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4690 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4691 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4692 RD = Base;
4693 }
4694 Result = *Value;
4695 return true;
4696 }
4697 }
4698}
4699
Richard Smithd62306a2011-11-10 06:34:14 +00004700bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4701 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004702 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004703 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4704
4705 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004706 const FieldDecl *Field = E->getInitializedFieldInUnion();
4707 Result = APValue(Field);
4708 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004709 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004710
4711 // If the initializer list for a union does not contain any elements, the
4712 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004713 // FIXME: The element should be initialized from an initializer list.
4714 // Is this difference ever observable for initializer lists which
4715 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004716 ImplicitValueInitExpr VIE(Field->getType());
4717 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4718
Richard Smithd62306a2011-11-10 06:34:14 +00004719 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004720 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4721 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004722
4723 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4724 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4725 isa<CXXDefaultInitExpr>(InitExpr));
4726
Richard Smithb228a862012-02-15 02:18:13 +00004727 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004728 }
4729
4730 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4731 "initializer list for class with base classes");
4732 Result = APValue(APValue::UninitStruct(), 0,
4733 std::distance(RD->field_begin(), RD->field_end()));
4734 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004735 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004736 for (RecordDecl::field_iterator Field = RD->field_begin(),
4737 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4738 // Anonymous bit-fields are not considered members of the class for
4739 // purposes of aggregate initialization.
4740 if (Field->isUnnamedBitfield())
4741 continue;
4742
4743 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004744
Richard Smith253c2a32012-01-27 01:14:48 +00004745 bool HaveInit = ElementNo < E->getNumInits();
4746
4747 // FIXME: Diagnostics here should point to the end of the initializer
4748 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004749 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004750 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004751 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004752
4753 // Perform an implicit value-initialization for members beyond the end of
4754 // the initializer list.
4755 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004756 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004757
Richard Smith852c9db2013-04-20 22:23:05 +00004758 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4759 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4760 isa<CXXDefaultInitExpr>(Init));
4761
4762 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4763 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004764 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004765 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004766 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004767 }
4768 }
4769
Richard Smith253c2a32012-01-27 01:14:48 +00004770 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004771}
4772
4773bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4774 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004775 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4776
Richard Smithfddd3842011-12-30 21:15:51 +00004777 bool ZeroInit = E->requiresZeroInitialization();
4778 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004779 // If we've already performed zero-initialization, we're already done.
4780 if (!Result.isUninit())
4781 return true;
4782
Richard Smithfddd3842011-12-30 21:15:51 +00004783 if (ZeroInit)
4784 return ZeroInitialization(E);
4785
Richard Smithcc36f692011-12-22 02:22:31 +00004786 const CXXRecordDecl *RD = FD->getParent();
4787 if (RD->isUnion())
4788 Result = APValue((FieldDecl*)0);
4789 else
4790 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4791 std::distance(RD->field_begin(), RD->field_end()));
4792 return true;
4793 }
4794
Richard Smithd62306a2011-11-10 06:34:14 +00004795 const FunctionDecl *Definition = 0;
4796 FD->getBody(Definition);
4797
Richard Smith357362d2011-12-13 06:39:58 +00004798 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4799 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004800
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004801 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004802 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004803 if (const MaterializeTemporaryExpr *ME
4804 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4805 return Visit(ME->GetTemporaryExpr());
4806
Richard Smithfddd3842011-12-30 21:15:51 +00004807 if (ZeroInit && !ZeroInitialization(E))
4808 return false;
4809
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004810 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004811 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004812 cast<CXXConstructorDecl>(Definition), Info,
4813 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004814}
4815
Richard Smithcc1b96d2013-06-12 22:31:48 +00004816bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
4817 const CXXStdInitializerListExpr *E) {
4818 const ConstantArrayType *ArrayType =
4819 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
4820
4821 LValue Array;
4822 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
4823 return false;
4824
4825 // Get a pointer to the first element of the array.
4826 Array.addArray(Info, E, ArrayType);
4827
4828 // FIXME: Perform the checks on the field types in SemaInit.
4829 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
4830 RecordDecl::field_iterator Field = Record->field_begin();
4831 if (Field == Record->field_end())
4832 return Error(E);
4833
4834 // Start pointer.
4835 if (!Field->getType()->isPointerType() ||
4836 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4837 ArrayType->getElementType()))
4838 return Error(E);
4839
4840 // FIXME: What if the initializer_list type has base classes, etc?
4841 Result = APValue(APValue::UninitStruct(), 0, 2);
4842 Array.moveInto(Result.getStructField(0));
4843
4844 if (++Field == Record->field_end())
4845 return Error(E);
4846
4847 if (Field->getType()->isPointerType() &&
4848 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4849 ArrayType->getElementType())) {
4850 // End pointer.
4851 if (!HandleLValueArrayAdjustment(Info, E, Array,
4852 ArrayType->getElementType(),
4853 ArrayType->getSize().getZExtValue()))
4854 return false;
4855 Array.moveInto(Result.getStructField(1));
4856 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
4857 // Length.
4858 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
4859 else
4860 return Error(E);
4861
4862 if (++Field != Record->field_end())
4863 return Error(E);
4864
4865 return true;
4866}
4867
Richard Smithd62306a2011-11-10 06:34:14 +00004868static bool EvaluateRecord(const Expr *E, const LValue &This,
4869 APValue &Result, EvalInfo &Info) {
4870 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004871 "can't evaluate expression as a record rvalue");
4872 return RecordExprEvaluator(Info, This, Result).Visit(E);
4873}
4874
4875//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004876// Temporary Evaluation
4877//
4878// Temporaries are represented in the AST as rvalues, but generally behave like
4879// lvalues. The full-object of which the temporary is a subobject is implicitly
4880// materialized so that a reference can bind to it.
4881//===----------------------------------------------------------------------===//
4882namespace {
4883class TemporaryExprEvaluator
4884 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4885public:
4886 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4887 LValueExprEvaluatorBaseTy(Info, Result) {}
4888
4889 /// Visit an expression which constructs the value of this temporary.
4890 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004891 Result.set(E, Info.CurrentCall->Index);
4892 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004893 }
4894
4895 bool VisitCastExpr(const CastExpr *E) {
4896 switch (E->getCastKind()) {
4897 default:
4898 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4899
4900 case CK_ConstructorConversion:
4901 return VisitConstructExpr(E->getSubExpr());
4902 }
4903 }
4904 bool VisitInitListExpr(const InitListExpr *E) {
4905 return VisitConstructExpr(E);
4906 }
4907 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4908 return VisitConstructExpr(E);
4909 }
4910 bool VisitCallExpr(const CallExpr *E) {
4911 return VisitConstructExpr(E);
4912 }
4913};
4914} // end anonymous namespace
4915
4916/// Evaluate an expression of record type as a temporary.
4917static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004918 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004919 return TemporaryExprEvaluator(Info, Result).Visit(E);
4920}
4921
4922//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004923// Vector Evaluation
4924//===----------------------------------------------------------------------===//
4925
4926namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004927 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004928 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4929 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004930 public:
Mike Stump11289f42009-09-09 15:08:12 +00004931
Richard Smith2d406342011-10-22 21:10:00 +00004932 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4933 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004934
Richard Smith2d406342011-10-22 21:10:00 +00004935 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4936 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4937 // FIXME: remove this APValue copy.
4938 Result = APValue(V.data(), V.size());
4939 return true;
4940 }
Richard Smith2e312c82012-03-03 22:46:17 +00004941 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004942 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004943 Result = V;
4944 return true;
4945 }
Richard Smithfddd3842011-12-30 21:15:51 +00004946 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004947
Richard Smith2d406342011-10-22 21:10:00 +00004948 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004949 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004950 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004951 bool VisitInitListExpr(const InitListExpr *E);
4952 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004953 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004954 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004955 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004956 };
4957} // end anonymous namespace
4958
4959static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004960 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004961 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004962}
4963
Richard Smith2d406342011-10-22 21:10:00 +00004964bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4965 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004966 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004967
Richard Smith161f09a2011-12-06 22:44:34 +00004968 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004969 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004970
Eli Friedmanc757de22011-03-25 00:43:55 +00004971 switch (E->getCastKind()) {
4972 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004973 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004974 if (SETy->isIntegerType()) {
4975 APSInt IntResult;
4976 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004977 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004978 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004979 } else if (SETy->isRealFloatingType()) {
4980 APFloat F(0.0);
4981 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004982 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004983 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004984 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004985 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004986 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004987
4988 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004989 SmallVector<APValue, 4> Elts(NElts, Val);
4990 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004991 }
Eli Friedman803acb32011-12-22 03:51:45 +00004992 case CK_BitCast: {
4993 // Evaluate the operand into an APInt we can extract from.
4994 llvm::APInt SValInt;
4995 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4996 return false;
4997 // Extract the elements
4998 QualType EltTy = VTy->getElementType();
4999 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5000 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5001 SmallVector<APValue, 4> Elts;
5002 if (EltTy->isRealFloatingType()) {
5003 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005004 unsigned FloatEltSize = EltSize;
5005 if (&Sem == &APFloat::x87DoubleExtended)
5006 FloatEltSize = 80;
5007 for (unsigned i = 0; i < NElts; i++) {
5008 llvm::APInt Elt;
5009 if (BigEndian)
5010 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5011 else
5012 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005013 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005014 }
5015 } else if (EltTy->isIntegerType()) {
5016 for (unsigned i = 0; i < NElts; i++) {
5017 llvm::APInt Elt;
5018 if (BigEndian)
5019 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5020 else
5021 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5022 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5023 }
5024 } else {
5025 return Error(E);
5026 }
5027 return Success(Elts, E);
5028 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005029 default:
Richard Smith11562c52011-10-28 17:51:58 +00005030 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005031 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005032}
5033
Richard Smith2d406342011-10-22 21:10:00 +00005034bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005035VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005036 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005037 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005038 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005039
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005040 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005041 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005042
Eli Friedmanb9c71292012-01-03 23:24:20 +00005043 // The number of initializers can be less than the number of
5044 // vector elements. For OpenCL, this can be due to nested vector
5045 // initialization. For GCC compatibility, missing trailing elements
5046 // should be initialized with zeroes.
5047 unsigned CountInits = 0, CountElts = 0;
5048 while (CountElts < NumElements) {
5049 // Handle nested vector initialization.
5050 if (CountInits < NumInits
5051 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5052 APValue v;
5053 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5054 return Error(E);
5055 unsigned vlen = v.getVectorLength();
5056 for (unsigned j = 0; j < vlen; j++)
5057 Elements.push_back(v.getVectorElt(j));
5058 CountElts += vlen;
5059 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005060 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005061 if (CountInits < NumInits) {
5062 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005063 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005064 } else // trailing integer zero.
5065 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5066 Elements.push_back(APValue(sInt));
5067 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005068 } else {
5069 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005070 if (CountInits < NumInits) {
5071 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005072 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005073 } else // trailing float zero.
5074 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5075 Elements.push_back(APValue(f));
5076 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005077 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005078 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005079 }
Richard Smith2d406342011-10-22 21:10:00 +00005080 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005081}
5082
Richard Smith2d406342011-10-22 21:10:00 +00005083bool
Richard Smithfddd3842011-12-30 21:15:51 +00005084VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005085 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005086 QualType EltTy = VT->getElementType();
5087 APValue ZeroElement;
5088 if (EltTy->isIntegerType())
5089 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5090 else
5091 ZeroElement =
5092 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5093
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005094 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005095 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005096}
5097
Richard Smith2d406342011-10-22 21:10:00 +00005098bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005099 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005100 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005101}
5102
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005103//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005104// Array Evaluation
5105//===----------------------------------------------------------------------===//
5106
5107namespace {
5108 class ArrayExprEvaluator
5109 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005110 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005111 APValue &Result;
5112 public:
5113
Richard Smithd62306a2011-11-10 06:34:14 +00005114 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5115 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005116
5117 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005118 assert((V.isArray() || V.isLValue()) &&
5119 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005120 Result = V;
5121 return true;
5122 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005123
Richard Smithfddd3842011-12-30 21:15:51 +00005124 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005125 const ConstantArrayType *CAT =
5126 Info.Ctx.getAsConstantArrayType(E->getType());
5127 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005128 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005129
5130 Result = APValue(APValue::UninitArray(), 0,
5131 CAT->getSize().getZExtValue());
5132 if (!Result.hasArrayFiller()) return true;
5133
Richard Smithfddd3842011-12-30 21:15:51 +00005134 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005135 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005136 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005137 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005138 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005139 }
5140
Richard Smithf3e9e432011-11-07 09:22:26 +00005141 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005142 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005143 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5144 const LValue &Subobject,
5145 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005146 };
5147} // end anonymous namespace
5148
Richard Smithd62306a2011-11-10 06:34:14 +00005149static bool EvaluateArray(const Expr *E, const LValue &This,
5150 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005151 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005152 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005153}
5154
5155bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5156 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5157 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005158 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005159
Richard Smithca2cfbf2011-12-22 01:07:19 +00005160 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5161 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005162 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005163 LValue LV;
5164 if (!EvaluateLValue(E->getInit(0), LV, Info))
5165 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005166 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005167 LV.moveInto(Val);
5168 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005169 }
5170
Richard Smith253c2a32012-01-27 01:14:48 +00005171 bool Success = true;
5172
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005173 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5174 "zero-initialized array shouldn't have any initialized elts");
5175 APValue Filler;
5176 if (Result.isArray() && Result.hasArrayFiller())
5177 Filler = Result.getArrayFiller();
5178
Richard Smith9543c5e2013-04-22 14:44:29 +00005179 unsigned NumEltsToInit = E->getNumInits();
5180 unsigned NumElts = CAT->getSize().getZExtValue();
5181 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5182
5183 // If the initializer might depend on the array index, run it for each
5184 // array element. For now, just whitelist non-class value-initialization.
5185 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5186 NumEltsToInit = NumElts;
5187
5188 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005189
5190 // If the array was previously zero-initialized, preserve the
5191 // zero-initialized values.
5192 if (!Filler.isUninit()) {
5193 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5194 Result.getArrayInitializedElt(I) = Filler;
5195 if (Result.hasArrayFiller())
5196 Result.getArrayFiller() = Filler;
5197 }
5198
Richard Smithd62306a2011-11-10 06:34:14 +00005199 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005200 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005201 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5202 const Expr *Init =
5203 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005204 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005205 Info, Subobject, Init) ||
5206 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005207 CAT->getElementType(), 1)) {
5208 if (!Info.keepEvaluatingAfterFailure())
5209 return false;
5210 Success = false;
5211 }
Richard Smithd62306a2011-11-10 06:34:14 +00005212 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005213
Richard Smith9543c5e2013-04-22 14:44:29 +00005214 if (!Result.hasArrayFiller())
5215 return Success;
5216
5217 // If we get here, we have a trivial filler, which we can just evaluate
5218 // once and splat over the rest of the array elements.
5219 assert(FillerExpr && "no array filler for incomplete init list");
5220 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5221 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005222}
5223
Richard Smith027bf112011-11-17 22:56:20 +00005224bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005225 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5226}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005227
Richard Smith9543c5e2013-04-22 14:44:29 +00005228bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5229 const LValue &Subobject,
5230 APValue *Value,
5231 QualType Type) {
5232 bool HadZeroInit = !Value->isUninit();
5233
5234 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5235 unsigned N = CAT->getSize().getZExtValue();
5236
5237 // Preserve the array filler if we had prior zero-initialization.
5238 APValue Filler =
5239 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5240 : APValue();
5241
5242 *Value = APValue(APValue::UninitArray(), N, N);
5243
5244 if (HadZeroInit)
5245 for (unsigned I = 0; I != N; ++I)
5246 Value->getArrayInitializedElt(I) = Filler;
5247
5248 // Initialize the elements.
5249 LValue ArrayElt = Subobject;
5250 ArrayElt.addArray(Info, E, CAT);
5251 for (unsigned I = 0; I != N; ++I)
5252 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5253 CAT->getElementType()) ||
5254 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5255 CAT->getElementType(), 1))
5256 return false;
5257
5258 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005259 }
Richard Smith027bf112011-11-17 22:56:20 +00005260
Richard Smith9543c5e2013-04-22 14:44:29 +00005261 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005262 return Error(E);
5263
Richard Smith027bf112011-11-17 22:56:20 +00005264 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005265
Richard Smithfddd3842011-12-30 21:15:51 +00005266 bool ZeroInit = E->requiresZeroInitialization();
5267 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005268 if (HadZeroInit)
5269 return true;
5270
Richard Smithfddd3842011-12-30 21:15:51 +00005271 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005272 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005273 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005274 }
5275
Richard Smithcc36f692011-12-22 02:22:31 +00005276 const CXXRecordDecl *RD = FD->getParent();
5277 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005278 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005279 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005280 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005281 APValue(APValue::UninitStruct(), RD->getNumBases(),
5282 std::distance(RD->field_begin(), RD->field_end()));
5283 return true;
5284 }
5285
Richard Smith027bf112011-11-17 22:56:20 +00005286 const FunctionDecl *Definition = 0;
5287 FD->getBody(Definition);
5288
Richard Smith357362d2011-12-13 06:39:58 +00005289 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5290 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005291
Richard Smith9eae7232012-01-12 18:54:33 +00005292 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005293 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005294 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005295 return false;
5296 }
5297
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005298 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005299 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005300 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005301 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005302}
5303
Richard Smithf3e9e432011-11-07 09:22:26 +00005304//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005305// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005306//
5307// As a GNU extension, we support casting pointers to sufficiently-wide integer
5308// types and back in constant folding. Integer values are thus represented
5309// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005310//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005311
5312namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005313class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005314 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005315 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005316public:
Richard Smith2e312c82012-03-03 22:46:17 +00005317 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005318 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005319
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005320 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005321 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005322 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005323 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005324 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005325 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005326 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005327 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005328 return true;
5329 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005330 bool Success(const llvm::APSInt &SI, const Expr *E) {
5331 return Success(SI, E, Result);
5332 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005333
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005334 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005335 assert(E->getType()->isIntegralOrEnumerationType() &&
5336 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005337 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005338 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005339 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005340 Result.getInt().setIsUnsigned(
5341 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005342 return true;
5343 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005344 bool Success(const llvm::APInt &I, const Expr *E) {
5345 return Success(I, E, Result);
5346 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005347
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005348 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005349 assert(E->getType()->isIntegralOrEnumerationType() &&
5350 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005351 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005352 return true;
5353 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005354 bool Success(uint64_t Value, const Expr *E) {
5355 return Success(Value, E, Result);
5356 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005357
Ken Dyckdbc01912011-03-11 02:13:43 +00005358 bool Success(CharUnits Size, const Expr *E) {
5359 return Success(Size.getQuantity(), E);
5360 }
5361
Richard Smith2e312c82012-03-03 22:46:17 +00005362 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005363 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005364 Result = V;
5365 return true;
5366 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005367 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005368 }
Mike Stump11289f42009-09-09 15:08:12 +00005369
Richard Smithfddd3842011-12-30 21:15:51 +00005370 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005371
Peter Collingbournee9200682011-05-13 03:29:01 +00005372 //===--------------------------------------------------------------------===//
5373 // Visitor Methods
5374 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005375
Chris Lattner7174bf32008-07-12 00:38:25 +00005376 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005377 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005378 }
5379 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005380 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005381 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005382
5383 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5384 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005385 if (CheckReferencedDecl(E, E->getDecl()))
5386 return true;
5387
5388 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005389 }
5390 bool VisitMemberExpr(const MemberExpr *E) {
5391 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005392 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005393 return true;
5394 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005395
5396 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005397 }
5398
Peter Collingbournee9200682011-05-13 03:29:01 +00005399 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005400 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005401 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005402 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005403
Peter Collingbournee9200682011-05-13 03:29:01 +00005404 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005405 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005406
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005407 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005408 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005409 }
Mike Stump11289f42009-09-09 15:08:12 +00005410
Ted Kremeneke65b0862012-03-06 20:05:56 +00005411 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5412 return Success(E->getValue(), E);
5413 }
5414
Richard Smith4ce706a2011-10-11 21:43:33 +00005415 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005416 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005417 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005418 }
5419
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005420 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005421 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005422 }
5423
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005424 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5425 return Success(E->getValue(), E);
5426 }
5427
Douglas Gregor29c42f22012-02-24 07:38:34 +00005428 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5429 return Success(E->getValue(), E);
5430 }
5431
John Wiegley6242b6a2011-04-28 00:16:57 +00005432 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5433 return Success(E->getValue(), E);
5434 }
5435
John Wiegleyf9f65842011-04-25 06:54:41 +00005436 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5437 return Success(E->getValue(), E);
5438 }
5439
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005440 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005441 bool VisitUnaryImag(const UnaryOperator *E);
5442
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005443 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005444 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005445
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005446private:
Ken Dyck160146e2010-01-27 17:10:57 +00005447 CharUnits GetAlignOfExpr(const Expr *E);
5448 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005449 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005450 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005451 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005452};
Chris Lattner05706e882008-07-11 18:11:29 +00005453} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005454
Richard Smith11562c52011-10-28 17:51:58 +00005455/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5456/// produce either the integer value or a pointer.
5457///
5458/// GCC has a heinous extension which folds casts between pointer types and
5459/// pointer-sized integral types. We support this by allowing the evaluation of
5460/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5461/// Some simple arithmetic on such values is supported (they are treated much
5462/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005463static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005464 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005465 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005466 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005467}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005468
Richard Smithf57d8cb2011-12-09 22:58:01 +00005469static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005470 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005471 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005472 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005473 if (!Val.isInt()) {
5474 // FIXME: It would be better to produce the diagnostic for casting
5475 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005477 return false;
5478 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005479 Result = Val.getInt();
5480 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005481}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005482
Richard Smithf57d8cb2011-12-09 22:58:01 +00005483/// Check whether the given declaration can be directly converted to an integral
5484/// rvalue. If not, no diagnostic is produced; there are other things we can
5485/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005486bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005487 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005488 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005489 // Check for signedness/width mismatches between E type and ECD value.
5490 bool SameSign = (ECD->getInitVal().isSigned()
5491 == E->getType()->isSignedIntegerOrEnumerationType());
5492 bool SameWidth = (ECD->getInitVal().getBitWidth()
5493 == Info.Ctx.getIntWidth(E->getType()));
5494 if (SameSign && SameWidth)
5495 return Success(ECD->getInitVal(), E);
5496 else {
5497 // Get rid of mismatch (otherwise Success assertions will fail)
5498 // by computing a new value matching the type of E.
5499 llvm::APSInt Val = ECD->getInitVal();
5500 if (!SameSign)
5501 Val.setIsSigned(!ECD->getInitVal().isSigned());
5502 if (!SameWidth)
5503 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5504 return Success(Val, E);
5505 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005506 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005507 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005508}
5509
Chris Lattner86ee2862008-10-06 06:40:35 +00005510/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5511/// as GCC.
5512static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5513 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005514 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005515 enum gcc_type_class {
5516 no_type_class = -1,
5517 void_type_class, integer_type_class, char_type_class,
5518 enumeral_type_class, boolean_type_class,
5519 pointer_type_class, reference_type_class, offset_type_class,
5520 real_type_class, complex_type_class,
5521 function_type_class, method_type_class,
5522 record_type_class, union_type_class,
5523 array_type_class, string_type_class,
5524 lang_type_class
5525 };
Mike Stump11289f42009-09-09 15:08:12 +00005526
5527 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005528 // ideal, however it is what gcc does.
5529 if (E->getNumArgs() == 0)
5530 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005531
Chris Lattner86ee2862008-10-06 06:40:35 +00005532 QualType ArgTy = E->getArg(0)->getType();
5533 if (ArgTy->isVoidType())
5534 return void_type_class;
5535 else if (ArgTy->isEnumeralType())
5536 return enumeral_type_class;
5537 else if (ArgTy->isBooleanType())
5538 return boolean_type_class;
5539 else if (ArgTy->isCharType())
5540 return string_type_class; // gcc doesn't appear to use char_type_class
5541 else if (ArgTy->isIntegerType())
5542 return integer_type_class;
5543 else if (ArgTy->isPointerType())
5544 return pointer_type_class;
5545 else if (ArgTy->isReferenceType())
5546 return reference_type_class;
5547 else if (ArgTy->isRealType())
5548 return real_type_class;
5549 else if (ArgTy->isComplexType())
5550 return complex_type_class;
5551 else if (ArgTy->isFunctionType())
5552 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005553 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005554 return record_type_class;
5555 else if (ArgTy->isUnionType())
5556 return union_type_class;
5557 else if (ArgTy->isArrayType())
5558 return array_type_class;
5559 else if (ArgTy->isUnionType())
5560 return union_type_class;
5561 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005562 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005563}
5564
Richard Smith5fab0c92011-12-28 19:48:30 +00005565/// EvaluateBuiltinConstantPForLValue - Determine the result of
5566/// __builtin_constant_p when applied to the given lvalue.
5567///
5568/// An lvalue is only "constant" if it is a pointer or reference to the first
5569/// character of a string literal.
5570template<typename LValue>
5571static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005572 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005573 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5574}
5575
5576/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5577/// GCC as we can manage.
5578static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5579 QualType ArgType = Arg->getType();
5580
5581 // __builtin_constant_p always has one operand. The rules which gcc follows
5582 // are not precisely documented, but are as follows:
5583 //
5584 // - If the operand is of integral, floating, complex or enumeration type,
5585 // and can be folded to a known value of that type, it returns 1.
5586 // - If the operand and can be folded to a pointer to the first character
5587 // of a string literal (or such a pointer cast to an integral type), it
5588 // returns 1.
5589 //
5590 // Otherwise, it returns 0.
5591 //
5592 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5593 // its support for this does not currently work.
5594 if (ArgType->isIntegralOrEnumerationType()) {
5595 Expr::EvalResult Result;
5596 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5597 return false;
5598
5599 APValue &V = Result.Val;
5600 if (V.getKind() == APValue::Int)
5601 return true;
5602
5603 return EvaluateBuiltinConstantPForLValue(V);
5604 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5605 return Arg->isEvaluatable(Ctx);
5606 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5607 LValue LV;
5608 Expr::EvalStatus Status;
5609 EvalInfo Info(Ctx, Status);
5610 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5611 : EvaluatePointer(Arg, LV, Info)) &&
5612 !Status.HasSideEffects)
5613 return EvaluateBuiltinConstantPForLValue(LV);
5614 }
5615
5616 // Anything else isn't considered to be sufficiently constant.
5617 return false;
5618}
5619
John McCall95007602010-05-10 23:27:23 +00005620/// Retrieves the "underlying object type" of the given expression,
5621/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005622QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5623 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5624 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005625 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005626 } else if (const Expr *E = B.get<const Expr*>()) {
5627 if (isa<CompoundLiteralExpr>(E))
5628 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005629 }
5630
5631 return QualType();
5632}
5633
Peter Collingbournee9200682011-05-13 03:29:01 +00005634bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005635 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005636
5637 {
5638 // The operand of __builtin_object_size is never evaluated for side-effects.
5639 // If there are any, but we can determine the pointed-to object anyway, then
5640 // ignore the side-effects.
5641 SpeculativeEvaluationRAII SpeculativeEval(Info);
5642 if (!EvaluatePointer(E->getArg(0), Base, Info))
5643 return false;
5644 }
John McCall95007602010-05-10 23:27:23 +00005645
5646 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005647 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005648
Richard Smithce40ad62011-11-12 22:28:03 +00005649 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005650 if (T.isNull() ||
5651 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005652 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005653 T->isVariablyModifiedType() ||
5654 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005655 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005656
5657 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5658 CharUnits Offset = Base.getLValueOffset();
5659
5660 if (!Offset.isNegative() && Offset <= Size)
5661 Size -= Offset;
5662 else
5663 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005664 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005665}
5666
Peter Collingbournee9200682011-05-13 03:29:01 +00005667bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005668 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005669 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005670 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005671
5672 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005673 if (TryEvaluateBuiltinObjectSize(E))
5674 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005675
Richard Smith0421ce72012-08-07 04:16:51 +00005676 // If evaluating the argument has side-effects, we can't determine the size
5677 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5678 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005679 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005680 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005681 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005682 return Success(0, E);
5683 }
Mike Stump876387b2009-10-27 22:09:17 +00005684
Richard Smith01ade172012-05-23 04:13:20 +00005685 // Expression had no side effects, but we couldn't statically determine the
5686 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005687 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005688 }
5689
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005690 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005691 case Builtin::BI__builtin_bswap32:
5692 case Builtin::BI__builtin_bswap64: {
5693 APSInt Val;
5694 if (!EvaluateInteger(E->getArg(0), Val, Info))
5695 return false;
5696
5697 return Success(Val.byteSwap(), E);
5698 }
5699
Richard Smith8889a3d2013-06-13 06:26:32 +00005700 case Builtin::BI__builtin_classify_type:
5701 return Success(EvaluateBuiltinClassifyType(E), E);
5702
5703 // FIXME: BI__builtin_clrsb
5704 // FIXME: BI__builtin_clrsbl
5705 // FIXME: BI__builtin_clrsbll
5706
Richard Smith80b3c8e2013-06-13 05:04:16 +00005707 case Builtin::BI__builtin_clz:
5708 case Builtin::BI__builtin_clzl:
5709 case Builtin::BI__builtin_clzll: {
5710 APSInt Val;
5711 if (!EvaluateInteger(E->getArg(0), Val, Info))
5712 return false;
5713 if (!Val)
5714 return Error(E);
5715
5716 return Success(Val.countLeadingZeros(), E);
5717 }
5718
Richard Smith8889a3d2013-06-13 06:26:32 +00005719 case Builtin::BI__builtin_constant_p:
5720 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5721
Richard Smith80b3c8e2013-06-13 05:04:16 +00005722 case Builtin::BI__builtin_ctz:
5723 case Builtin::BI__builtin_ctzl:
5724 case Builtin::BI__builtin_ctzll: {
5725 APSInt Val;
5726 if (!EvaluateInteger(E->getArg(0), Val, Info))
5727 return false;
5728 if (!Val)
5729 return Error(E);
5730
5731 return Success(Val.countTrailingZeros(), E);
5732 }
5733
Richard Smith8889a3d2013-06-13 06:26:32 +00005734 case Builtin::BI__builtin_eh_return_data_regno: {
5735 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5736 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5737 return Success(Operand, E);
5738 }
5739
5740 case Builtin::BI__builtin_expect:
5741 return Visit(E->getArg(0));
5742
5743 case Builtin::BI__builtin_ffs:
5744 case Builtin::BI__builtin_ffsl:
5745 case Builtin::BI__builtin_ffsll: {
5746 APSInt Val;
5747 if (!EvaluateInteger(E->getArg(0), Val, Info))
5748 return false;
5749
5750 unsigned N = Val.countTrailingZeros();
5751 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5752 }
5753
5754 case Builtin::BI__builtin_fpclassify: {
5755 APFloat Val(0.0);
5756 if (!EvaluateFloat(E->getArg(5), Val, Info))
5757 return false;
5758 unsigned Arg;
5759 switch (Val.getCategory()) {
5760 case APFloat::fcNaN: Arg = 0; break;
5761 case APFloat::fcInfinity: Arg = 1; break;
5762 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5763 case APFloat::fcZero: Arg = 4; break;
5764 }
5765 return Visit(E->getArg(Arg));
5766 }
5767
5768 case Builtin::BI__builtin_isinf_sign: {
5769 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00005770 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00005771 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5772 }
5773
5774 case Builtin::BI__builtin_parity:
5775 case Builtin::BI__builtin_parityl:
5776 case Builtin::BI__builtin_parityll: {
5777 APSInt Val;
5778 if (!EvaluateInteger(E->getArg(0), Val, Info))
5779 return false;
5780
5781 return Success(Val.countPopulation() % 2, E);
5782 }
5783
Richard Smith80b3c8e2013-06-13 05:04:16 +00005784 case Builtin::BI__builtin_popcount:
5785 case Builtin::BI__builtin_popcountl:
5786 case Builtin::BI__builtin_popcountll: {
5787 APSInt Val;
5788 if (!EvaluateInteger(E->getArg(0), Val, Info))
5789 return false;
5790
5791 return Success(Val.countPopulation(), E);
5792 }
5793
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005794 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005795 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005796 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005797 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005798 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5799 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005800 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005801 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005802 case Builtin::BI__builtin_strlen:
5803 // As an extension, we support strlen() and __builtin_strlen() as constant
5804 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005805 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005806 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5807 // The string literal may have embedded null characters. Find the first
5808 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005809 StringRef Str = S->getString();
5810 StringRef::size_type Pos = Str.find(0);
5811 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005812 Str = Str.substr(0, Pos);
5813
5814 return Success(Str.size(), E);
5815 }
5816
Richard Smithf57d8cb2011-12-09 22:58:01 +00005817 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005818
Richard Smith01ba47d2012-04-13 00:45:38 +00005819 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005820 case Builtin::BI__atomic_is_lock_free:
5821 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005822 APSInt SizeVal;
5823 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5824 return false;
5825
5826 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5827 // of two less than the maximum inline atomic width, we know it is
5828 // lock-free. If the size isn't a power of two, or greater than the
5829 // maximum alignment where we promote atomics, we know it is not lock-free
5830 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5831 // the answer can only be determined at runtime; for example, 16-byte
5832 // atomics have lock-free implementations on some, but not all,
5833 // x86-64 processors.
5834
5835 // Check power-of-two.
5836 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005837 if (Size.isPowerOfTwo()) {
5838 // Check against inlining width.
5839 unsigned InlineWidthBits =
5840 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5841 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5842 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5843 Size == CharUnits::One() ||
5844 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5845 Expr::NPC_NeverValueDependent))
5846 // OK, we will inline appropriately-aligned operations of this size,
5847 // and _Atomic(T) is appropriately-aligned.
5848 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005849
Richard Smith01ba47d2012-04-13 00:45:38 +00005850 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5851 castAs<PointerType>()->getPointeeType();
5852 if (!PointeeType->isIncompleteType() &&
5853 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5854 // OK, we will inline operations on this object.
5855 return Success(1, E);
5856 }
5857 }
5858 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005859
Richard Smith01ba47d2012-04-13 00:45:38 +00005860 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5861 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005862 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005863 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005864}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005865
Richard Smith8b3497e2011-10-31 01:37:14 +00005866static bool HasSameBase(const LValue &A, const LValue &B) {
5867 if (!A.getLValueBase())
5868 return !B.getLValueBase();
5869 if (!B.getLValueBase())
5870 return false;
5871
Richard Smithce40ad62011-11-12 22:28:03 +00005872 if (A.getLValueBase().getOpaqueValue() !=
5873 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005874 const Decl *ADecl = GetLValueBaseDecl(A);
5875 if (!ADecl)
5876 return false;
5877 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005878 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005879 return false;
5880 }
5881
5882 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005883 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005884}
5885
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005886namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005887
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005888/// \brief Data recursive integer evaluator of certain binary operators.
5889///
5890/// We use a data recursive algorithm for binary operators so that we are able
5891/// to handle extreme cases of chained binary operators without causing stack
5892/// overflow.
5893class DataRecursiveIntBinOpEvaluator {
5894 struct EvalResult {
5895 APValue Val;
5896 bool Failed;
5897
5898 EvalResult() : Failed(false) { }
5899
5900 void swap(EvalResult &RHS) {
5901 Val.swap(RHS.Val);
5902 Failed = RHS.Failed;
5903 RHS.Failed = false;
5904 }
5905 };
5906
5907 struct Job {
5908 const Expr *E;
5909 EvalResult LHSResult; // meaningful only for binary operator expression.
5910 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5911
5912 Job() : StoredInfo(0) { }
5913 void startSpeculativeEval(EvalInfo &Info) {
5914 OldEvalStatus = Info.EvalStatus;
5915 Info.EvalStatus.Diag = 0;
5916 StoredInfo = &Info;
5917 }
5918 ~Job() {
5919 if (StoredInfo) {
5920 StoredInfo->EvalStatus = OldEvalStatus;
5921 }
5922 }
5923 private:
5924 EvalInfo *StoredInfo; // non-null if status changed.
5925 Expr::EvalStatus OldEvalStatus;
5926 };
5927
5928 SmallVector<Job, 16> Queue;
5929
5930 IntExprEvaluator &IntEval;
5931 EvalInfo &Info;
5932 APValue &FinalResult;
5933
5934public:
5935 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5936 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5937
5938 /// \brief True if \param E is a binary operator that we are going to handle
5939 /// data recursively.
5940 /// We handle binary operators that are comma, logical, or that have operands
5941 /// with integral or enumeration type.
5942 static bool shouldEnqueue(const BinaryOperator *E) {
5943 return E->getOpcode() == BO_Comma ||
5944 E->isLogicalOp() ||
5945 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5946 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005947 }
5948
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005949 bool Traverse(const BinaryOperator *E) {
5950 enqueue(E);
5951 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005952 while (!Queue.empty())
5953 process(PrevResult);
5954
5955 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005956
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005957 FinalResult.swap(PrevResult.Val);
5958 return true;
5959 }
5960
5961private:
5962 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5963 return IntEval.Success(Value, E, Result);
5964 }
5965 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5966 return IntEval.Success(Value, E, Result);
5967 }
5968 bool Error(const Expr *E) {
5969 return IntEval.Error(E);
5970 }
5971 bool Error(const Expr *E, diag::kind D) {
5972 return IntEval.Error(E, D);
5973 }
5974
5975 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5976 return Info.CCEDiag(E, D);
5977 }
5978
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005979 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5980 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005981 bool &SuppressRHSDiags);
5982
5983 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5984 const BinaryOperator *E, APValue &Result);
5985
5986 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5987 Result.Failed = !Evaluate(Result.Val, Info, E);
5988 if (Result.Failed)
5989 Result.Val = APValue();
5990 }
5991
Richard Trieuba4d0872012-03-21 23:30:30 +00005992 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005993
5994 void enqueue(const Expr *E) {
5995 E = E->IgnoreParens();
5996 Queue.resize(Queue.size()+1);
5997 Queue.back().E = E;
5998 Queue.back().Kind = Job::AnyExprKind;
5999 }
6000};
6001
6002}
6003
6004bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006005 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006006 bool &SuppressRHSDiags) {
6007 if (E->getOpcode() == BO_Comma) {
6008 // Ignore LHS but note if we could not evaluate it.
6009 if (LHSResult.Failed)
6010 Info.EvalStatus.HasSideEffects = true;
6011 return true;
6012 }
6013
6014 if (E->isLogicalOp()) {
6015 bool lhsResult;
6016 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006017 // We were able to evaluate the LHS, see if we can get away with not
6018 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006019 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006020 Success(lhsResult, E, LHSResult.Val);
6021 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006022 }
6023 } else {
6024 // Since we weren't able to evaluate the left hand side, it
6025 // must have had side effects.
6026 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006027
6028 // We can't evaluate the LHS; however, sometimes the result
6029 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6030 // Don't ignore RHS and suppress diagnostics from this arm.
6031 SuppressRHSDiags = true;
6032 }
6033
6034 return true;
6035 }
6036
6037 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6038 E->getRHS()->getType()->isIntegralOrEnumerationType());
6039
6040 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006041 return false; // Ignore RHS;
6042
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006043 return true;
6044}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006045
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006046bool DataRecursiveIntBinOpEvaluator::
6047 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6048 const BinaryOperator *E, APValue &Result) {
6049 if (E->getOpcode() == BO_Comma) {
6050 if (RHSResult.Failed)
6051 return false;
6052 Result = RHSResult.Val;
6053 return true;
6054 }
6055
6056 if (E->isLogicalOp()) {
6057 bool lhsResult, rhsResult;
6058 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6059 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6060
6061 if (LHSIsOK) {
6062 if (RHSIsOK) {
6063 if (E->getOpcode() == BO_LOr)
6064 return Success(lhsResult || rhsResult, E, Result);
6065 else
6066 return Success(lhsResult && rhsResult, E, Result);
6067 }
6068 } else {
6069 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006070 // We can't evaluate the LHS; however, sometimes the result
6071 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6072 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006073 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006074 }
6075 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006076
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006077 return false;
6078 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006079
6080 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6081 E->getRHS()->getType()->isIntegralOrEnumerationType());
6082
6083 if (LHSResult.Failed || RHSResult.Failed)
6084 return false;
6085
6086 const APValue &LHSVal = LHSResult.Val;
6087 const APValue &RHSVal = RHSResult.Val;
6088
6089 // Handle cases like (unsigned long)&a + 4.
6090 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6091 Result = LHSVal;
6092 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6093 RHSVal.getInt().getZExtValue());
6094 if (E->getOpcode() == BO_Add)
6095 Result.getLValueOffset() += AdditionalOffset;
6096 else
6097 Result.getLValueOffset() -= AdditionalOffset;
6098 return true;
6099 }
6100
6101 // Handle cases like 4 + (unsigned long)&a
6102 if (E->getOpcode() == BO_Add &&
6103 RHSVal.isLValue() && LHSVal.isInt()) {
6104 Result = RHSVal;
6105 Result.getLValueOffset() += CharUnits::fromQuantity(
6106 LHSVal.getInt().getZExtValue());
6107 return true;
6108 }
6109
6110 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6111 // Handle (intptr_t)&&A - (intptr_t)&&B.
6112 if (!LHSVal.getLValueOffset().isZero() ||
6113 !RHSVal.getLValueOffset().isZero())
6114 return false;
6115 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6116 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6117 if (!LHSExpr || !RHSExpr)
6118 return false;
6119 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6120 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6121 if (!LHSAddrExpr || !RHSAddrExpr)
6122 return false;
6123 // Make sure both labels come from the same function.
6124 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6125 RHSAddrExpr->getLabel()->getDeclContext())
6126 return false;
6127 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6128 return true;
6129 }
Richard Smith43e77732013-05-07 04:50:00 +00006130
6131 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006132 if (!LHSVal.isInt() || !RHSVal.isInt())
6133 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006134
6135 // Set up the width and signedness manually, in case it can't be deduced
6136 // from the operation we're performing.
6137 // FIXME: Don't do this in the cases where we can deduce it.
6138 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6139 E->getType()->isUnsignedIntegerOrEnumerationType());
6140 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6141 RHSVal.getInt(), Value))
6142 return false;
6143 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006144}
6145
Richard Trieuba4d0872012-03-21 23:30:30 +00006146void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006147 Job &job = Queue.back();
6148
6149 switch (job.Kind) {
6150 case Job::AnyExprKind: {
6151 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6152 if (shouldEnqueue(Bop)) {
6153 job.Kind = Job::BinOpKind;
6154 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006155 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006156 }
6157 }
6158
6159 EvaluateExpr(job.E, Result);
6160 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006161 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006162 }
6163
6164 case Job::BinOpKind: {
6165 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006166 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006167 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006168 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006169 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006170 }
6171 if (SuppressRHSDiags)
6172 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006173 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006174 job.Kind = Job::BinOpVisitedLHSKind;
6175 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006176 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006177 }
6178
6179 case Job::BinOpVisitedLHSKind: {
6180 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6181 EvalResult RHS;
6182 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006183 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006184 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006185 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006186 }
6187 }
6188
6189 llvm_unreachable("Invalid Job::Kind!");
6190}
6191
6192bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6193 if (E->isAssignmentOp())
6194 return Error(E);
6195
6196 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6197 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006198
Anders Carlssonacc79812008-11-16 07:17:21 +00006199 QualType LHSTy = E->getLHS()->getType();
6200 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006201
6202 if (LHSTy->isAnyComplexType()) {
6203 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006204 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006205
Richard Smith253c2a32012-01-27 01:14:48 +00006206 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6207 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006208 return false;
6209
Richard Smith253c2a32012-01-27 01:14:48 +00006210 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006211 return false;
6212
6213 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006214 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006215 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006216 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006217 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6218
John McCalle3027922010-08-25 11:45:40 +00006219 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006220 return Success((CR_r == APFloat::cmpEqual &&
6221 CR_i == APFloat::cmpEqual), E);
6222 else {
John McCalle3027922010-08-25 11:45:40 +00006223 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006224 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006225 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006226 CR_r == APFloat::cmpLessThan ||
6227 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006228 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006229 CR_i == APFloat::cmpLessThan ||
6230 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006231 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006232 } else {
John McCalle3027922010-08-25 11:45:40 +00006233 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006234 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6235 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6236 else {
John McCalle3027922010-08-25 11:45:40 +00006237 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006238 "Invalid compex comparison.");
6239 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6240 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6241 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006242 }
6243 }
Mike Stump11289f42009-09-09 15:08:12 +00006244
Anders Carlssonacc79812008-11-16 07:17:21 +00006245 if (LHSTy->isRealFloatingType() &&
6246 RHSTy->isRealFloatingType()) {
6247 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006248
Richard Smith253c2a32012-01-27 01:14:48 +00006249 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6250 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006251 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006252
Richard Smith253c2a32012-01-27 01:14:48 +00006253 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006254 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006255
Anders Carlssonacc79812008-11-16 07:17:21 +00006256 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006257
Anders Carlssonacc79812008-11-16 07:17:21 +00006258 switch (E->getOpcode()) {
6259 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006260 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006261 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006262 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006263 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006264 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006265 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006266 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006267 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006268 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006269 E);
John McCalle3027922010-08-25 11:45:40 +00006270 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006271 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006272 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006273 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006274 || CR == APFloat::cmpLessThan
6275 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006276 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006277 }
Mike Stump11289f42009-09-09 15:08:12 +00006278
Eli Friedmana38da572009-04-28 19:17:36 +00006279 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006280 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006281 LValue LHSValue, RHSValue;
6282
6283 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6284 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006285 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006286
Richard Smith253c2a32012-01-27 01:14:48 +00006287 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006288 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006289
Richard Smith8b3497e2011-10-31 01:37:14 +00006290 // Reject differing bases from the normal codepath; we special-case
6291 // comparisons to null.
6292 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006293 if (E->getOpcode() == BO_Sub) {
6294 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006295 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6296 return false;
6297 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006298 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006299 if (!LHSExpr || !RHSExpr)
6300 return false;
6301 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6302 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6303 if (!LHSAddrExpr || !RHSAddrExpr)
6304 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006305 // Make sure both labels come from the same function.
6306 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6307 RHSAddrExpr->getLabel()->getDeclContext())
6308 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006309 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006310 return true;
6311 }
Richard Smith83c68212011-10-31 05:11:32 +00006312 // Inequalities and subtractions between unrelated pointers have
6313 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006314 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006315 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006316 // A constant address may compare equal to the address of a symbol.
6317 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006318 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006319 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6320 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006321 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006322 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006323 // distinct addresses. In clang, the result of such a comparison is
6324 // unspecified, so it is not a constant expression. However, we do know
6325 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006326 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6327 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006328 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006329 // We can't tell whether weak symbols will end up pointing to the same
6330 // object.
6331 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006332 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006333 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006334 // (Note that clang defaults to -fmerge-all-constants, which can
6335 // lead to inconsistent results for comparisons involving the address
6336 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006337 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006338 }
Eli Friedman64004332009-03-23 04:38:34 +00006339
Richard Smith1b470412012-02-01 08:10:20 +00006340 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6341 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6342
Richard Smith84f6dcf2012-02-02 01:16:57 +00006343 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6344 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6345
John McCalle3027922010-08-25 11:45:40 +00006346 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006347 // C++11 [expr.add]p6:
6348 // Unless both pointers point to elements of the same array object, or
6349 // one past the last element of the array object, the behavior is
6350 // undefined.
6351 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6352 !AreElementsOfSameArray(getType(LHSValue.Base),
6353 LHSDesignator, RHSDesignator))
6354 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6355
Chris Lattner882bdf22010-04-20 17:13:14 +00006356 QualType Type = E->getLHS()->getType();
6357 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006358
Richard Smithd62306a2011-11-10 06:34:14 +00006359 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006360 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006361 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006362
Richard Smith1b470412012-02-01 08:10:20 +00006363 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6364 // and produce incorrect results when it overflows. Such behavior
6365 // appears to be non-conforming, but is common, so perhaps we should
6366 // assume the standard intended for such cases to be undefined behavior
6367 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006368
Richard Smith1b470412012-02-01 08:10:20 +00006369 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6370 // overflow in the final conversion to ptrdiff_t.
6371 APSInt LHS(
6372 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6373 APSInt RHS(
6374 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6375 APSInt ElemSize(
6376 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6377 APSInt TrueResult = (LHS - RHS) / ElemSize;
6378 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6379
6380 if (Result.extend(65) != TrueResult)
6381 HandleOverflow(Info, E, TrueResult, E->getType());
6382 return Success(Result, E);
6383 }
Richard Smithde21b242012-01-31 06:41:30 +00006384
6385 // C++11 [expr.rel]p3:
6386 // Pointers to void (after pointer conversions) can be compared, with a
6387 // result defined as follows: If both pointers represent the same
6388 // address or are both the null pointer value, the result is true if the
6389 // operator is <= or >= and false otherwise; otherwise the result is
6390 // unspecified.
6391 // We interpret this as applying to pointers to *cv* void.
6392 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006393 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006394 CCEDiag(E, diag::note_constexpr_void_comparison);
6395
Richard Smith84f6dcf2012-02-02 01:16:57 +00006396 // C++11 [expr.rel]p2:
6397 // - If two pointers point to non-static data members of the same object,
6398 // or to subobjects or array elements fo such members, recursively, the
6399 // pointer to the later declared member compares greater provided the
6400 // two members have the same access control and provided their class is
6401 // not a union.
6402 // [...]
6403 // - Otherwise pointer comparisons are unspecified.
6404 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6405 E->isRelationalOp()) {
6406 bool WasArrayIndex;
6407 unsigned Mismatch =
6408 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6409 RHSDesignator, WasArrayIndex);
6410 // At the point where the designators diverge, the comparison has a
6411 // specified value if:
6412 // - we are comparing array indices
6413 // - we are comparing fields of a union, or fields with the same access
6414 // Otherwise, the result is unspecified and thus the comparison is not a
6415 // constant expression.
6416 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6417 Mismatch < RHSDesignator.Entries.size()) {
6418 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6419 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6420 if (!LF && !RF)
6421 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6422 else if (!LF)
6423 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6424 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6425 << RF->getParent() << RF;
6426 else if (!RF)
6427 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6428 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6429 << LF->getParent() << LF;
6430 else if (!LF->getParent()->isUnion() &&
6431 LF->getAccess() != RF->getAccess())
6432 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6433 << LF << LF->getAccess() << RF << RF->getAccess()
6434 << LF->getParent();
6435 }
6436 }
6437
Eli Friedman6c31cb42012-04-16 04:30:08 +00006438 // The comparison here must be unsigned, and performed with the same
6439 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006440 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6441 uint64_t CompareLHS = LHSOffset.getQuantity();
6442 uint64_t CompareRHS = RHSOffset.getQuantity();
6443 assert(PtrSize <= 64 && "Unexpected pointer width");
6444 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6445 CompareLHS &= Mask;
6446 CompareRHS &= Mask;
6447
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006448 // If there is a base and this is a relational operator, we can only
6449 // compare pointers within the object in question; otherwise, the result
6450 // depends on where the object is located in memory.
6451 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6452 QualType BaseTy = getType(LHSValue.Base);
6453 if (BaseTy->isIncompleteType())
6454 return Error(E);
6455 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6456 uint64_t OffsetLimit = Size.getQuantity();
6457 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6458 return Error(E);
6459 }
6460
Richard Smith8b3497e2011-10-31 01:37:14 +00006461 switch (E->getOpcode()) {
6462 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006463 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6464 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6465 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6466 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6467 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6468 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006469 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006470 }
6471 }
Richard Smith7bb00672012-02-01 01:42:44 +00006472
6473 if (LHSTy->isMemberPointerType()) {
6474 assert(E->isEqualityOp() && "unexpected member pointer operation");
6475 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6476
6477 MemberPtr LHSValue, RHSValue;
6478
6479 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6480 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6481 return false;
6482
6483 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6484 return false;
6485
6486 // C++11 [expr.eq]p2:
6487 // If both operands are null, they compare equal. Otherwise if only one is
6488 // null, they compare unequal.
6489 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6490 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6491 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6492 }
6493
6494 // Otherwise if either is a pointer to a virtual member function, the
6495 // result is unspecified.
6496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6497 if (MD->isVirtual())
6498 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6499 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6500 if (MD->isVirtual())
6501 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6502
6503 // Otherwise they compare equal if and only if they would refer to the
6504 // same member of the same most derived object or the same subobject if
6505 // they were dereferenced with a hypothetical object of the associated
6506 // class type.
6507 bool Equal = LHSValue == RHSValue;
6508 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6509 }
6510
Richard Smithab44d9b2012-02-14 22:35:28 +00006511 if (LHSTy->isNullPtrType()) {
6512 assert(E->isComparisonOp() && "unexpected nullptr operation");
6513 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6514 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6515 // are compared, the result is true of the operator is <=, >= or ==, and
6516 // false otherwise.
6517 BinaryOperator::Opcode Opcode = E->getOpcode();
6518 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6519 }
6520
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006521 assert((!LHSTy->isIntegralOrEnumerationType() ||
6522 !RHSTy->isIntegralOrEnumerationType()) &&
6523 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6524 // We can't continue from here for non-integral types.
6525 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006526}
6527
Ken Dyck160146e2010-01-27 17:10:57 +00006528CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006529 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6530 // result shall be the alignment of the referenced type."
6531 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6532 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006533
6534 // __alignof is defined to return the preferred alignment.
6535 return Info.Ctx.toCharUnitsFromBits(
6536 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006537}
6538
Ken Dyck160146e2010-01-27 17:10:57 +00006539CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006540 E = E->IgnoreParens();
6541
John McCall768439e2013-05-06 07:40:34 +00006542 // The kinds of expressions that we have special-case logic here for
6543 // should be kept up to date with the special checks for those
6544 // expressions in Sema.
6545
Chris Lattner68061312009-01-24 21:53:27 +00006546 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006547 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006549 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6550 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006551
Chris Lattner68061312009-01-24 21:53:27 +00006552 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006553 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6554 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006555
Chris Lattner24aeeab2009-01-24 21:09:06 +00006556 return GetAlignOfType(E->getType());
6557}
6558
6559
Peter Collingbournee190dee2011-03-11 19:24:49 +00006560/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6561/// a result as the expression's type.
6562bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6563 const UnaryExprOrTypeTraitExpr *E) {
6564 switch(E->getKind()) {
6565 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006566 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006567 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006568 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006569 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006570 }
Eli Friedman64004332009-03-23 04:38:34 +00006571
Peter Collingbournee190dee2011-03-11 19:24:49 +00006572 case UETT_VecStep: {
6573 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006574
Peter Collingbournee190dee2011-03-11 19:24:49 +00006575 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006576 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006577
Peter Collingbournee190dee2011-03-11 19:24:49 +00006578 // The vec_step built-in functions that take a 3-component
6579 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6580 if (n == 3)
6581 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006582
Peter Collingbournee190dee2011-03-11 19:24:49 +00006583 return Success(n, E);
6584 } else
6585 return Success(1, E);
6586 }
6587
6588 case UETT_SizeOf: {
6589 QualType SrcTy = E->getTypeOfArgument();
6590 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6591 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006592 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6593 SrcTy = Ref->getPointeeType();
6594
Richard Smithd62306a2011-11-10 06:34:14 +00006595 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006596 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006597 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006598 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006599 }
6600 }
6601
6602 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006603}
6604
Peter Collingbournee9200682011-05-13 03:29:01 +00006605bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006606 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006607 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006608 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006609 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006610 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006611 for (unsigned i = 0; i != n; ++i) {
6612 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6613 switch (ON.getKind()) {
6614 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006615 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006616 APSInt IdxResult;
6617 if (!EvaluateInteger(Idx, IdxResult, Info))
6618 return false;
6619 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6620 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006621 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006622 CurrentType = AT->getElementType();
6623 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6624 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006625 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006626 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006627
Douglas Gregor882211c2010-04-28 22:16:22 +00006628 case OffsetOfExpr::OffsetOfNode::Field: {
6629 FieldDecl *MemberDecl = ON.getField();
6630 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006631 if (!RT)
6632 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006633 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006634 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006635 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006636 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006637 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006638 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006639 CurrentType = MemberDecl->getType().getNonReferenceType();
6640 break;
6641 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006642
Douglas Gregor882211c2010-04-28 22:16:22 +00006643 case OffsetOfExpr::OffsetOfNode::Identifier:
6644 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006645
Douglas Gregord1702062010-04-29 00:18:15 +00006646 case OffsetOfExpr::OffsetOfNode::Base: {
6647 CXXBaseSpecifier *BaseSpec = ON.getBase();
6648 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006649 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006650
6651 // Find the layout of the class whose base we are looking into.
6652 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006653 if (!RT)
6654 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006655 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006656 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006657 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6658
6659 // Find the base class itself.
6660 CurrentType = BaseSpec->getType();
6661 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6662 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006663 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006664
6665 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006666 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006667 break;
6668 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006669 }
6670 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006671 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006672}
6673
Chris Lattnere13042c2008-07-11 19:10:17 +00006674bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006675 switch (E->getOpcode()) {
6676 default:
6677 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6678 // See C99 6.6p3.
6679 return Error(E);
6680 case UO_Extension:
6681 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6682 // If so, we could clear the diagnostic ID.
6683 return Visit(E->getSubExpr());
6684 case UO_Plus:
6685 // The result is just the value.
6686 return Visit(E->getSubExpr());
6687 case UO_Minus: {
6688 if (!Visit(E->getSubExpr()))
6689 return false;
6690 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006691 const APSInt &Value = Result.getInt();
6692 if (Value.isSigned() && Value.isMinSignedValue())
6693 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6694 E->getType());
6695 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006696 }
6697 case UO_Not: {
6698 if (!Visit(E->getSubExpr()))
6699 return false;
6700 if (!Result.isInt()) return Error(E);
6701 return Success(~Result.getInt(), E);
6702 }
6703 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006704 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006705 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006706 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006707 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006708 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006709 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006710}
Mike Stump11289f42009-09-09 15:08:12 +00006711
Chris Lattner477c4be2008-07-12 01:15:53 +00006712/// HandleCast - This is used to evaluate implicit or explicit casts where the
6713/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006714bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6715 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006716 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006717 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006718
Eli Friedmanc757de22011-03-25 00:43:55 +00006719 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006720 case CK_BaseToDerived:
6721 case CK_DerivedToBase:
6722 case CK_UncheckedDerivedToBase:
6723 case CK_Dynamic:
6724 case CK_ToUnion:
6725 case CK_ArrayToPointerDecay:
6726 case CK_FunctionToPointerDecay:
6727 case CK_NullToPointer:
6728 case CK_NullToMemberPointer:
6729 case CK_BaseToDerivedMemberPointer:
6730 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006731 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006732 case CK_ConstructorConversion:
6733 case CK_IntegralToPointer:
6734 case CK_ToVoid:
6735 case CK_VectorSplat:
6736 case CK_IntegralToFloating:
6737 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006738 case CK_CPointerToObjCPointerCast:
6739 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006740 case CK_AnyPointerToBlockPointerCast:
6741 case CK_ObjCObjectLValueCast:
6742 case CK_FloatingRealToComplex:
6743 case CK_FloatingComplexToReal:
6744 case CK_FloatingComplexCast:
6745 case CK_FloatingComplexToIntegralComplex:
6746 case CK_IntegralRealToComplex:
6747 case CK_IntegralComplexCast:
6748 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006749 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006750 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006751 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006752 llvm_unreachable("invalid cast kind for integral value");
6753
Eli Friedman9faf2f92011-03-25 19:07:11 +00006754 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006755 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006756 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006757 case CK_ARCProduceObject:
6758 case CK_ARCConsumeObject:
6759 case CK_ARCReclaimReturnedObject:
6760 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006761 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006762 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006763
Richard Smith4ef685b2012-01-17 21:17:26 +00006764 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006765 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006766 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006767 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006768 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006769
6770 case CK_MemberPointerToBoolean:
6771 case CK_PointerToBoolean:
6772 case CK_IntegralToBoolean:
6773 case CK_FloatingToBoolean:
6774 case CK_FloatingComplexToBoolean:
6775 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006776 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006777 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006778 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006779 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006780 }
6781
Eli Friedmanc757de22011-03-25 00:43:55 +00006782 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006783 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006784 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006785
Eli Friedman742421e2009-02-20 01:15:07 +00006786 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006787 // Allow casts of address-of-label differences if they are no-ops
6788 // or narrowing. (The narrowing case isn't actually guaranteed to
6789 // be constant-evaluatable except in some narrow cases which are hard
6790 // to detect here. We let it through on the assumption the user knows
6791 // what they are doing.)
6792 if (Result.isAddrLabelDiff())
6793 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006794 // Only allow casts of lvalues if they are lossless.
6795 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6796 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006797
Richard Smith911e1422012-01-30 22:27:01 +00006798 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6799 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006800 }
Mike Stump11289f42009-09-09 15:08:12 +00006801
Eli Friedmanc757de22011-03-25 00:43:55 +00006802 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006803 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6804
John McCall45d55e42010-05-07 21:00:08 +00006805 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006806 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006807 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006808
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006809 if (LV.getLValueBase()) {
6810 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006811 // FIXME: Allow a larger integer size than the pointer size, and allow
6812 // narrowing back down to pointer width in subsequent integral casts.
6813 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006814 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006815 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006816
Richard Smithcf74da72011-11-16 07:18:12 +00006817 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006818 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006819 return true;
6820 }
6821
Ken Dyck02990832010-01-15 12:37:54 +00006822 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6823 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006824 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006825 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006826
Eli Friedmanc757de22011-03-25 00:43:55 +00006827 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006828 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006829 if (!EvaluateComplex(SubExpr, C, Info))
6830 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006831 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006832 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006833
Eli Friedmanc757de22011-03-25 00:43:55 +00006834 case CK_FloatingToIntegral: {
6835 APFloat F(0.0);
6836 if (!EvaluateFloat(SubExpr, F, Info))
6837 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006838
Richard Smith357362d2011-12-13 06:39:58 +00006839 APSInt Value;
6840 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6841 return false;
6842 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006843 }
6844 }
Mike Stump11289f42009-09-09 15:08:12 +00006845
Eli Friedmanc757de22011-03-25 00:43:55 +00006846 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006847}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006848
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006849bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6850 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006851 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006852 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6853 return false;
6854 if (!LV.isComplexInt())
6855 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006856 return Success(LV.getComplexIntReal(), E);
6857 }
6858
6859 return Visit(E->getSubExpr());
6860}
6861
Eli Friedman4e7a2412009-02-27 04:45:43 +00006862bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006863 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006864 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006865 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6866 return false;
6867 if (!LV.isComplexInt())
6868 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006869 return Success(LV.getComplexIntImag(), E);
6870 }
6871
Richard Smith4a678122011-10-24 18:44:57 +00006872 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006873 return Success(0, E);
6874}
6875
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006876bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6877 return Success(E->getPackLength(), E);
6878}
6879
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006880bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6881 return Success(E->getValue(), E);
6882}
6883
Chris Lattner05706e882008-07-11 18:11:29 +00006884//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006885// Float Evaluation
6886//===----------------------------------------------------------------------===//
6887
6888namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006889class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006890 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006891 APFloat &Result;
6892public:
6893 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006894 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006895
Richard Smith2e312c82012-03-03 22:46:17 +00006896 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006897 Result = V.getFloat();
6898 return true;
6899 }
Eli Friedman24c01542008-08-22 00:06:13 +00006900
Richard Smithfddd3842011-12-30 21:15:51 +00006901 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006902 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6903 return true;
6904 }
6905
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006906 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006907
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006908 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006909 bool VisitBinaryOperator(const BinaryOperator *E);
6910 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006911 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006912
John McCallb1fb0d32010-05-07 22:08:54 +00006913 bool VisitUnaryReal(const UnaryOperator *E);
6914 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006915
Richard Smithfddd3842011-12-30 21:15:51 +00006916 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006917};
6918} // end anonymous namespace
6919
6920static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006921 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006922 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006923}
6924
Jay Foad39c79802011-01-12 09:06:06 +00006925static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006926 QualType ResultTy,
6927 const Expr *Arg,
6928 bool SNaN,
6929 llvm::APFloat &Result) {
6930 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6931 if (!S) return false;
6932
6933 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6934
6935 llvm::APInt fill;
6936
6937 // Treat empty strings as if they were zero.
6938 if (S->getString().empty())
6939 fill = llvm::APInt(32, 0);
6940 else if (S->getString().getAsInteger(0, fill))
6941 return false;
6942
6943 if (SNaN)
6944 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6945 else
6946 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6947 return true;
6948}
6949
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006950bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006951 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006952 default:
6953 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6954
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006955 case Builtin::BI__builtin_huge_val:
6956 case Builtin::BI__builtin_huge_valf:
6957 case Builtin::BI__builtin_huge_vall:
6958 case Builtin::BI__builtin_inf:
6959 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006960 case Builtin::BI__builtin_infl: {
6961 const llvm::fltSemantics &Sem =
6962 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006963 Result = llvm::APFloat::getInf(Sem);
6964 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006965 }
Mike Stump11289f42009-09-09 15:08:12 +00006966
John McCall16291492010-02-28 13:00:19 +00006967 case Builtin::BI__builtin_nans:
6968 case Builtin::BI__builtin_nansf:
6969 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006970 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6971 true, Result))
6972 return Error(E);
6973 return true;
John McCall16291492010-02-28 13:00:19 +00006974
Chris Lattner0b7282e2008-10-06 06:31:58 +00006975 case Builtin::BI__builtin_nan:
6976 case Builtin::BI__builtin_nanf:
6977 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006978 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006979 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006980 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6981 false, Result))
6982 return Error(E);
6983 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006984
6985 case Builtin::BI__builtin_fabs:
6986 case Builtin::BI__builtin_fabsf:
6987 case Builtin::BI__builtin_fabsl:
6988 if (!EvaluateFloat(E->getArg(0), Result, Info))
6989 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006990
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006991 if (Result.isNegative())
6992 Result.changeSign();
6993 return true;
6994
Richard Smith8889a3d2013-06-13 06:26:32 +00006995 // FIXME: Builtin::BI__builtin_powi
6996 // FIXME: Builtin::BI__builtin_powif
6997 // FIXME: Builtin::BI__builtin_powil
6998
Mike Stump11289f42009-09-09 15:08:12 +00006999 case Builtin::BI__builtin_copysign:
7000 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007001 case Builtin::BI__builtin_copysignl: {
7002 APFloat RHS(0.);
7003 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7004 !EvaluateFloat(E->getArg(1), RHS, Info))
7005 return false;
7006 Result.copySign(RHS);
7007 return true;
7008 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007009 }
7010}
7011
John McCallb1fb0d32010-05-07 22:08:54 +00007012bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007013 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7014 ComplexValue CV;
7015 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7016 return false;
7017 Result = CV.FloatReal;
7018 return true;
7019 }
7020
7021 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007022}
7023
7024bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007025 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7026 ComplexValue CV;
7027 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7028 return false;
7029 Result = CV.FloatImag;
7030 return true;
7031 }
7032
Richard Smith4a678122011-10-24 18:44:57 +00007033 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007034 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7035 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007036 return true;
7037}
7038
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007039bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007040 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007041 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007042 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007043 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007044 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007045 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7046 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007047 Result.changeSign();
7048 return true;
7049 }
7050}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007051
Eli Friedman24c01542008-08-22 00:06:13 +00007052bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007053 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7054 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007055
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007056 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007057 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7058 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007059 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007060 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7061 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007062}
7063
7064bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7065 Result = E->getValue();
7066 return true;
7067}
7068
Peter Collingbournee9200682011-05-13 03:29:01 +00007069bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7070 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007071
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007072 switch (E->getCastKind()) {
7073 default:
Richard Smith11562c52011-10-28 17:51:58 +00007074 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007075
7076 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007077 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007078 return EvaluateInteger(SubExpr, IntResult, Info) &&
7079 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7080 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007081 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007082
7083 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007084 if (!Visit(SubExpr))
7085 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007086 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7087 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007088 }
John McCalld7646252010-11-14 08:17:51 +00007089
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007090 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007091 ComplexValue V;
7092 if (!EvaluateComplex(SubExpr, V, Info))
7093 return false;
7094 Result = V.getComplexFloatReal();
7095 return true;
7096 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007097 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007098}
7099
Eli Friedman24c01542008-08-22 00:06:13 +00007100//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007101// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007102//===----------------------------------------------------------------------===//
7103
7104namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007105class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007106 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007107 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007108
Anders Carlsson537969c2008-11-16 20:27:53 +00007109public:
John McCall93d91dc2010-05-07 17:22:02 +00007110 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007111 : ExprEvaluatorBaseTy(info), Result(Result) {}
7112
Richard Smith2e312c82012-03-03 22:46:17 +00007113 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007114 Result.setFrom(V);
7115 return true;
7116 }
Mike Stump11289f42009-09-09 15:08:12 +00007117
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007118 bool ZeroInitialization(const Expr *E);
7119
Anders Carlsson537969c2008-11-16 20:27:53 +00007120 //===--------------------------------------------------------------------===//
7121 // Visitor Methods
7122 //===--------------------------------------------------------------------===//
7123
Peter Collingbournee9200682011-05-13 03:29:01 +00007124 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007125 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007126 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007127 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007128 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007129};
7130} // end anonymous namespace
7131
John McCall93d91dc2010-05-07 17:22:02 +00007132static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7133 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007134 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007135 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007136}
7137
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007138bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007139 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007140 if (ElemTy->isRealFloatingType()) {
7141 Result.makeComplexFloat();
7142 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7143 Result.FloatReal = Zero;
7144 Result.FloatImag = Zero;
7145 } else {
7146 Result.makeComplexInt();
7147 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7148 Result.IntReal = Zero;
7149 Result.IntImag = Zero;
7150 }
7151 return true;
7152}
7153
Peter Collingbournee9200682011-05-13 03:29:01 +00007154bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7155 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007156
7157 if (SubExpr->getType()->isRealFloatingType()) {
7158 Result.makeComplexFloat();
7159 APFloat &Imag = Result.FloatImag;
7160 if (!EvaluateFloat(SubExpr, Imag, Info))
7161 return false;
7162
7163 Result.FloatReal = APFloat(Imag.getSemantics());
7164 return true;
7165 } else {
7166 assert(SubExpr->getType()->isIntegerType() &&
7167 "Unexpected imaginary literal.");
7168
7169 Result.makeComplexInt();
7170 APSInt &Imag = Result.IntImag;
7171 if (!EvaluateInteger(SubExpr, Imag, Info))
7172 return false;
7173
7174 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7175 return true;
7176 }
7177}
7178
Peter Collingbournee9200682011-05-13 03:29:01 +00007179bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007180
John McCallfcef3cf2010-12-14 17:51:41 +00007181 switch (E->getCastKind()) {
7182 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007183 case CK_BaseToDerived:
7184 case CK_DerivedToBase:
7185 case CK_UncheckedDerivedToBase:
7186 case CK_Dynamic:
7187 case CK_ToUnion:
7188 case CK_ArrayToPointerDecay:
7189 case CK_FunctionToPointerDecay:
7190 case CK_NullToPointer:
7191 case CK_NullToMemberPointer:
7192 case CK_BaseToDerivedMemberPointer:
7193 case CK_DerivedToBaseMemberPointer:
7194 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007195 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007196 case CK_ConstructorConversion:
7197 case CK_IntegralToPointer:
7198 case CK_PointerToIntegral:
7199 case CK_PointerToBoolean:
7200 case CK_ToVoid:
7201 case CK_VectorSplat:
7202 case CK_IntegralCast:
7203 case CK_IntegralToBoolean:
7204 case CK_IntegralToFloating:
7205 case CK_FloatingToIntegral:
7206 case CK_FloatingToBoolean:
7207 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007208 case CK_CPointerToObjCPointerCast:
7209 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007210 case CK_AnyPointerToBlockPointerCast:
7211 case CK_ObjCObjectLValueCast:
7212 case CK_FloatingComplexToReal:
7213 case CK_FloatingComplexToBoolean:
7214 case CK_IntegralComplexToReal:
7215 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007216 case CK_ARCProduceObject:
7217 case CK_ARCConsumeObject:
7218 case CK_ARCReclaimReturnedObject:
7219 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007220 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007221 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007222 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007223 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007224 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007225
John McCallfcef3cf2010-12-14 17:51:41 +00007226 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007227 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007228 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007230
7231 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007232 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007233 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007234 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007235
7236 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007237 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007238 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007239 return false;
7240
John McCallfcef3cf2010-12-14 17:51:41 +00007241 Result.makeComplexFloat();
7242 Result.FloatImag = APFloat(Real.getSemantics());
7243 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007244 }
7245
John McCallfcef3cf2010-12-14 17:51:41 +00007246 case CK_FloatingComplexCast: {
7247 if (!Visit(E->getSubExpr()))
7248 return false;
7249
7250 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7251 QualType From
7252 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7253
Richard Smith357362d2011-12-13 06:39:58 +00007254 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7255 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007256 }
7257
7258 case CK_FloatingComplexToIntegralComplex: {
7259 if (!Visit(E->getSubExpr()))
7260 return false;
7261
7262 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7263 QualType From
7264 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7265 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007266 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7267 To, Result.IntReal) &&
7268 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7269 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007270 }
7271
7272 case CK_IntegralRealToComplex: {
7273 APSInt &Real = Result.IntReal;
7274 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7275 return false;
7276
7277 Result.makeComplexInt();
7278 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7279 return true;
7280 }
7281
7282 case CK_IntegralComplexCast: {
7283 if (!Visit(E->getSubExpr()))
7284 return false;
7285
7286 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7287 QualType From
7288 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7289
Richard Smith911e1422012-01-30 22:27:01 +00007290 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7291 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007292 return true;
7293 }
7294
7295 case CK_IntegralComplexToFloatingComplex: {
7296 if (!Visit(E->getSubExpr()))
7297 return false;
7298
Ted Kremenek28831752012-08-23 20:46:57 +00007299 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007300 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007301 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007302 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007303 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7304 To, Result.FloatReal) &&
7305 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7306 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007307 }
7308 }
7309
7310 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007311}
7312
John McCall93d91dc2010-05-07 17:22:02 +00007313bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007314 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007315 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7316
Richard Smith253c2a32012-01-27 01:14:48 +00007317 bool LHSOK = Visit(E->getLHS());
7318 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007319 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007320
John McCall93d91dc2010-05-07 17:22:02 +00007321 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007322 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007323 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007324
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007325 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7326 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007327 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007328 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007329 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007330 if (Result.isComplexFloat()) {
7331 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7332 APFloat::rmNearestTiesToEven);
7333 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7334 APFloat::rmNearestTiesToEven);
7335 } else {
7336 Result.getComplexIntReal() += RHS.getComplexIntReal();
7337 Result.getComplexIntImag() += RHS.getComplexIntImag();
7338 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007339 break;
John McCalle3027922010-08-25 11:45:40 +00007340 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007341 if (Result.isComplexFloat()) {
7342 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7343 APFloat::rmNearestTiesToEven);
7344 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7345 APFloat::rmNearestTiesToEven);
7346 } else {
7347 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7348 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7349 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007350 break;
John McCalle3027922010-08-25 11:45:40 +00007351 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007352 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007353 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007354 APFloat &LHS_r = LHS.getComplexFloatReal();
7355 APFloat &LHS_i = LHS.getComplexFloatImag();
7356 APFloat &RHS_r = RHS.getComplexFloatReal();
7357 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007358
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007359 APFloat Tmp = LHS_r;
7360 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7361 Result.getComplexFloatReal() = Tmp;
7362 Tmp = LHS_i;
7363 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7364 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7365
7366 Tmp = LHS_r;
7367 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7368 Result.getComplexFloatImag() = Tmp;
7369 Tmp = LHS_i;
7370 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7371 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7372 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007373 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007374 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007375 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7376 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007377 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007378 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7379 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7380 }
7381 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007382 case BO_Div:
7383 if (Result.isComplexFloat()) {
7384 ComplexValue LHS = Result;
7385 APFloat &LHS_r = LHS.getComplexFloatReal();
7386 APFloat &LHS_i = LHS.getComplexFloatImag();
7387 APFloat &RHS_r = RHS.getComplexFloatReal();
7388 APFloat &RHS_i = RHS.getComplexFloatImag();
7389 APFloat &Res_r = Result.getComplexFloatReal();
7390 APFloat &Res_i = Result.getComplexFloatImag();
7391
7392 APFloat Den = RHS_r;
7393 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7394 APFloat Tmp = RHS_i;
7395 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7396 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7397
7398 Res_r = LHS_r;
7399 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7400 Tmp = LHS_i;
7401 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7402 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7403 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7404
7405 Res_i = LHS_i;
7406 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7407 Tmp = LHS_r;
7408 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7409 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7410 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7411 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007412 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7413 return Error(E, diag::note_expr_divide_by_zero);
7414
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007415 ComplexValue LHS = Result;
7416 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7417 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7418 Result.getComplexIntReal() =
7419 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7420 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7421 Result.getComplexIntImag() =
7422 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7423 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7424 }
7425 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007426 }
7427
John McCall93d91dc2010-05-07 17:22:02 +00007428 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007429}
7430
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007431bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7432 // Get the operand value into 'Result'.
7433 if (!Visit(E->getSubExpr()))
7434 return false;
7435
7436 switch (E->getOpcode()) {
7437 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007438 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007439 case UO_Extension:
7440 return true;
7441 case UO_Plus:
7442 // The result is always just the subexpr.
7443 return true;
7444 case UO_Minus:
7445 if (Result.isComplexFloat()) {
7446 Result.getComplexFloatReal().changeSign();
7447 Result.getComplexFloatImag().changeSign();
7448 }
7449 else {
7450 Result.getComplexIntReal() = -Result.getComplexIntReal();
7451 Result.getComplexIntImag() = -Result.getComplexIntImag();
7452 }
7453 return true;
7454 case UO_Not:
7455 if (Result.isComplexFloat())
7456 Result.getComplexFloatImag().changeSign();
7457 else
7458 Result.getComplexIntImag() = -Result.getComplexIntImag();
7459 return true;
7460 }
7461}
7462
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007463bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7464 if (E->getNumInits() == 2) {
7465 if (E->getType()->isComplexType()) {
7466 Result.makeComplexFloat();
7467 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7468 return false;
7469 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7470 return false;
7471 } else {
7472 Result.makeComplexInt();
7473 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7474 return false;
7475 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7476 return false;
7477 }
7478 return true;
7479 }
7480 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7481}
7482
Anders Carlsson537969c2008-11-16 20:27:53 +00007483//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007484// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7485// implicit conversion.
7486//===----------------------------------------------------------------------===//
7487
7488namespace {
7489class AtomicExprEvaluator :
7490 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7491 APValue &Result;
7492public:
7493 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7494 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7495
7496 bool Success(const APValue &V, const Expr *E) {
7497 Result = V;
7498 return true;
7499 }
7500
7501 bool ZeroInitialization(const Expr *E) {
7502 ImplicitValueInitExpr VIE(
7503 E->getType()->castAs<AtomicType>()->getValueType());
7504 return Evaluate(Result, Info, &VIE);
7505 }
7506
7507 bool VisitCastExpr(const CastExpr *E) {
7508 switch (E->getCastKind()) {
7509 default:
7510 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7511 case CK_NonAtomicToAtomic:
7512 return Evaluate(Result, Info, E->getSubExpr());
7513 }
7514 }
7515};
7516} // end anonymous namespace
7517
7518static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7519 assert(E->isRValue() && E->getType()->isAtomicType());
7520 return AtomicExprEvaluator(Info, Result).Visit(E);
7521}
7522
7523//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007524// Void expression evaluation, primarily for a cast to void on the LHS of a
7525// comma operator
7526//===----------------------------------------------------------------------===//
7527
7528namespace {
7529class VoidExprEvaluator
7530 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7531public:
7532 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7533
Richard Smith2e312c82012-03-03 22:46:17 +00007534 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007535
7536 bool VisitCastExpr(const CastExpr *E) {
7537 switch (E->getCastKind()) {
7538 default:
7539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7540 case CK_ToVoid:
7541 VisitIgnoredValue(E->getSubExpr());
7542 return true;
7543 }
7544 }
7545};
7546} // end anonymous namespace
7547
7548static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7549 assert(E->isRValue() && E->getType()->isVoidType());
7550 return VoidExprEvaluator(Info).Visit(E);
7551}
7552
7553//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007554// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007555//===----------------------------------------------------------------------===//
7556
Richard Smith2e312c82012-03-03 22:46:17 +00007557static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007558 // In C, function designators are not lvalues, but we evaluate them as if they
7559 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007560 QualType T = E->getType();
7561 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007562 LValue LV;
7563 if (!EvaluateLValue(E, LV, Info))
7564 return false;
7565 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007566 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007567 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007568 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007569 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007570 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007571 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007572 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007573 LValue LV;
7574 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007575 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007576 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007577 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007578 llvm::APFloat F(0.0);
7579 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007580 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007581 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007582 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007583 ComplexValue C;
7584 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007585 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007586 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007587 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007588 MemberPtr P;
7589 if (!EvaluateMemberPointer(E, P, Info))
7590 return false;
7591 P.moveInto(Result);
7592 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007593 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007594 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007595 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007596 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007597 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007598 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007599 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007600 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007601 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007602 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7603 return false;
7604 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007605 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007606 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007607 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007608 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007609 if (!EvaluateVoid(E, Info))
7610 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007611 } else if (T->isAtomicType()) {
7612 if (!EvaluateAtomic(E, Result, Info))
7613 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007614 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007615 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007616 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007617 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007618 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007619 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007620 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007621
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007622 return true;
7623}
7624
Richard Smithb228a862012-02-15 02:18:13 +00007625/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7626/// cases, the in-place evaluation is essential, since later initializers for
7627/// an object can indirectly refer to subobjects which were initialized earlier.
7628static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007629 const Expr *E, bool AllowNonLiteralTypes) {
7630 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007631 return false;
7632
7633 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007634 // Evaluate arrays and record types in-place, so that later initializers can
7635 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007636 if (E->getType()->isArrayType())
7637 return EvaluateArray(E, This, Result, Info);
7638 else if (E->getType()->isRecordType())
7639 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007640 }
7641
7642 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007643 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007644}
7645
Richard Smithf57d8cb2011-12-09 22:58:01 +00007646/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7647/// lvalue-to-rvalue cast if it is an lvalue.
7648static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007649 if (!CheckLiteralType(Info, E))
7650 return false;
7651
Richard Smith2e312c82012-03-03 22:46:17 +00007652 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007653 return false;
7654
7655 if (E->isGLValue()) {
7656 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007657 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007658 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007659 return false;
7660 }
7661
Richard Smith2e312c82012-03-03 22:46:17 +00007662 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007663 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007664}
Richard Smith11562c52011-10-28 17:51:58 +00007665
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007666static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7667 const ASTContext &Ctx, bool &IsConst) {
7668 // Fast-path evaluations of integer literals, since we sometimes see files
7669 // containing vast quantities of these.
7670 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7671 Result.Val = APValue(APSInt(L->getValue(),
7672 L->getType()->isUnsignedIntegerType()));
7673 IsConst = true;
7674 return true;
7675 }
7676
7677 // FIXME: Evaluating values of large array and record types can cause
7678 // performance problems. Only do so in C++11 for now.
7679 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7680 Exp->getType()->isRecordType()) &&
7681 !Ctx.getLangOpts().CPlusPlus11) {
7682 IsConst = false;
7683 return true;
7684 }
7685 return false;
7686}
7687
7688
Richard Smith7b553f12011-10-29 00:50:52 +00007689/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007690/// any crazy technique (that has nothing to do with language standards) that
7691/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007692/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7693/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007694bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007695 bool IsConst;
7696 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7697 return IsConst;
7698
Richard Smithf57d8cb2011-12-09 22:58:01 +00007699 EvalInfo Info(Ctx, Result);
7700 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007701}
7702
Jay Foad39c79802011-01-12 09:06:06 +00007703bool Expr::EvaluateAsBooleanCondition(bool &Result,
7704 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007705 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007706 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007707 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007708}
7709
Richard Smith5fab0c92011-12-28 19:48:30 +00007710bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7711 SideEffectsKind AllowSideEffects) const {
7712 if (!getType()->isIntegralOrEnumerationType())
7713 return false;
7714
Richard Smith11562c52011-10-28 17:51:58 +00007715 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007716 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7717 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007718 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007719
Richard Smith11562c52011-10-28 17:51:58 +00007720 Result = ExprResult.Val.getInt();
7721 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007722}
7723
Jay Foad39c79802011-01-12 09:06:06 +00007724bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007725 EvalInfo Info(Ctx, Result);
7726
John McCall45d55e42010-05-07 21:00:08 +00007727 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007728 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7729 !CheckLValueConstantExpression(Info, getExprLoc(),
7730 Ctx.getLValueReferenceType(getType()), LV))
7731 return false;
7732
Richard Smith2e312c82012-03-03 22:46:17 +00007733 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007734 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007735}
7736
Richard Smithd0b4dd62011-12-19 06:19:21 +00007737bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7738 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007739 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007740 // FIXME: Evaluating initializers for large array and record types can cause
7741 // performance problems. Only do so in C++11 for now.
7742 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007743 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007744 return false;
7745
Richard Smithd0b4dd62011-12-19 06:19:21 +00007746 Expr::EvalStatus EStatus;
7747 EStatus.Diag = &Notes;
7748
7749 EvalInfo InitInfo(Ctx, EStatus);
7750 InitInfo.setEvaluatingDecl(VD, Value);
7751
7752 LValue LVal;
7753 LVal.set(VD);
7754
Richard Smithfddd3842011-12-30 21:15:51 +00007755 // C++11 [basic.start.init]p2:
7756 // Variables with static storage duration or thread storage duration shall be
7757 // zero-initialized before any other initialization takes place.
7758 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007759 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007760 !VD->getType()->isReferenceType()) {
7761 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007762 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007763 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007764 return false;
7765 }
7766
Richard Smith7525ff62013-05-09 07:14:00 +00007767 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7768 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007769 EStatus.HasSideEffects)
7770 return false;
7771
7772 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7773 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007774}
7775
Richard Smith7b553f12011-10-29 00:50:52 +00007776/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7777/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007778bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007779 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007780 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007781}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007782
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007783APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007784 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007785 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007786 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007787 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007788 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007789 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007790 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007791
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007792 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007793}
John McCall864e3962010-05-07 05:32:02 +00007794
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007795void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7796 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7797 bool IsConst;
7798 EvalResult EvalResult;
7799 EvalResult.Diag = Diags;
7800 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7801 EvalInfo Info(Ctx, EvalResult, true);
7802 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7803 }
7804}
7805
Richard Smithe6c01442013-06-05 00:46:14 +00007806bool Expr::EvalResult::isGlobalLValue() const {
7807 assert(Val.isLValue());
7808 return IsGlobalLValue(Val.getLValueBase());
7809}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007810
7811
John McCall864e3962010-05-07 05:32:02 +00007812/// isIntegerConstantExpr - this recursive routine will test if an expression is
7813/// an integer constant expression.
7814
7815/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7816/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007817
7818// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007819// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7820// and a (possibly null) SourceLocation indicating the location of the problem.
7821//
John McCall864e3962010-05-07 05:32:02 +00007822// Note that to reduce code duplication, this helper does no evaluation
7823// itself; the caller checks whether the expression is evaluatable, and
7824// in the rare cases where CheckICE actually cares about the evaluated
7825// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007826
Dan Gohman28ade552010-07-26 21:25:24 +00007827namespace {
7828
Richard Smith9e575da2012-12-28 13:25:52 +00007829enum ICEKind {
7830 /// This expression is an ICE.
7831 IK_ICE,
7832 /// This expression is not an ICE, but if it isn't evaluated, it's
7833 /// a legal subexpression for an ICE. This return value is used to handle
7834 /// the comma operator in C99 mode, and non-constant subexpressions.
7835 IK_ICEIfUnevaluated,
7836 /// This expression is not an ICE, and is not a legal subexpression for one.
7837 IK_NotICE
7838};
7839
John McCall864e3962010-05-07 05:32:02 +00007840struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007841 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007842 SourceLocation Loc;
7843
Richard Smith9e575da2012-12-28 13:25:52 +00007844 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007845};
7846
Dan Gohman28ade552010-07-26 21:25:24 +00007847}
7848
Richard Smith9e575da2012-12-28 13:25:52 +00007849static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7850
7851static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007852
7853static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7854 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007855 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007856 !EVResult.Val.isInt())
7857 return ICEDiag(IK_NotICE, E->getLocStart());
7858
John McCall864e3962010-05-07 05:32:02 +00007859 return NoDiag();
7860}
7861
7862static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7863 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007864 if (!E->getType()->isIntegralOrEnumerationType())
7865 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007866
7867 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007868#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007869#define STMT(Node, Base) case Expr::Node##Class:
7870#define EXPR(Node, Base)
7871#include "clang/AST/StmtNodes.inc"
7872 case Expr::PredefinedExprClass:
7873 case Expr::FloatingLiteralClass:
7874 case Expr::ImaginaryLiteralClass:
7875 case Expr::StringLiteralClass:
7876 case Expr::ArraySubscriptExprClass:
7877 case Expr::MemberExprClass:
7878 case Expr::CompoundAssignOperatorClass:
7879 case Expr::CompoundLiteralExprClass:
7880 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007881 case Expr::DesignatedInitExprClass:
7882 case Expr::ImplicitValueInitExprClass:
7883 case Expr::ParenListExprClass:
7884 case Expr::VAArgExprClass:
7885 case Expr::AddrLabelExprClass:
7886 case Expr::StmtExprClass:
7887 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007888 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007889 case Expr::CXXDynamicCastExprClass:
7890 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007891 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007892 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007893 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007894 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007895 case Expr::CXXThisExprClass:
7896 case Expr::CXXThrowExprClass:
7897 case Expr::CXXNewExprClass:
7898 case Expr::CXXDeleteExprClass:
7899 case Expr::CXXPseudoDestructorExprClass:
7900 case Expr::UnresolvedLookupExprClass:
7901 case Expr::DependentScopeDeclRefExprClass:
7902 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00007903 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00007904 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007905 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007906 case Expr::CXXTemporaryObjectExprClass:
7907 case Expr::CXXUnresolvedConstructExprClass:
7908 case Expr::CXXDependentScopeMemberExprClass:
7909 case Expr::UnresolvedMemberExprClass:
7910 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007911 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007912 case Expr::ObjCArrayLiteralClass:
7913 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007914 case Expr::ObjCEncodeExprClass:
7915 case Expr::ObjCMessageExprClass:
7916 case Expr::ObjCSelectorExprClass:
7917 case Expr::ObjCProtocolExprClass:
7918 case Expr::ObjCIvarRefExprClass:
7919 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007920 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007921 case Expr::ObjCIsaExprClass:
7922 case Expr::ShuffleVectorExprClass:
7923 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007924 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007925 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007926 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007927 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007928 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007929 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007930 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007931 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007932 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007933 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007934 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007935 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007936 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007937
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007938 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007939 case Expr::GNUNullExprClass:
7940 // GCC considers the GNU __null value to be an integral constant expression.
7941 return NoDiag();
7942
John McCall7c454bb2011-07-15 05:09:51 +00007943 case Expr::SubstNonTypeTemplateParmExprClass:
7944 return
7945 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7946
John McCall864e3962010-05-07 05:32:02 +00007947 case Expr::ParenExprClass:
7948 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007949 case Expr::GenericSelectionExprClass:
7950 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007951 case Expr::IntegerLiteralClass:
7952 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007953 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007954 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007955 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007956 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007957 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007958 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007959 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007960 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007961 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007962 return NoDiag();
7963 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007964 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007965 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7966 // constant expressions, but they can never be ICEs because an ICE cannot
7967 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007968 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007969 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007970 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007971 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007972 }
Richard Smith6365c912012-02-24 22:12:32 +00007973 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007974 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7975 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007976 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007977 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007978 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007979 // Parameter variables are never constants. Without this check,
7980 // getAnyInitializer() can find a default argument, which leads
7981 // to chaos.
7982 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007983 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007984
7985 // C++ 7.1.5.1p2
7986 // A variable of non-volatile const-qualified integral or enumeration
7987 // type initialized by an ICE can be used in ICEs.
7988 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007989 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007990 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007991
Richard Smithd0b4dd62011-12-19 06:19:21 +00007992 const VarDecl *VD;
7993 // Look for a declaration of this variable that has an initializer, and
7994 // check whether it is an ICE.
7995 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7996 return NoDiag();
7997 else
Richard Smith9e575da2012-12-28 13:25:52 +00007998 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007999 }
8000 }
Richard Smith9e575da2012-12-28 13:25:52 +00008001 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008002 }
John McCall864e3962010-05-07 05:32:02 +00008003 case Expr::UnaryOperatorClass: {
8004 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8005 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008006 case UO_PostInc:
8007 case UO_PostDec:
8008 case UO_PreInc:
8009 case UO_PreDec:
8010 case UO_AddrOf:
8011 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008012 // C99 6.6/3 allows increment and decrement within unevaluated
8013 // subexpressions of constant expressions, but they can never be ICEs
8014 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008015 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008016 case UO_Extension:
8017 case UO_LNot:
8018 case UO_Plus:
8019 case UO_Minus:
8020 case UO_Not:
8021 case UO_Real:
8022 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008023 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008024 }
Richard Smith9e575da2012-12-28 13:25:52 +00008025
John McCall864e3962010-05-07 05:32:02 +00008026 // OffsetOf falls through here.
8027 }
8028 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008029 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8030 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8031 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8032 // compliance: we should warn earlier for offsetof expressions with
8033 // array subscripts that aren't ICEs, and if the array subscripts
8034 // are ICEs, the value of the offsetof must be an integer constant.
8035 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008036 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008037 case Expr::UnaryExprOrTypeTraitExprClass: {
8038 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8039 if ((Exp->getKind() == UETT_SizeOf) &&
8040 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008041 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008042 return NoDiag();
8043 }
8044 case Expr::BinaryOperatorClass: {
8045 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8046 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008047 case BO_PtrMemD:
8048 case BO_PtrMemI:
8049 case BO_Assign:
8050 case BO_MulAssign:
8051 case BO_DivAssign:
8052 case BO_RemAssign:
8053 case BO_AddAssign:
8054 case BO_SubAssign:
8055 case BO_ShlAssign:
8056 case BO_ShrAssign:
8057 case BO_AndAssign:
8058 case BO_XorAssign:
8059 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008060 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8061 // constant expressions, but they can never be ICEs because an ICE cannot
8062 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008063 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008064
John McCalle3027922010-08-25 11:45:40 +00008065 case BO_Mul:
8066 case BO_Div:
8067 case BO_Rem:
8068 case BO_Add:
8069 case BO_Sub:
8070 case BO_Shl:
8071 case BO_Shr:
8072 case BO_LT:
8073 case BO_GT:
8074 case BO_LE:
8075 case BO_GE:
8076 case BO_EQ:
8077 case BO_NE:
8078 case BO_And:
8079 case BO_Xor:
8080 case BO_Or:
8081 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008082 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8083 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008084 if (Exp->getOpcode() == BO_Div ||
8085 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008086 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008087 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008088 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008089 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008090 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008091 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008092 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008093 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008094 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008095 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008096 }
8097 }
8098 }
John McCalle3027922010-08-25 11:45:40 +00008099 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008100 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008101 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8102 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008103 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8104 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008105 } else {
8106 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008107 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008108 }
8109 }
Richard Smith9e575da2012-12-28 13:25:52 +00008110 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008111 }
John McCalle3027922010-08-25 11:45:40 +00008112 case BO_LAnd:
8113 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008114 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8115 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008116 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008117 // Rare case where the RHS has a comma "side-effect"; we need
8118 // to actually check the condition to see whether the side
8119 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008120 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008121 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008122 return RHSResult;
8123 return NoDiag();
8124 }
8125
Richard Smith9e575da2012-12-28 13:25:52 +00008126 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008127 }
8128 }
8129 }
8130 case Expr::ImplicitCastExprClass:
8131 case Expr::CStyleCastExprClass:
8132 case Expr::CXXFunctionalCastExprClass:
8133 case Expr::CXXStaticCastExprClass:
8134 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008135 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008136 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008137 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008138 if (isa<ExplicitCastExpr>(E)) {
8139 if (const FloatingLiteral *FL
8140 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8141 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8142 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8143 APSInt IgnoredVal(DestWidth, !DestSigned);
8144 bool Ignored;
8145 // If the value does not fit in the destination type, the behavior is
8146 // undefined, so we are not required to treat it as a constant
8147 // expression.
8148 if (FL->getValue().convertToInteger(IgnoredVal,
8149 llvm::APFloat::rmTowardZero,
8150 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008151 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008152 return NoDiag();
8153 }
8154 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008155 switch (cast<CastExpr>(E)->getCastKind()) {
8156 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008157 case CK_AtomicToNonAtomic:
8158 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008159 case CK_NoOp:
8160 case CK_IntegralToBoolean:
8161 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008162 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008163 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008164 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008165 }
John McCall864e3962010-05-07 05:32:02 +00008166 }
John McCallc07a0c72011-02-17 10:25:35 +00008167 case Expr::BinaryConditionalOperatorClass: {
8168 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8169 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008170 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008171 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008172 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8173 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8174 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008175 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008176 return FalseResult;
8177 }
John McCall864e3962010-05-07 05:32:02 +00008178 case Expr::ConditionalOperatorClass: {
8179 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8180 // If the condition (ignoring parens) is a __builtin_constant_p call,
8181 // then only the true side is actually considered in an integer constant
8182 // expression, and it is fully evaluated. This is an important GNU
8183 // extension. See GCC PR38377 for discussion.
8184 if (const CallExpr *CallCE
8185 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008186 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8187 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008188 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008189 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008190 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008191
Richard Smithf57d8cb2011-12-09 22:58:01 +00008192 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8193 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008194
Richard Smith9e575da2012-12-28 13:25:52 +00008195 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008196 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008197 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008198 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008199 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008200 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008201 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008202 return NoDiag();
8203 // Rare case where the diagnostics depend on which side is evaluated
8204 // Note that if we get here, CondResult is 0, and at least one of
8205 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008206 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008207 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008208 return TrueResult;
8209 }
8210 case Expr::CXXDefaultArgExprClass:
8211 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008212 case Expr::CXXDefaultInitExprClass:
8213 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008214 case Expr::ChooseExprClass: {
8215 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
8216 }
8217 }
8218
David Blaikiee4d798f2012-01-20 21:50:17 +00008219 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008220}
8221
Richard Smithf57d8cb2011-12-09 22:58:01 +00008222/// Evaluate an expression as a C++11 integral constant expression.
8223static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8224 const Expr *E,
8225 llvm::APSInt *Value,
8226 SourceLocation *Loc) {
8227 if (!E->getType()->isIntegralOrEnumerationType()) {
8228 if (Loc) *Loc = E->getExprLoc();
8229 return false;
8230 }
8231
Richard Smith66e05fe2012-01-18 05:21:49 +00008232 APValue Result;
8233 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008234 return false;
8235
Richard Smith66e05fe2012-01-18 05:21:49 +00008236 assert(Result.isInt() && "pointer cast to int is not an ICE");
8237 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008238 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008239}
8240
Richard Smith92b1ce02011-12-12 09:28:41 +00008241bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008242 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008243 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8244
Richard Smith9e575da2012-12-28 13:25:52 +00008245 ICEDiag D = CheckICE(this, Ctx);
8246 if (D.Kind != IK_ICE) {
8247 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008248 return false;
8249 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008250 return true;
8251}
8252
8253bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8254 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008255 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008256 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8257
8258 if (!isIntegerConstantExpr(Ctx, Loc))
8259 return false;
8260 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008261 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008262 return true;
8263}
Richard Smith66e05fe2012-01-18 05:21:49 +00008264
Richard Smith98a0a492012-02-14 21:38:30 +00008265bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008266 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008267}
8268
Richard Smith66e05fe2012-01-18 05:21:49 +00008269bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8270 SourceLocation *Loc) const {
8271 // We support this checking in C++98 mode in order to diagnose compatibility
8272 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008273 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008274
Richard Smith98a0a492012-02-14 21:38:30 +00008275 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008276 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008277 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008278 Status.Diag = &Diags;
8279 EvalInfo Info(Ctx, Status);
8280
8281 APValue Scratch;
8282 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8283
8284 if (!Diags.empty()) {
8285 IsConstExpr = false;
8286 if (Loc) *Loc = Diags[0].first;
8287 } else if (!IsConstExpr) {
8288 // FIXME: This shouldn't happen.
8289 if (Loc) *Loc = getExprLoc();
8290 }
8291
8292 return IsConstExpr;
8293}
Richard Smith253c2a32012-01-27 01:14:48 +00008294
8295bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008296 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008297 PartialDiagnosticAt> &Diags) {
8298 // FIXME: It would be useful to check constexpr function templates, but at the
8299 // moment the constant expression evaluator cannot cope with the non-rigorous
8300 // ASTs which we build for dependent expressions.
8301 if (FD->isDependentContext())
8302 return true;
8303
8304 Expr::EvalStatus Status;
8305 Status.Diag = &Diags;
8306
8307 EvalInfo Info(FD->getASTContext(), Status);
8308 Info.CheckingPotentialConstantExpression = true;
8309
8310 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8311 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8312
Richard Smith7525ff62013-05-09 07:14:00 +00008313 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008314 // is a temporary being used as the 'this' pointer.
8315 LValue This;
8316 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008317 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008318
Richard Smith253c2a32012-01-27 01:14:48 +00008319 ArrayRef<const Expr*> Args;
8320
8321 SourceLocation Loc = FD->getLocation();
8322
Richard Smith2e312c82012-03-03 22:46:17 +00008323 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008324 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8325 // Evaluate the call as a constant initializer, to allow the construction
8326 // of objects of non-literal types.
8327 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008328 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008329 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008330 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8331 Args, FD->getBody(), Info, Scratch);
8332
8333 return Diags.empty();
8334}