blob: 28473f0bdbd8969a64300c4cc2bd1a0d402ed778 [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()) {
Richard Smith51f03172013-06-20 03:00:05 +00001136 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1137 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001138 return false;
1139 }
1140
Richard Smithb228a862012-02-15 02:18:13 +00001141 // Core issue 1454: For a literal constant expression of array or class type,
1142 // each subobject of its value shall have been initialized by a constant
1143 // expression.
1144 if (Value.isArray()) {
1145 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1146 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1147 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1148 Value.getArrayInitializedElt(I)))
1149 return false;
1150 }
1151 if (!Value.hasArrayFiller())
1152 return true;
1153 return CheckConstantExpression(Info, DiagLoc, EltTy,
1154 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001155 }
Richard Smithb228a862012-02-15 02:18:13 +00001156 if (Value.isUnion() && Value.getUnionField()) {
1157 return CheckConstantExpression(Info, DiagLoc,
1158 Value.getUnionField()->getType(),
1159 Value.getUnionValue());
1160 }
1161 if (Value.isStruct()) {
1162 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1163 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1164 unsigned BaseIndex = 0;
1165 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1166 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1167 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1168 Value.getStructBase(BaseIndex)))
1169 return false;
1170 }
1171 }
1172 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1173 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001174 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1175 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001176 return false;
1177 }
1178 }
1179
1180 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001181 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001182 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001183 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1184 }
1185
1186 // Everything else is fine.
1187 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001188}
1189
Richard Smith83c68212011-10-31 05:11:32 +00001190const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001191 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001192}
1193
1194static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001195 if (Value.CallIndex)
1196 return false;
1197 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1198 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001199}
1200
Richard Smithcecf1842011-11-01 21:06:14 +00001201static bool IsWeakLValue(const LValue &Value) {
1202 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001203 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001204}
1205
Richard Smith2e312c82012-03-03 22:46:17 +00001206static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001207 // A null base expression indicates a null pointer. These are always
1208 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001209 if (!Value.getLValueBase()) {
1210 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001211 return true;
1212 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001213
Richard Smith027bf112011-11-17 22:56:20 +00001214 // We have a non-null base. These are generally known to be true, but if it's
1215 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001216 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001217 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001218 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001219}
1220
Richard Smith2e312c82012-03-03 22:46:17 +00001221static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001222 switch (Val.getKind()) {
1223 case APValue::Uninitialized:
1224 return false;
1225 case APValue::Int:
1226 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001227 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001228 case APValue::Float:
1229 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001230 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001231 case APValue::ComplexInt:
1232 Result = Val.getComplexIntReal().getBoolValue() ||
1233 Val.getComplexIntImag().getBoolValue();
1234 return true;
1235 case APValue::ComplexFloat:
1236 Result = !Val.getComplexFloatReal().isZero() ||
1237 !Val.getComplexFloatImag().isZero();
1238 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001239 case APValue::LValue:
1240 return EvalPointerValueAsBool(Val, Result);
1241 case APValue::MemberPointer:
1242 Result = Val.getMemberPointerDecl();
1243 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001244 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001245 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001246 case APValue::Struct:
1247 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001248 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001249 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001250 }
1251
Richard Smith11562c52011-10-28 17:51:58 +00001252 llvm_unreachable("unknown APValue kind");
1253}
1254
1255static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1256 EvalInfo &Info) {
1257 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001258 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001259 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001260 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001261 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001262}
1263
Richard Smith357362d2011-12-13 06:39:58 +00001264template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001265static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001266 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001267 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001268 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001269}
1270
1271static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1272 QualType SrcType, const APFloat &Value,
1273 QualType DestType, APSInt &Result) {
1274 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001275 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001276 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001277
Richard Smith357362d2011-12-13 06:39:58 +00001278 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001279 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001280 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1281 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001282 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001283 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001284}
1285
Richard Smith357362d2011-12-13 06:39:58 +00001286static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1287 QualType SrcType, QualType DestType,
1288 APFloat &Result) {
1289 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001290 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001291 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1292 APFloat::rmNearestTiesToEven, &ignored)
1293 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001294 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001295 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001296}
1297
Richard Smith911e1422012-01-30 22:27:01 +00001298static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1299 QualType DestType, QualType SrcType,
1300 APSInt &Value) {
1301 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001302 APSInt Result = Value;
1303 // Figure out if this is a truncate, extend or noop cast.
1304 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001305 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001306 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001307 return Result;
1308}
1309
Richard Smith357362d2011-12-13 06:39:58 +00001310static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1311 QualType SrcType, const APSInt &Value,
1312 QualType DestType, APFloat &Result) {
1313 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1314 if (Result.convertFromAPInt(Value, Value.isSigned(),
1315 APFloat::rmNearestTiesToEven)
1316 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001317 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001318 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001319}
1320
Eli Friedman803acb32011-12-22 03:51:45 +00001321static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1322 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001323 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001324 if (!Evaluate(SVal, Info, E))
1325 return false;
1326 if (SVal.isInt()) {
1327 Res = SVal.getInt();
1328 return true;
1329 }
1330 if (SVal.isFloat()) {
1331 Res = SVal.getFloat().bitcastToAPInt();
1332 return true;
1333 }
1334 if (SVal.isVector()) {
1335 QualType VecTy = E->getType();
1336 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1337 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1338 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1339 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1340 Res = llvm::APInt::getNullValue(VecSize);
1341 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1342 APValue &Elt = SVal.getVectorElt(i);
1343 llvm::APInt EltAsInt;
1344 if (Elt.isInt()) {
1345 EltAsInt = Elt.getInt();
1346 } else if (Elt.isFloat()) {
1347 EltAsInt = Elt.getFloat().bitcastToAPInt();
1348 } else {
1349 // Don't try to handle vectors of anything other than int or float
1350 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001351 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001352 return false;
1353 }
1354 unsigned BaseEltSize = EltAsInt.getBitWidth();
1355 if (BigEndian)
1356 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1357 else
1358 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1359 }
1360 return true;
1361 }
1362 // Give up if the input isn't an int, float, or vector. For example, we
1363 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001364 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001365 return false;
1366}
1367
Richard Smith43e77732013-05-07 04:50:00 +00001368/// Perform the given integer operation, which is known to need at most BitWidth
1369/// bits, and check for overflow in the original type (if that type was not an
1370/// unsigned type).
1371template<typename Operation>
1372static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1373 const APSInt &LHS, const APSInt &RHS,
1374 unsigned BitWidth, Operation Op) {
1375 if (LHS.isUnsigned())
1376 return Op(LHS, RHS);
1377
1378 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1379 APSInt Result = Value.trunc(LHS.getBitWidth());
1380 if (Result.extend(BitWidth) != Value) {
1381 if (Info.getIntOverflowCheckMode())
1382 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1383 diag::warn_integer_constant_overflow)
1384 << Result.toString(10) << E->getType();
1385 else
1386 HandleOverflow(Info, E, Value, E->getType());
1387 }
1388 return Result;
1389}
1390
1391/// Perform the given binary integer operation.
1392static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1393 BinaryOperatorKind Opcode, APSInt RHS,
1394 APSInt &Result) {
1395 switch (Opcode) {
1396 default:
1397 Info.Diag(E);
1398 return false;
1399 case BO_Mul:
1400 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1401 std::multiplies<APSInt>());
1402 return true;
1403 case BO_Add:
1404 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1405 std::plus<APSInt>());
1406 return true;
1407 case BO_Sub:
1408 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1409 std::minus<APSInt>());
1410 return true;
1411 case BO_And: Result = LHS & RHS; return true;
1412 case BO_Xor: Result = LHS ^ RHS; return true;
1413 case BO_Or: Result = LHS | RHS; return true;
1414 case BO_Div:
1415 case BO_Rem:
1416 if (RHS == 0) {
1417 Info.Diag(E, diag::note_expr_divide_by_zero);
1418 return false;
1419 }
1420 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1421 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1422 LHS.isSigned() && LHS.isMinSignedValue())
1423 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1424 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1425 return true;
1426 case BO_Shl: {
1427 if (Info.getLangOpts().OpenCL)
1428 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1429 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1430 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1431 RHS.isUnsigned());
1432 else if (RHS.isSigned() && RHS.isNegative()) {
1433 // During constant-folding, a negative shift is an opposite shift. Such
1434 // a shift is not a constant expression.
1435 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1436 RHS = -RHS;
1437 goto shift_right;
1438 }
1439 shift_left:
1440 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1441 // the shifted type.
1442 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1443 if (SA != RHS) {
1444 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1445 << RHS << E->getType() << LHS.getBitWidth();
1446 } else if (LHS.isSigned()) {
1447 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1448 // operand, and must not overflow the corresponding unsigned type.
1449 if (LHS.isNegative())
1450 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1451 else if (LHS.countLeadingZeros() < SA)
1452 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1453 }
1454 Result = LHS << SA;
1455 return true;
1456 }
1457 case BO_Shr: {
1458 if (Info.getLangOpts().OpenCL)
1459 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1460 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1461 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1462 RHS.isUnsigned());
1463 else if (RHS.isSigned() && RHS.isNegative()) {
1464 // During constant-folding, a negative shift is an opposite shift. Such a
1465 // shift is not a constant expression.
1466 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1467 RHS = -RHS;
1468 goto shift_left;
1469 }
1470 shift_right:
1471 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1472 // shifted type.
1473 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1474 if (SA != RHS)
1475 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1476 << RHS << E->getType() << LHS.getBitWidth();
1477 Result = LHS >> SA;
1478 return true;
1479 }
1480
1481 case BO_LT: Result = LHS < RHS; return true;
1482 case BO_GT: Result = LHS > RHS; return true;
1483 case BO_LE: Result = LHS <= RHS; return true;
1484 case BO_GE: Result = LHS >= RHS; return true;
1485 case BO_EQ: Result = LHS == RHS; return true;
1486 case BO_NE: Result = LHS != RHS; return true;
1487 }
1488}
1489
Richard Smith861b5b52013-05-07 23:34:45 +00001490/// Perform the given binary floating-point operation, in-place, on LHS.
1491static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1492 APFloat &LHS, BinaryOperatorKind Opcode,
1493 const APFloat &RHS) {
1494 switch (Opcode) {
1495 default:
1496 Info.Diag(E);
1497 return false;
1498 case BO_Mul:
1499 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1500 break;
1501 case BO_Add:
1502 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1503 break;
1504 case BO_Sub:
1505 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1506 break;
1507 case BO_Div:
1508 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1509 break;
1510 }
1511
1512 if (LHS.isInfinity() || LHS.isNaN())
1513 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1514 return true;
1515}
1516
Richard Smitha8105bc2012-01-06 16:39:00 +00001517/// Cast an lvalue referring to a base subobject to a derived class, by
1518/// truncating the lvalue's path to the given length.
1519static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1520 const RecordDecl *TruncatedType,
1521 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001522 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001523
1524 // Check we actually point to a derived class object.
1525 if (TruncatedElements == D.Entries.size())
1526 return true;
1527 assert(TruncatedElements >= D.MostDerivedPathLength &&
1528 "not casting to a derived class");
1529 if (!Result.checkSubobject(Info, E, CSK_Derived))
1530 return false;
1531
1532 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001533 const RecordDecl *RD = TruncatedType;
1534 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001535 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001536 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1537 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001538 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001539 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001540 else
Richard Smithd62306a2011-11-10 06:34:14 +00001541 Result.Offset -= Layout.getBaseClassOffset(Base);
1542 RD = Base;
1543 }
Richard Smith027bf112011-11-17 22:56:20 +00001544 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001545 return true;
1546}
1547
John McCalld7bca762012-05-01 00:38:49 +00001548static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001549 const CXXRecordDecl *Derived,
1550 const CXXRecordDecl *Base,
1551 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001552 if (!RL) {
1553 if (Derived->isInvalidDecl()) return false;
1554 RL = &Info.Ctx.getASTRecordLayout(Derived);
1555 }
1556
Richard Smithd62306a2011-11-10 06:34:14 +00001557 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001558 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001559 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001560}
1561
Richard Smitha8105bc2012-01-06 16:39:00 +00001562static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001563 const CXXRecordDecl *DerivedDecl,
1564 const CXXBaseSpecifier *Base) {
1565 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1566
John McCalld7bca762012-05-01 00:38:49 +00001567 if (!Base->isVirtual())
1568 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001569
Richard Smitha8105bc2012-01-06 16:39:00 +00001570 SubobjectDesignator &D = Obj.Designator;
1571 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001572 return false;
1573
Richard Smitha8105bc2012-01-06 16:39:00 +00001574 // Extract most-derived object and corresponding type.
1575 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1576 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1577 return false;
1578
1579 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001580 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001581 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1582 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001583 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001584 return true;
1585}
1586
Richard Smith84401042013-06-03 05:03:02 +00001587static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1588 QualType Type, LValue &Result) {
1589 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1590 PathE = E->path_end();
1591 PathI != PathE; ++PathI) {
1592 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1593 *PathI))
1594 return false;
1595 Type = (*PathI)->getType();
1596 }
1597 return true;
1598}
1599
Richard Smithd62306a2011-11-10 06:34:14 +00001600/// Update LVal to refer to the given field, which must be a member of the type
1601/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001602static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001603 const FieldDecl *FD,
1604 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001605 if (!RL) {
1606 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001607 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001608 }
Richard Smithd62306a2011-11-10 06:34:14 +00001609
1610 unsigned I = FD->getFieldIndex();
1611 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001612 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001613 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001614}
1615
Richard Smith1b78b3d2012-01-25 22:15:11 +00001616/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001617static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001618 LValue &LVal,
1619 const IndirectFieldDecl *IFD) {
1620 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1621 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001622 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1623 return false;
1624 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001625}
1626
Richard Smithd62306a2011-11-10 06:34:14 +00001627/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001628static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1629 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001630 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1631 // extension.
1632 if (Type->isVoidType() || Type->isFunctionType()) {
1633 Size = CharUnits::One();
1634 return true;
1635 }
1636
1637 if (!Type->isConstantSizeType()) {
1638 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001639 // FIXME: Better diagnostic.
1640 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001641 return false;
1642 }
1643
1644 Size = Info.Ctx.getTypeSizeInChars(Type);
1645 return true;
1646}
1647
1648/// Update a pointer value to model pointer arithmetic.
1649/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001650/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001651/// \param LVal - The pointer value to be updated.
1652/// \param EltTy - The pointee type represented by LVal.
1653/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001654static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1655 LValue &LVal, QualType EltTy,
1656 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001657 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001658 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001659 return false;
1660
1661 // Compute the new offset in the appropriate width.
1662 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001663 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001664 return true;
1665}
1666
Richard Smith66c96992012-02-18 22:04:06 +00001667/// Update an lvalue to refer to a component of a complex number.
1668/// \param Info - Information about the ongoing evaluation.
1669/// \param LVal - The lvalue to be updated.
1670/// \param EltTy - The complex number's component type.
1671/// \param Imag - False for the real component, true for the imaginary.
1672static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1673 LValue &LVal, QualType EltTy,
1674 bool Imag) {
1675 if (Imag) {
1676 CharUnits SizeOfComponent;
1677 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1678 return false;
1679 LVal.Offset += SizeOfComponent;
1680 }
1681 LVal.addComplex(Info, E, EltTy, Imag);
1682 return true;
1683}
1684
Richard Smith27908702011-10-24 17:54:18 +00001685/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001686///
1687/// \param Info Information about the ongoing evaluation.
1688/// \param E An expression to be used when printing diagnostics.
1689/// \param VD The variable whose initializer should be obtained.
1690/// \param Frame The frame in which the variable was created. Must be null
1691/// if this variable is not local to the evaluation.
1692/// \param Result Filled in with a pointer to the value of the variable.
1693static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1694 const VarDecl *VD, CallStackFrame *Frame,
1695 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001696 // If this is a parameter to an active constexpr function call, perform
1697 // argument substitution.
1698 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001699 // Assume arguments of a potential constant expression are unknown
1700 // constant expressions.
1701 if (Info.CheckingPotentialConstantExpression)
1702 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001703 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001704 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001705 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001706 }
Richard Smith3229b742013-05-05 21:17:10 +00001707 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001708 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001709 }
Richard Smith27908702011-10-24 17:54:18 +00001710
Richard Smithd9f663b2013-04-22 15:31:51 +00001711 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001712 if (Frame) {
1713 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001714 // If we've carried on past an unevaluatable local variable initializer,
1715 // we can't go any further. This can happen during potential constant
1716 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001717 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001718 }
1719
Richard Smithd0b4dd62011-12-19 06:19:21 +00001720 // Dig out the initializer, and use the declaration which it's attached to.
1721 const Expr *Init = VD->getAnyInitializer(VD);
1722 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001723 // If we're checking a potential constant expression, the variable could be
1724 // initialized later.
1725 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001726 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001727 return false;
1728 }
1729
Richard Smithd62306a2011-11-10 06:34:14 +00001730 // If we're currently evaluating the initializer of this declaration, use that
1731 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001732 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001733 Result = Info.EvaluatingDeclValue;
1734 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001735 }
1736
Richard Smithcecf1842011-11-01 21:06:14 +00001737 // Never evaluate the initializer of a weak variable. We can't be sure that
1738 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001739 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001740 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001741 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001742 }
Richard Smithcecf1842011-11-01 21:06:14 +00001743
Richard Smithd0b4dd62011-12-19 06:19:21 +00001744 // Check that we can fold the initializer. In C++, we will have already done
1745 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001746 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001747 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001748 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001749 Notes.size() + 1) << VD;
1750 Info.Note(VD->getLocation(), diag::note_declared_at);
1751 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001752 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001753 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001754 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001755 Notes.size() + 1) << VD;
1756 Info.Note(VD->getLocation(), diag::note_declared_at);
1757 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001758 }
Richard Smith27908702011-10-24 17:54:18 +00001759
Richard Smith3229b742013-05-05 21:17:10 +00001760 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001761 return true;
Richard Smith27908702011-10-24 17:54:18 +00001762}
1763
Richard Smith11562c52011-10-28 17:51:58 +00001764static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001765 Qualifiers Quals = T.getQualifiers();
1766 return Quals.hasConst() && !Quals.hasVolatile();
1767}
1768
Richard Smithe97cbd72011-11-11 04:05:33 +00001769/// Get the base index of the given base class within an APValue representing
1770/// the given derived class.
1771static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1772 const CXXRecordDecl *Base) {
1773 Base = Base->getCanonicalDecl();
1774 unsigned Index = 0;
1775 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1776 E = Derived->bases_end(); I != E; ++I, ++Index) {
1777 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1778 return Index;
1779 }
1780
1781 llvm_unreachable("base class missing from derived class's bases list");
1782}
1783
Richard Smith3da88fa2013-04-26 14:36:30 +00001784/// Extract the value of a character from a string literal.
1785static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1786 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001787 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001788 const StringLiteral *S = cast<StringLiteral>(Lit);
1789 const ConstantArrayType *CAT =
1790 Info.Ctx.getAsConstantArrayType(S->getType());
1791 assert(CAT && "string literal isn't an array");
1792 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001793 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001794
1795 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001796 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001797 if (Index < S->getLength())
1798 Value = S->getCodeUnit(Index);
1799 return Value;
1800}
1801
Richard Smith3da88fa2013-04-26 14:36:30 +00001802// Expand a string literal into an array of characters.
1803static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1804 APValue &Result) {
1805 const StringLiteral *S = cast<StringLiteral>(Lit);
1806 const ConstantArrayType *CAT =
1807 Info.Ctx.getAsConstantArrayType(S->getType());
1808 assert(CAT && "string literal isn't an array");
1809 QualType CharType = CAT->getElementType();
1810 assert(CharType->isIntegerType() && "unexpected character type");
1811
1812 unsigned Elts = CAT->getSize().getZExtValue();
1813 Result = APValue(APValue::UninitArray(),
1814 std::min(S->getLength(), Elts), Elts);
1815 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1816 CharType->isUnsignedIntegerType());
1817 if (Result.hasArrayFiller())
1818 Result.getArrayFiller() = APValue(Value);
1819 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1820 Value = S->getCodeUnit(I);
1821 Result.getArrayInitializedElt(I) = APValue(Value);
1822 }
1823}
1824
1825// Expand an array so that it has more than Index filled elements.
1826static void expandArray(APValue &Array, unsigned Index) {
1827 unsigned Size = Array.getArraySize();
1828 assert(Index < Size);
1829
1830 // Always at least double the number of elements for which we store a value.
1831 unsigned OldElts = Array.getArrayInitializedElts();
1832 unsigned NewElts = std::max(Index+1, OldElts * 2);
1833 NewElts = std::min(Size, std::max(NewElts, 8u));
1834
1835 // Copy the data across.
1836 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1837 for (unsigned I = 0; I != OldElts; ++I)
1838 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1839 for (unsigned I = OldElts; I != NewElts; ++I)
1840 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1841 if (NewValue.hasArrayFiller())
1842 NewValue.getArrayFiller() = Array.getArrayFiller();
1843 Array.swap(NewValue);
1844}
1845
Richard Smith861b5b52013-05-07 23:34:45 +00001846/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001847enum AccessKinds {
1848 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001849 AK_Assign,
1850 AK_Increment,
1851 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001852};
1853
Richard Smith3229b742013-05-05 21:17:10 +00001854/// A handle to a complete object (an object that is not a subobject of
1855/// another object).
1856struct CompleteObject {
1857 /// The value of the complete object.
1858 APValue *Value;
1859 /// The type of the complete object.
1860 QualType Type;
1861
1862 CompleteObject() : Value(0) {}
1863 CompleteObject(APValue *Value, QualType Type)
1864 : Value(Value), Type(Type) {
1865 assert(Value && "missing value for complete object");
1866 }
1867
David Blaikie7d170102013-05-15 07:37:26 +00001868 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001869};
1870
Richard Smith3da88fa2013-04-26 14:36:30 +00001871/// Find the designated sub-object of an rvalue.
1872template<typename SubobjectHandler>
1873typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001874findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001875 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001876 if (Sub.Invalid)
1877 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001878 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001879 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001880 if (Info.getLangOpts().CPlusPlus11)
1881 Info.Diag(E, diag::note_constexpr_access_past_end)
1882 << handler.AccessKind;
1883 else
1884 Info.Diag(E);
1885 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001886 }
Richard Smith6804be52011-11-11 08:28:03 +00001887 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001888 return handler.found(*Obj.Value, Obj.Type);
1889 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001890 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001891 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001892
Richard Smith3229b742013-05-05 21:17:10 +00001893 APValue *O = Obj.Value;
1894 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001895 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001896 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001897 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001898 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001899 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001900 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001901 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001902 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001903 // Note, it should not be possible to form a pointer with a valid
1904 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001905 if (Info.getLangOpts().CPlusPlus11)
1906 Info.Diag(E, diag::note_constexpr_access_past_end)
1907 << handler.AccessKind;
1908 else
1909 Info.Diag(E);
1910 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001911 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001912
1913 ObjType = CAT->getElementType();
1914
Richard Smith14a94132012-02-17 03:35:37 +00001915 // An array object is represented as either an Array APValue or as an
1916 // LValue which refers to a string literal.
1917 if (O->isLValue()) {
1918 assert(I == N - 1 && "extracting subobject of character?");
1919 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001920 if (handler.AccessKind != AK_Read)
1921 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1922 *O);
1923 else
1924 return handler.foundString(*O, ObjType, Index);
1925 }
1926
1927 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001928 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001929 else if (handler.AccessKind != AK_Read) {
1930 expandArray(*O, Index);
1931 O = &O->getArrayInitializedElt(Index);
1932 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001933 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001934 } else if (ObjType->isAnyComplexType()) {
1935 // Next subobject is a complex number.
1936 uint64_t Index = Sub.Entries[I].ArrayIndex;
1937 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001938 if (Info.getLangOpts().CPlusPlus11)
1939 Info.Diag(E, diag::note_constexpr_access_past_end)
1940 << handler.AccessKind;
1941 else
1942 Info.Diag(E);
1943 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001944 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001945
1946 bool WasConstQualified = ObjType.isConstQualified();
1947 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1948 if (WasConstQualified)
1949 ObjType.addConst();
1950
Richard Smith66c96992012-02-18 22:04:06 +00001951 assert(I == N - 1 && "extracting subobject of scalar?");
1952 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001953 return handler.found(Index ? O->getComplexIntImag()
1954 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001955 } else {
1956 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001957 return handler.found(Index ? O->getComplexFloatImag()
1958 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001959 }
Richard Smithd62306a2011-11-10 06:34:14 +00001960 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001962 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001963 << Field;
1964 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001965 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001966 }
1967
Richard Smithd62306a2011-11-10 06:34:14 +00001968 // Next subobject is a class, struct or union field.
1969 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1970 if (RD->isUnion()) {
1971 const FieldDecl *UnionField = O->getUnionField();
1972 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001973 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1975 << handler.AccessKind << Field << !UnionField << UnionField;
1976 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001977 }
Richard Smithd62306a2011-11-10 06:34:14 +00001978 O = &O->getUnionValue();
1979 } else
1980 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001981
1982 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001983 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001984 if (WasConstQualified && !Field->isMutable())
1985 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001986
1987 if (ObjType.isVolatileQualified()) {
1988 if (Info.getLangOpts().CPlusPlus) {
1989 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001990 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1991 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001992 Info.Note(Field->getLocation(), diag::note_declared_at);
1993 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001994 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001995 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001996 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001997 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001998 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001999 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002000 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2001 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2002 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002003
2004 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002005 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002006 if (WasConstQualified)
2007 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002008 }
Richard Smithd62306a2011-11-10 06:34:14 +00002009
Richard Smithf57d8cb2011-12-09 22:58:01 +00002010 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002011 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00002012 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2013 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002014 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002015 }
2016
Richard Smith3da88fa2013-04-26 14:36:30 +00002017 return handler.found(*O, ObjType);
2018}
2019
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002020namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002021struct ExtractSubobjectHandler {
2022 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002023 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002024
2025 static const AccessKinds AccessKind = AK_Read;
2026
2027 typedef bool result_type;
2028 bool failed() { return false; }
2029 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002030 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002031 return true;
2032 }
2033 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002034 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002035 return true;
2036 }
2037 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002038 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002039 return true;
2040 }
2041 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002042 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002043 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2044 return true;
2045 }
2046};
Richard Smith3229b742013-05-05 21:17:10 +00002047} // end anonymous namespace
2048
Richard Smith3da88fa2013-04-26 14:36:30 +00002049const AccessKinds ExtractSubobjectHandler::AccessKind;
2050
2051/// Extract the designated sub-object of an rvalue.
2052static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002053 const CompleteObject &Obj,
2054 const SubobjectDesignator &Sub,
2055 APValue &Result) {
2056 ExtractSubobjectHandler Handler = { Info, Result };
2057 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002058}
2059
Richard Smith3229b742013-05-05 21:17:10 +00002060namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002061struct ModifySubobjectHandler {
2062 EvalInfo &Info;
2063 APValue &NewVal;
2064 const Expr *E;
2065
2066 typedef bool result_type;
2067 static const AccessKinds AccessKind = AK_Assign;
2068
2069 bool checkConst(QualType QT) {
2070 // Assigning to a const object has undefined behavior.
2071 if (QT.isConstQualified()) {
2072 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2073 return false;
2074 }
2075 return true;
2076 }
2077
2078 bool failed() { return false; }
2079 bool found(APValue &Subobj, QualType SubobjType) {
2080 if (!checkConst(SubobjType))
2081 return false;
2082 // We've been given ownership of NewVal, so just swap it in.
2083 Subobj.swap(NewVal);
2084 return true;
2085 }
2086 bool found(APSInt &Value, QualType SubobjType) {
2087 if (!checkConst(SubobjType))
2088 return false;
2089 if (!NewVal.isInt()) {
2090 // Maybe trying to write a cast pointer value into a complex?
2091 Info.Diag(E);
2092 return false;
2093 }
2094 Value = NewVal.getInt();
2095 return true;
2096 }
2097 bool found(APFloat &Value, QualType SubobjType) {
2098 if (!checkConst(SubobjType))
2099 return false;
2100 Value = NewVal.getFloat();
2101 return true;
2102 }
2103 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2104 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2105 }
2106};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002107} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002108
Richard Smith3229b742013-05-05 21:17:10 +00002109const AccessKinds ModifySubobjectHandler::AccessKind;
2110
Richard Smith3da88fa2013-04-26 14:36:30 +00002111/// Update the designated sub-object of an rvalue to the given value.
2112static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002113 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002114 const SubobjectDesignator &Sub,
2115 APValue &NewVal) {
2116 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002117 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002118}
2119
Richard Smith84f6dcf2012-02-02 01:16:57 +00002120/// Find the position where two subobject designators diverge, or equivalently
2121/// the length of the common initial subsequence.
2122static unsigned FindDesignatorMismatch(QualType ObjType,
2123 const SubobjectDesignator &A,
2124 const SubobjectDesignator &B,
2125 bool &WasArrayIndex) {
2126 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2127 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002128 if (!ObjType.isNull() &&
2129 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002130 // Next subobject is an array element.
2131 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2132 WasArrayIndex = true;
2133 return I;
2134 }
Richard Smith66c96992012-02-18 22:04:06 +00002135 if (ObjType->isAnyComplexType())
2136 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2137 else
2138 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002139 } else {
2140 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2141 WasArrayIndex = false;
2142 return I;
2143 }
2144 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2145 // Next subobject is a field.
2146 ObjType = FD->getType();
2147 else
2148 // Next subobject is a base class.
2149 ObjType = QualType();
2150 }
2151 }
2152 WasArrayIndex = false;
2153 return I;
2154}
2155
2156/// Determine whether the given subobject designators refer to elements of the
2157/// same array object.
2158static bool AreElementsOfSameArray(QualType ObjType,
2159 const SubobjectDesignator &A,
2160 const SubobjectDesignator &B) {
2161 if (A.Entries.size() != B.Entries.size())
2162 return false;
2163
2164 bool IsArray = A.MostDerivedArraySize != 0;
2165 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2166 // A is a subobject of the array element.
2167 return false;
2168
2169 // If A (and B) designates an array element, the last entry will be the array
2170 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2171 // of length 1' case, and the entire path must match.
2172 bool WasArrayIndex;
2173 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2174 return CommonLength >= A.Entries.size() - IsArray;
2175}
2176
Richard Smith3229b742013-05-05 21:17:10 +00002177/// Find the complete object to which an LValue refers.
2178CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2179 const LValue &LVal, QualType LValType) {
2180 if (!LVal.Base) {
2181 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2182 return CompleteObject();
2183 }
2184
2185 CallStackFrame *Frame = 0;
2186 if (LVal.CallIndex) {
2187 Frame = Info.getCallFrame(LVal.CallIndex);
2188 if (!Frame) {
2189 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2190 << AK << LVal.Base.is<const ValueDecl*>();
2191 NoteLValueLocation(Info, LVal.Base);
2192 return CompleteObject();
2193 }
Richard Smith3229b742013-05-05 21:17:10 +00002194 }
2195
2196 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2197 // is not a constant expression (even if the object is non-volatile). We also
2198 // apply this rule to C++98, in order to conform to the expected 'volatile'
2199 // semantics.
2200 if (LValType.isVolatileQualified()) {
2201 if (Info.getLangOpts().CPlusPlus)
2202 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2203 << AK << LValType;
2204 else
2205 Info.Diag(E);
2206 return CompleteObject();
2207 }
2208
2209 // Compute value storage location and type of base object.
2210 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002211 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002212
2213 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2214 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2215 // In C++11, constexpr, non-volatile variables initialized with constant
2216 // expressions are constant expressions too. Inside constexpr functions,
2217 // parameters are constant expressions even if they're non-const.
2218 // In C++1y, objects local to a constant expression (those with a Frame) are
2219 // both readable and writable inside constant expressions.
2220 // In C, such things can also be folded, although they are not ICEs.
2221 const VarDecl *VD = dyn_cast<VarDecl>(D);
2222 if (VD) {
2223 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2224 VD = VDef;
2225 }
2226 if (!VD || VD->isInvalidDecl()) {
2227 Info.Diag(E);
2228 return CompleteObject();
2229 }
2230
2231 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002232 if (BaseType.isVolatileQualified()) {
2233 if (Info.getLangOpts().CPlusPlus) {
2234 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2235 << AK << 1 << VD;
2236 Info.Note(VD->getLocation(), diag::note_declared_at);
2237 } else {
2238 Info.Diag(E);
2239 }
2240 return CompleteObject();
2241 }
2242
2243 // Unless we're looking at a local variable or argument in a constexpr call,
2244 // the variable we're reading must be const.
2245 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002246 if (Info.getLangOpts().CPlusPlus1y &&
2247 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2248 // OK, we can read and modify an object if we're in the process of
2249 // evaluating its initializer, because its lifetime began in this
2250 // evaluation.
2251 } else if (AK != AK_Read) {
2252 // All the remaining cases only permit reading.
2253 Info.Diag(E, diag::note_constexpr_modify_global);
2254 return CompleteObject();
2255 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002256 // OK, we can read this variable.
2257 } else if (BaseType->isIntegralOrEnumerationType()) {
2258 if (!BaseType.isConstQualified()) {
2259 if (Info.getLangOpts().CPlusPlus) {
2260 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2261 Info.Note(VD->getLocation(), diag::note_declared_at);
2262 } else {
2263 Info.Diag(E);
2264 }
2265 return CompleteObject();
2266 }
2267 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2268 // We support folding of const floating-point types, in order to make
2269 // static const data members of such types (supported as an extension)
2270 // more useful.
2271 if (Info.getLangOpts().CPlusPlus11) {
2272 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2273 Info.Note(VD->getLocation(), diag::note_declared_at);
2274 } else {
2275 Info.CCEDiag(E);
2276 }
2277 } else {
2278 // FIXME: Allow folding of values of any literal type in all languages.
2279 if (Info.getLangOpts().CPlusPlus11) {
2280 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2281 Info.Note(VD->getLocation(), diag::note_declared_at);
2282 } else {
2283 Info.Diag(E);
2284 }
2285 return CompleteObject();
2286 }
2287 }
2288
2289 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2290 return CompleteObject();
2291 } else {
2292 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2293
2294 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002295 if (const MaterializeTemporaryExpr *MTE =
2296 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2297 assert(MTE->getStorageDuration() == SD_Static &&
2298 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002299
Richard Smithe6c01442013-06-05 00:46:14 +00002300 // Per C++1y [expr.const]p2:
2301 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2302 // - a [...] glvalue of integral or enumeration type that refers to
2303 // a non-volatile const object [...]
2304 // [...]
2305 // - a [...] glvalue of literal type that refers to a non-volatile
2306 // object whose lifetime began within the evaluation of e.
2307 //
2308 // C++11 misses the 'began within the evaluation of e' check and
2309 // instead allows all temporaries, including things like:
2310 // int &&r = 1;
2311 // int x = ++r;
2312 // constexpr int k = r;
2313 // Therefore we use the C++1y rules in C++11 too.
2314 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2315 const ValueDecl *ED = MTE->getExtendingDecl();
2316 if (!(BaseType.isConstQualified() &&
2317 BaseType->isIntegralOrEnumerationType()) &&
2318 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2319 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2320 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2321 return CompleteObject();
2322 }
2323
2324 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2325 assert(BaseVal && "got reference to unevaluated temporary");
2326 } else {
2327 Info.Diag(E);
2328 return CompleteObject();
2329 }
2330 } else {
2331 BaseVal = &Frame->Temporaries[Base];
2332 }
Richard Smith3229b742013-05-05 21:17:10 +00002333
2334 // Volatile temporary objects cannot be accessed in constant expressions.
2335 if (BaseType.isVolatileQualified()) {
2336 if (Info.getLangOpts().CPlusPlus) {
2337 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2338 << AK << 0;
2339 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2340 } else {
2341 Info.Diag(E);
2342 }
2343 return CompleteObject();
2344 }
2345 }
2346
Richard Smith7525ff62013-05-09 07:14:00 +00002347 // During the construction of an object, it is not yet 'const'.
2348 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2349 // and this doesn't do quite the right thing for const subobjects of the
2350 // object under construction.
2351 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2352 BaseType = Info.Ctx.getCanonicalType(BaseType);
2353 BaseType.removeLocalConst();
2354 }
2355
Richard Smith3229b742013-05-05 21:17:10 +00002356 // In C++1y, we can't safely access any mutable state when checking a
2357 // potential constant expression.
2358 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2359 Info.CheckingPotentialConstantExpression)
2360 return CompleteObject();
2361
2362 return CompleteObject(BaseVal, BaseType);
2363}
2364
Richard Smith243ef902013-05-05 23:31:59 +00002365/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2366/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2367/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002368///
2369/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002370/// \param Conv - The expression for which we are performing the conversion.
2371/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002372/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2373/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002374/// \param LVal - The glvalue on which we are attempting to perform this action.
2375/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002376static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002377 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002378 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002379 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002380 return false;
2381
Richard Smith3229b742013-05-05 21:17:10 +00002382 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002383 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002384 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2385 !Type.isVolatileQualified()) {
2386 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2387 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2388 // initializer until now for such expressions. Such an expression can't be
2389 // an ICE in C, so this only matters for fold.
2390 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2391 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002392 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002393 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002394 }
Richard Smith3229b742013-05-05 21:17:10 +00002395 APValue Lit;
2396 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2397 return false;
2398 CompleteObject LitObj(&Lit, Base->getType());
2399 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2400 } else if (isa<StringLiteral>(Base)) {
2401 // We represent a string literal array as an lvalue pointing at the
2402 // corresponding expression, rather than building an array of chars.
2403 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2404 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2405 CompleteObject StrObj(&Str, Base->getType());
2406 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002407 }
Richard Smith11562c52011-10-28 17:51:58 +00002408 }
2409
Richard Smith3229b742013-05-05 21:17:10 +00002410 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2411 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002412}
2413
2414/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002415static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002416 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002417 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002418 return false;
2419
Richard Smith3229b742013-05-05 21:17:10 +00002420 if (!Info.getLangOpts().CPlusPlus1y) {
2421 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002422 return false;
2423 }
2424
Richard Smith3229b742013-05-05 21:17:10 +00002425 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2426 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002427}
2428
Richard Smith243ef902013-05-05 23:31:59 +00002429static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2430 return T->isSignedIntegerType() &&
2431 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2432}
2433
2434namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002435struct CompoundAssignSubobjectHandler {
2436 EvalInfo &Info;
2437 const Expr *E;
2438 QualType PromotedLHSType;
2439 BinaryOperatorKind Opcode;
2440 const APValue &RHS;
2441
2442 static const AccessKinds AccessKind = AK_Assign;
2443
2444 typedef bool result_type;
2445
2446 bool checkConst(QualType QT) {
2447 // Assigning to a const object has undefined behavior.
2448 if (QT.isConstQualified()) {
2449 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2450 return false;
2451 }
2452 return true;
2453 }
2454
2455 bool failed() { return false; }
2456 bool found(APValue &Subobj, QualType SubobjType) {
2457 switch (Subobj.getKind()) {
2458 case APValue::Int:
2459 return found(Subobj.getInt(), SubobjType);
2460 case APValue::Float:
2461 return found(Subobj.getFloat(), SubobjType);
2462 case APValue::ComplexInt:
2463 case APValue::ComplexFloat:
2464 // FIXME: Implement complex compound assignment.
2465 Info.Diag(E);
2466 return false;
2467 case APValue::LValue:
2468 return foundPointer(Subobj, SubobjType);
2469 default:
2470 // FIXME: can this happen?
2471 Info.Diag(E);
2472 return false;
2473 }
2474 }
2475 bool found(APSInt &Value, QualType SubobjType) {
2476 if (!checkConst(SubobjType))
2477 return false;
2478
2479 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2480 // We don't support compound assignment on integer-cast-to-pointer
2481 // values.
2482 Info.Diag(E);
2483 return false;
2484 }
2485
2486 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2487 SubobjType, Value);
2488 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2489 return false;
2490 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2491 return true;
2492 }
2493 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002494 return checkConst(SubobjType) &&
2495 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2496 Value) &&
2497 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2498 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002499 }
2500 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2501 if (!checkConst(SubobjType))
2502 return false;
2503
2504 QualType PointeeType;
2505 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2506 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002507
2508 if (PointeeType.isNull() || !RHS.isInt() ||
2509 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002510 Info.Diag(E);
2511 return false;
2512 }
2513
Richard Smith861b5b52013-05-07 23:34:45 +00002514 int64_t Offset = getExtValue(RHS.getInt());
2515 if (Opcode == BO_Sub)
2516 Offset = -Offset;
2517
2518 LValue LVal;
2519 LVal.setFrom(Info.Ctx, Subobj);
2520 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2521 return false;
2522 LVal.moveInto(Subobj);
2523 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002524 }
2525 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2526 llvm_unreachable("shouldn't encounter string elements here");
2527 }
2528};
2529} // end anonymous namespace
2530
2531const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2532
2533/// Perform a compound assignment of LVal <op>= RVal.
2534static bool handleCompoundAssignment(
2535 EvalInfo &Info, const Expr *E,
2536 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2537 BinaryOperatorKind Opcode, const APValue &RVal) {
2538 if (LVal.Designator.Invalid)
2539 return false;
2540
2541 if (!Info.getLangOpts().CPlusPlus1y) {
2542 Info.Diag(E);
2543 return false;
2544 }
2545
2546 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2547 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2548 RVal };
2549 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2550}
2551
2552namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002553struct IncDecSubobjectHandler {
2554 EvalInfo &Info;
2555 const Expr *E;
2556 AccessKinds AccessKind;
2557 APValue *Old;
2558
2559 typedef bool result_type;
2560
2561 bool checkConst(QualType QT) {
2562 // Assigning to a const object has undefined behavior.
2563 if (QT.isConstQualified()) {
2564 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2565 return false;
2566 }
2567 return true;
2568 }
2569
2570 bool failed() { return false; }
2571 bool found(APValue &Subobj, QualType SubobjType) {
2572 // Stash the old value. Also clear Old, so we don't clobber it later
2573 // if we're post-incrementing a complex.
2574 if (Old) {
2575 *Old = Subobj;
2576 Old = 0;
2577 }
2578
2579 switch (Subobj.getKind()) {
2580 case APValue::Int:
2581 return found(Subobj.getInt(), SubobjType);
2582 case APValue::Float:
2583 return found(Subobj.getFloat(), SubobjType);
2584 case APValue::ComplexInt:
2585 return found(Subobj.getComplexIntReal(),
2586 SubobjType->castAs<ComplexType>()->getElementType()
2587 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2588 case APValue::ComplexFloat:
2589 return found(Subobj.getComplexFloatReal(),
2590 SubobjType->castAs<ComplexType>()->getElementType()
2591 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2592 case APValue::LValue:
2593 return foundPointer(Subobj, SubobjType);
2594 default:
2595 // FIXME: can this happen?
2596 Info.Diag(E);
2597 return false;
2598 }
2599 }
2600 bool found(APSInt &Value, QualType SubobjType) {
2601 if (!checkConst(SubobjType))
2602 return false;
2603
2604 if (!SubobjType->isIntegerType()) {
2605 // We don't support increment / decrement on integer-cast-to-pointer
2606 // values.
2607 Info.Diag(E);
2608 return false;
2609 }
2610
2611 if (Old) *Old = APValue(Value);
2612
2613 // bool arithmetic promotes to int, and the conversion back to bool
2614 // doesn't reduce mod 2^n, so special-case it.
2615 if (SubobjType->isBooleanType()) {
2616 if (AccessKind == AK_Increment)
2617 Value = 1;
2618 else
2619 Value = !Value;
2620 return true;
2621 }
2622
2623 bool WasNegative = Value.isNegative();
2624 if (AccessKind == AK_Increment) {
2625 ++Value;
2626
2627 if (!WasNegative && Value.isNegative() &&
2628 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2629 APSInt ActualValue(Value, /*IsUnsigned*/true);
2630 HandleOverflow(Info, E, ActualValue, SubobjType);
2631 }
2632 } else {
2633 --Value;
2634
2635 if (WasNegative && !Value.isNegative() &&
2636 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2637 unsigned BitWidth = Value.getBitWidth();
2638 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2639 ActualValue.setBit(BitWidth);
2640 HandleOverflow(Info, E, ActualValue, SubobjType);
2641 }
2642 }
2643 return true;
2644 }
2645 bool found(APFloat &Value, QualType SubobjType) {
2646 if (!checkConst(SubobjType))
2647 return false;
2648
2649 if (Old) *Old = APValue(Value);
2650
2651 APFloat One(Value.getSemantics(), 1);
2652 if (AccessKind == AK_Increment)
2653 Value.add(One, APFloat::rmNearestTiesToEven);
2654 else
2655 Value.subtract(One, APFloat::rmNearestTiesToEven);
2656 return true;
2657 }
2658 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2659 if (!checkConst(SubobjType))
2660 return false;
2661
2662 QualType PointeeType;
2663 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2664 PointeeType = PT->getPointeeType();
2665 else {
2666 Info.Diag(E);
2667 return false;
2668 }
2669
2670 LValue LVal;
2671 LVal.setFrom(Info.Ctx, Subobj);
2672 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2673 AccessKind == AK_Increment ? 1 : -1))
2674 return false;
2675 LVal.moveInto(Subobj);
2676 return true;
2677 }
2678 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2679 llvm_unreachable("shouldn't encounter string elements here");
2680 }
2681};
2682} // end anonymous namespace
2683
2684/// Perform an increment or decrement on LVal.
2685static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2686 QualType LValType, bool IsIncrement, APValue *Old) {
2687 if (LVal.Designator.Invalid)
2688 return false;
2689
2690 if (!Info.getLangOpts().CPlusPlus1y) {
2691 Info.Diag(E);
2692 return false;
2693 }
2694
2695 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2696 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2697 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2698 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2699}
2700
Richard Smithe97cbd72011-11-11 04:05:33 +00002701/// Build an lvalue for the object argument of a member function call.
2702static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2703 LValue &This) {
2704 if (Object->getType()->isPointerType())
2705 return EvaluatePointer(Object, This, Info);
2706
2707 if (Object->isGLValue())
2708 return EvaluateLValue(Object, This, Info);
2709
Richard Smithd9f663b2013-04-22 15:31:51 +00002710 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002711 return EvaluateTemporary(Object, This, Info);
2712
2713 return false;
2714}
2715
2716/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2717/// lvalue referring to the result.
2718///
2719/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002720/// \param LV - An lvalue referring to the base of the member pointer.
2721/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002722/// \param IncludeMember - Specifies whether the member itself is included in
2723/// the resulting LValue subobject designator. This is not possible when
2724/// creating a bound member function.
2725/// \return The field or method declaration to which the member pointer refers,
2726/// or 0 if evaluation fails.
2727static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002728 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002729 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002730 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002731 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002732 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002733 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002734 return 0;
2735
2736 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2737 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002738 if (!MemPtr.getDecl()) {
2739 // FIXME: Specific diagnostic.
2740 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002741 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002742 }
Richard Smith253c2a32012-01-27 01:14:48 +00002743
Richard Smith027bf112011-11-17 22:56:20 +00002744 if (MemPtr.isDerivedMember()) {
2745 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002746 // The end of the derived-to-base path for the base object must match the
2747 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002748 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002749 LV.Designator.Entries.size()) {
2750 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002751 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002752 }
Richard Smith027bf112011-11-17 22:56:20 +00002753 unsigned PathLengthToMember =
2754 LV.Designator.Entries.size() - MemPtr.Path.size();
2755 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2756 const CXXRecordDecl *LVDecl = getAsBaseClass(
2757 LV.Designator.Entries[PathLengthToMember + I]);
2758 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002759 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2760 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002761 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002762 }
Richard Smith027bf112011-11-17 22:56:20 +00002763 }
2764
2765 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002766 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002767 PathLengthToMember))
2768 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002769 } else if (!MemPtr.Path.empty()) {
2770 // Extend the LValue path with the member pointer's path.
2771 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2772 MemPtr.Path.size() + IncludeMember);
2773
2774 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002775 if (const PointerType *PT = LVType->getAs<PointerType>())
2776 LVType = PT->getPointeeType();
2777 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2778 assert(RD && "member pointer access on non-class-type expression");
2779 // The first class in the path is that of the lvalue.
2780 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2781 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002782 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002783 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002784 RD = Base;
2785 }
2786 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002787 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2788 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002789 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002790 }
2791
2792 // Add the member. Note that we cannot build bound member functions here.
2793 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002794 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002795 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002796 return 0;
2797 } else if (const IndirectFieldDecl *IFD =
2798 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002799 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002800 return 0;
2801 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002802 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002803 }
Richard Smith027bf112011-11-17 22:56:20 +00002804 }
2805
2806 return MemPtr.getDecl();
2807}
2808
Richard Smith84401042013-06-03 05:03:02 +00002809static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2810 const BinaryOperator *BO,
2811 LValue &LV,
2812 bool IncludeMember = true) {
2813 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2814
2815 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2816 if (Info.keepEvaluatingAfterFailure()) {
2817 MemberPtr MemPtr;
2818 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2819 }
2820 return 0;
2821 }
2822
2823 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2824 BO->getRHS(), IncludeMember);
2825}
2826
Richard Smith027bf112011-11-17 22:56:20 +00002827/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2828/// the provided lvalue, which currently refers to the base object.
2829static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2830 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002831 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002832 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002833 return false;
2834
Richard Smitha8105bc2012-01-06 16:39:00 +00002835 QualType TargetQT = E->getType();
2836 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2837 TargetQT = PT->getPointeeType();
2838
2839 // Check this cast lands within the final derived-to-base subobject path.
2840 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002841 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002842 << D.MostDerivedType << TargetQT;
2843 return false;
2844 }
2845
Richard Smith027bf112011-11-17 22:56:20 +00002846 // Check the type of the final cast. We don't need to check the path,
2847 // since a cast can only be formed if the path is unique.
2848 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002849 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2850 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002851 if (NewEntriesSize == D.MostDerivedPathLength)
2852 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2853 else
Richard Smith027bf112011-11-17 22:56:20 +00002854 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002855 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002856 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002857 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002858 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002859 }
Richard Smith027bf112011-11-17 22:56:20 +00002860
2861 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002862 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002863}
2864
Mike Stump876387b2009-10-27 22:09:17 +00002865namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002866enum EvalStmtResult {
2867 /// Evaluation failed.
2868 ESR_Failed,
2869 /// Hit a 'return' statement.
2870 ESR_Returned,
2871 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002872 ESR_Succeeded,
2873 /// Hit a 'continue' statement.
2874 ESR_Continue,
2875 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002876 ESR_Break,
2877 /// Still scanning for 'case' or 'default' statement.
2878 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002879};
2880}
2881
Richard Smithd9f663b2013-04-22 15:31:51 +00002882static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2883 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2884 // We don't need to evaluate the initializer for a static local.
2885 if (!VD->hasLocalStorage())
2886 return true;
2887
2888 LValue Result;
2889 Result.set(VD, Info.CurrentCall->Index);
2890 APValue &Val = Info.CurrentCall->Temporaries[VD];
2891
Richard Smith51f03172013-06-20 03:00:05 +00002892 if (!VD->getInit()) {
2893 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
2894 << false << VD->getType();
2895 Val = APValue();
2896 return false;
2897 }
2898
Richard Smithd9f663b2013-04-22 15:31:51 +00002899 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2900 // Wipe out any partially-computed value, to allow tracking that this
2901 // evaluation failed.
2902 Val = APValue();
2903 return false;
2904 }
2905 }
2906
2907 return true;
2908}
2909
Richard Smith4e18ca52013-05-06 05:56:11 +00002910/// Evaluate a condition (either a variable declaration or an expression).
2911static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2912 const Expr *Cond, bool &Result) {
2913 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2914 return false;
2915 return EvaluateAsBooleanCondition(Cond, Result, Info);
2916}
2917
2918static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002919 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002920
2921/// Evaluate the body of a loop, and translate the result as appropriate.
2922static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002923 const Stmt *Body,
2924 const SwitchCase *Case = 0) {
2925 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002926 case ESR_Break:
2927 return ESR_Succeeded;
2928 case ESR_Succeeded:
2929 case ESR_Continue:
2930 return ESR_Continue;
2931 case ESR_Failed:
2932 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002933 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002934 return ESR;
2935 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002936 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002937}
2938
Richard Smith496ddcf2013-05-12 17:32:42 +00002939/// Evaluate a switch statement.
2940static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2941 const SwitchStmt *SS) {
2942 // Evaluate the switch condition.
2943 if (SS->getConditionVariable() &&
2944 !EvaluateDecl(Info, SS->getConditionVariable()))
2945 return ESR_Failed;
2946 APSInt Value;
2947 if (!EvaluateInteger(SS->getCond(), Value, Info))
2948 return ESR_Failed;
2949
2950 // Find the switch case corresponding to the value of the condition.
2951 // FIXME: Cache this lookup.
2952 const SwitchCase *Found = 0;
2953 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2954 SC = SC->getNextSwitchCase()) {
2955 if (isa<DefaultStmt>(SC)) {
2956 Found = SC;
2957 continue;
2958 }
2959
2960 const CaseStmt *CS = cast<CaseStmt>(SC);
2961 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2962 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2963 : LHS;
2964 if (LHS <= Value && Value <= RHS) {
2965 Found = SC;
2966 break;
2967 }
2968 }
2969
2970 if (!Found)
2971 return ESR_Succeeded;
2972
2973 // Search the switch body for the switch case and evaluate it from there.
2974 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2975 case ESR_Break:
2976 return ESR_Succeeded;
2977 case ESR_Succeeded:
2978 case ESR_Continue:
2979 case ESR_Failed:
2980 case ESR_Returned:
2981 return ESR;
2982 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00002983 // This can only happen if the switch case is nested within a statement
2984 // expression. We have no intention of supporting that.
2985 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
2986 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00002987 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002988 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002989}
2990
Richard Smith254a73d2011-10-28 22:34:42 +00002991// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002992static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002993 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002994 if (!Info.nextStep(S))
2995 return ESR_Failed;
2996
Richard Smith496ddcf2013-05-12 17:32:42 +00002997 // If we're hunting down a 'case' or 'default' label, recurse through
2998 // substatements until we hit the label.
2999 if (Case) {
3000 // FIXME: We don't start the lifetime of objects whose initialization we
3001 // jump over. However, such objects must be of class type with a trivial
3002 // default constructor that initialize all subobjects, so must be empty,
3003 // so this almost never matters.
3004 switch (S->getStmtClass()) {
3005 case Stmt::CompoundStmtClass:
3006 // FIXME: Precompute which substatement of a compound statement we
3007 // would jump to, and go straight there rather than performing a
3008 // linear scan each time.
3009 case Stmt::LabelStmtClass:
3010 case Stmt::AttributedStmtClass:
3011 case Stmt::DoStmtClass:
3012 break;
3013
3014 case Stmt::CaseStmtClass:
3015 case Stmt::DefaultStmtClass:
3016 if (Case == S)
3017 Case = 0;
3018 break;
3019
3020 case Stmt::IfStmtClass: {
3021 // FIXME: Precompute which side of an 'if' we would jump to, and go
3022 // straight there rather than scanning both sides.
3023 const IfStmt *IS = cast<IfStmt>(S);
3024 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3025 if (ESR != ESR_CaseNotFound || !IS->getElse())
3026 return ESR;
3027 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3028 }
3029
3030 case Stmt::WhileStmtClass: {
3031 EvalStmtResult ESR =
3032 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3033 if (ESR != ESR_Continue)
3034 return ESR;
3035 break;
3036 }
3037
3038 case Stmt::ForStmtClass: {
3039 const ForStmt *FS = cast<ForStmt>(S);
3040 EvalStmtResult ESR =
3041 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3042 if (ESR != ESR_Continue)
3043 return ESR;
3044 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3045 return ESR_Failed;
3046 break;
3047 }
3048
3049 case Stmt::DeclStmtClass:
3050 // FIXME: If the variable has initialization that can't be jumped over,
3051 // bail out of any immediately-surrounding compound-statement too.
3052 default:
3053 return ESR_CaseNotFound;
3054 }
3055 }
3056
Richard Smithd9f663b2013-04-22 15:31:51 +00003057 // FIXME: Mark all temporaries in the current frame as destroyed at
3058 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00003059 switch (S->getStmtClass()) {
3060 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003061 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003062 // Don't bother evaluating beyond an expression-statement which couldn't
3063 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00003064 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003065 return ESR_Failed;
3066 return ESR_Succeeded;
3067 }
3068
3069 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003070 return ESR_Failed;
3071
3072 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003073 return ESR_Succeeded;
3074
Richard Smithd9f663b2013-04-22 15:31:51 +00003075 case Stmt::DeclStmtClass: {
3076 const DeclStmt *DS = cast<DeclStmt>(S);
3077 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3078 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
3079 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3080 return ESR_Failed;
3081 return ESR_Succeeded;
3082 }
3083
Richard Smith357362d2011-12-13 06:39:58 +00003084 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003085 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00003086 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003087 return ESR_Failed;
3088 return ESR_Returned;
3089 }
Richard Smith254a73d2011-10-28 22:34:42 +00003090
3091 case Stmt::CompoundStmtClass: {
3092 const CompoundStmt *CS = cast<CompoundStmt>(S);
3093 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3094 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003095 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3096 if (ESR == ESR_Succeeded)
3097 Case = 0;
3098 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003099 return ESR;
3100 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003101 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003102 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003103
3104 case Stmt::IfStmtClass: {
3105 const IfStmt *IS = cast<IfStmt>(S);
3106
3107 // Evaluate the condition, as either a var decl or as an expression.
3108 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003109 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003110 return ESR_Failed;
3111
3112 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3113 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3114 if (ESR != ESR_Succeeded)
3115 return ESR;
3116 }
3117 return ESR_Succeeded;
3118 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003119
3120 case Stmt::WhileStmtClass: {
3121 const WhileStmt *WS = cast<WhileStmt>(S);
3122 while (true) {
3123 bool Continue;
3124 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3125 Continue))
3126 return ESR_Failed;
3127 if (!Continue)
3128 break;
3129
3130 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3131 if (ESR != ESR_Continue)
3132 return ESR;
3133 }
3134 return ESR_Succeeded;
3135 }
3136
3137 case Stmt::DoStmtClass: {
3138 const DoStmt *DS = cast<DoStmt>(S);
3139 bool Continue;
3140 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003141 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003142 if (ESR != ESR_Continue)
3143 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003144 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003145
3146 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3147 return ESR_Failed;
3148 } while (Continue);
3149 return ESR_Succeeded;
3150 }
3151
3152 case Stmt::ForStmtClass: {
3153 const ForStmt *FS = cast<ForStmt>(S);
3154 if (FS->getInit()) {
3155 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3156 if (ESR != ESR_Succeeded)
3157 return ESR;
3158 }
3159 while (true) {
3160 bool Continue = true;
3161 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3162 FS->getCond(), Continue))
3163 return ESR_Failed;
3164 if (!Continue)
3165 break;
3166
3167 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3168 if (ESR != ESR_Continue)
3169 return ESR;
3170
3171 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3172 return ESR_Failed;
3173 }
3174 return ESR_Succeeded;
3175 }
3176
Richard Smith896e0d72013-05-06 06:51:17 +00003177 case Stmt::CXXForRangeStmtClass: {
3178 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3179
3180 // Initialize the __range variable.
3181 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3182 if (ESR != ESR_Succeeded)
3183 return ESR;
3184
3185 // Create the __begin and __end iterators.
3186 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3187 if (ESR != ESR_Succeeded)
3188 return ESR;
3189
3190 while (true) {
3191 // Condition: __begin != __end.
3192 bool Continue = true;
3193 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3194 return ESR_Failed;
3195 if (!Continue)
3196 break;
3197
3198 // User's variable declaration, initialized by *__begin.
3199 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3200 if (ESR != ESR_Succeeded)
3201 return ESR;
3202
3203 // Loop body.
3204 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3205 if (ESR != ESR_Continue)
3206 return ESR;
3207
3208 // Increment: ++__begin
3209 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3210 return ESR_Failed;
3211 }
3212
3213 return ESR_Succeeded;
3214 }
3215
Richard Smith496ddcf2013-05-12 17:32:42 +00003216 case Stmt::SwitchStmtClass:
3217 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3218
Richard Smith4e18ca52013-05-06 05:56:11 +00003219 case Stmt::ContinueStmtClass:
3220 return ESR_Continue;
3221
3222 case Stmt::BreakStmtClass:
3223 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003224
3225 case Stmt::LabelStmtClass:
3226 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3227
3228 case Stmt::AttributedStmtClass:
3229 // As a general principle, C++11 attributes can be ignored without
3230 // any semantic impact.
3231 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3232 Case);
3233
3234 case Stmt::CaseStmtClass:
3235 case Stmt::DefaultStmtClass:
3236 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003237 }
3238}
3239
Richard Smithcc36f692011-12-22 02:22:31 +00003240/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3241/// default constructor. If so, we'll fold it whether or not it's marked as
3242/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3243/// so we need special handling.
3244static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003245 const CXXConstructorDecl *CD,
3246 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003247 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3248 return false;
3249
Richard Smith66e05fe2012-01-18 05:21:49 +00003250 // Value-initialization does not call a trivial default constructor, so such a
3251 // call is a core constant expression whether or not the constructor is
3252 // constexpr.
3253 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003254 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003255 // FIXME: If DiagDecl is an implicitly-declared special member function,
3256 // we should be much more explicit about why it's not constexpr.
3257 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3258 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3259 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003260 } else {
3261 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3262 }
3263 }
3264 return true;
3265}
3266
Richard Smith357362d2011-12-13 06:39:58 +00003267/// CheckConstexprFunction - Check that a function can be called in a constant
3268/// expression.
3269static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3270 const FunctionDecl *Declaration,
3271 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003272 // Potential constant expressions can contain calls to declared, but not yet
3273 // defined, constexpr functions.
3274 if (Info.CheckingPotentialConstantExpression && !Definition &&
3275 Declaration->isConstexpr())
3276 return false;
3277
Richard Smith0838f3a2013-05-14 05:18:44 +00003278 // Bail out with no diagnostic if the function declaration itself is invalid.
3279 // We will have produced a relevant diagnostic while parsing it.
3280 if (Declaration->isInvalidDecl())
3281 return false;
3282
Richard Smith357362d2011-12-13 06:39:58 +00003283 // Can we evaluate this function call?
3284 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3285 return true;
3286
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003287 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003288 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003289 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3290 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003291 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3292 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3293 << DiagDecl;
3294 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3295 } else {
3296 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3297 }
3298 return false;
3299}
3300
Richard Smithd62306a2011-11-10 06:34:14 +00003301namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003302typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003303}
3304
3305/// EvaluateArgs - Evaluate the arguments to a function call.
3306static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3307 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003308 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003309 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003310 I != E; ++I) {
3311 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3312 // If we're checking for a potential constant expression, evaluate all
3313 // initializers even if some of them fail.
3314 if (!Info.keepEvaluatingAfterFailure())
3315 return false;
3316 Success = false;
3317 }
3318 }
3319 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003320}
3321
Richard Smith254a73d2011-10-28 22:34:42 +00003322/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003323static bool HandleFunctionCall(SourceLocation CallLoc,
3324 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003325 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003326 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003327 ArgVector ArgValues(Args.size());
3328 if (!EvaluateArgs(Args, ArgValues, Info))
3329 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003330
Richard Smith253c2a32012-01-27 01:14:48 +00003331 if (!Info.CheckCallLimit(CallLoc))
3332 return false;
3333
3334 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003335
3336 // For a trivial copy or move assignment, perform an APValue copy. This is
3337 // essential for unions, where the operations performed by the assignment
3338 // operator cannot be represented as statements.
3339 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3340 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3341 assert(This &&
3342 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3343 LValue RHS;
3344 RHS.setFrom(Info.Ctx, ArgValues[0]);
3345 APValue RHSValue;
3346 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3347 RHS, RHSValue))
3348 return false;
3349 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3350 RHSValue))
3351 return false;
3352 This->moveInto(Result);
3353 return true;
3354 }
3355
Richard Smithd9f663b2013-04-22 15:31:51 +00003356 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003357 if (ESR == ESR_Succeeded) {
3358 if (Callee->getResultType()->isVoidType())
3359 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003360 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003361 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003362 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003363}
3364
Richard Smithd62306a2011-11-10 06:34:14 +00003365/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003366static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003367 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003368 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003369 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003370 ArgVector ArgValues(Args.size());
3371 if (!EvaluateArgs(Args, ArgValues, Info))
3372 return false;
3373
Richard Smith253c2a32012-01-27 01:14:48 +00003374 if (!Info.CheckCallLimit(CallLoc))
3375 return false;
3376
Richard Smith3607ffe2012-02-13 03:54:03 +00003377 const CXXRecordDecl *RD = Definition->getParent();
3378 if (RD->getNumVBases()) {
3379 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3380 return false;
3381 }
3382
Richard Smith253c2a32012-01-27 01:14:48 +00003383 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003384
3385 // If it's a delegating constructor, just delegate.
3386 if (Definition->isDelegatingConstructor()) {
3387 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003388 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3389 return false;
3390 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003391 }
3392
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003393 // For a trivial copy or move constructor, perform an APValue copy. This is
3394 // essential for unions, where the operations performed by the constructor
3395 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003396 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003397 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3398 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003399 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003400 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003401 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003402 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003403 }
3404
3405 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003406 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003407 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3408 std::distance(RD->field_begin(), RD->field_end()));
3409
John McCalld7bca762012-05-01 00:38:49 +00003410 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003411 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3412
Richard Smith253c2a32012-01-27 01:14:48 +00003413 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003414 unsigned BasesSeen = 0;
3415#ifndef NDEBUG
3416 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3417#endif
3418 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3419 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003420 LValue Subobject = This;
3421 APValue *Value = &Result;
3422
3423 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003424 if ((*I)->isBaseInitializer()) {
3425 QualType BaseType((*I)->getBaseClass(), 0);
3426#ifndef NDEBUG
3427 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003428 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003429 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3430 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3431 "base class initializers not in expected order");
3432 ++BaseIt;
3433#endif
John McCalld7bca762012-05-01 00:38:49 +00003434 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3435 BaseType->getAsCXXRecordDecl(), &Layout))
3436 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003437 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003438 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003439 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3440 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003441 if (RD->isUnion()) {
3442 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003443 Value = &Result.getUnionValue();
3444 } else {
3445 Value = &Result.getStructField(FD->getFieldIndex());
3446 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003447 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003448 // Walk the indirect field decl's chain to find the object to initialize,
3449 // and make sure we've initialized every step along it.
3450 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3451 CE = IFD->chain_end();
3452 C != CE; ++C) {
3453 FieldDecl *FD = cast<FieldDecl>(*C);
3454 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3455 // Switch the union field if it differs. This happens if we had
3456 // preceding zero-initialization, and we're now initializing a union
3457 // subobject other than the first.
3458 // FIXME: In this case, the values of the other subobjects are
3459 // specified, since zero-initialization sets all padding bits to zero.
3460 if (Value->isUninit() ||
3461 (Value->isUnion() && Value->getUnionField() != FD)) {
3462 if (CD->isUnion())
3463 *Value = APValue(FD);
3464 else
3465 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3466 std::distance(CD->field_begin(), CD->field_end()));
3467 }
John McCalld7bca762012-05-01 00:38:49 +00003468 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3469 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003470 if (CD->isUnion())
3471 Value = &Value->getUnionValue();
3472 else
3473 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003474 }
Richard Smithd62306a2011-11-10 06:34:14 +00003475 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003476 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003477 }
Richard Smith253c2a32012-01-27 01:14:48 +00003478
Richard Smith7525ff62013-05-09 07:14:00 +00003479 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003480 // If we're checking for a potential constant expression, evaluate all
3481 // initializers even if some of them fail.
3482 if (!Info.keepEvaluatingAfterFailure())
3483 return false;
3484 Success = false;
3485 }
Richard Smithd62306a2011-11-10 06:34:14 +00003486 }
3487
Richard Smithd9f663b2013-04-22 15:31:51 +00003488 return Success &&
3489 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003490}
3491
Eli Friedman9a156e52008-11-12 09:44:48 +00003492//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003493// Generic Evaluation
3494//===----------------------------------------------------------------------===//
3495namespace {
3496
Richard Smithf57d8cb2011-12-09 22:58:01 +00003497// FIXME: RetTy is always bool. Remove it.
3498template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003499class ExprEvaluatorBase
3500 : public ConstStmtVisitor<Derived, RetTy> {
3501private:
Richard Smith2e312c82012-03-03 22:46:17 +00003502 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003503 return static_cast<Derived*>(this)->Success(V, E);
3504 }
Richard Smithfddd3842011-12-30 21:15:51 +00003505 RetTy DerivedZeroInitialization(const Expr *E) {
3506 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003507 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003508
Richard Smith17100ba2012-02-16 02:46:34 +00003509 // Check whether a conditional operator with a non-constant condition is a
3510 // potential constant expression. If neither arm is a potential constant
3511 // expression, then the conditional operator is not either.
3512 template<typename ConditionalOperator>
3513 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3514 assert(Info.CheckingPotentialConstantExpression);
3515
3516 // Speculatively evaluate both arms.
3517 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003518 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003519 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3520
3521 StmtVisitorTy::Visit(E->getFalseExpr());
3522 if (Diag.empty())
3523 return;
3524
3525 Diag.clear();
3526 StmtVisitorTy::Visit(E->getTrueExpr());
3527 if (Diag.empty())
3528 return;
3529 }
3530
3531 Error(E, diag::note_constexpr_conditional_never_const);
3532 }
3533
3534
3535 template<typename ConditionalOperator>
3536 bool HandleConditionalOperator(const ConditionalOperator *E) {
3537 bool BoolResult;
3538 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3539 if (Info.CheckingPotentialConstantExpression)
3540 CheckPotentialConstantConditional(E);
3541 return false;
3542 }
3543
3544 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3545 return StmtVisitorTy::Visit(EvalExpr);
3546 }
3547
Peter Collingbournee9200682011-05-13 03:29:01 +00003548protected:
3549 EvalInfo &Info;
3550 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3551 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3552
Richard Smith92b1ce02011-12-12 09:28:41 +00003553 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003554 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003555 }
3556
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003557 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3558
3559public:
3560 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3561
3562 EvalInfo &getEvalInfo() { return Info; }
3563
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564 /// Report an evaluation error. This should only be called when an error is
3565 /// first discovered. When propagating an error, just return false.
3566 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003567 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003568 return false;
3569 }
3570 bool Error(const Expr *E) {
3571 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3572 }
3573
Peter Collingbournee9200682011-05-13 03:29:01 +00003574 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003575 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003576 }
3577 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003578 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003579 }
3580
3581 RetTy VisitParenExpr(const ParenExpr *E)
3582 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3583 RetTy VisitUnaryExtension(const UnaryOperator *E)
3584 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3585 RetTy VisitUnaryPlus(const UnaryOperator *E)
3586 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3587 RetTy VisitChooseExpr(const ChooseExpr *E)
3588 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3589 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3590 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003591 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3592 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003593 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3594 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003595 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3596 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003597 // We cannot create any objects for which cleanups are required, so there is
3598 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3599 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3600 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003601
Richard Smith6d6ecc32011-12-12 12:46:16 +00003602 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3603 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3604 return static_cast<Derived*>(this)->VisitCastExpr(E);
3605 }
3606 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3607 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3608 return static_cast<Derived*>(this)->VisitCastExpr(E);
3609 }
3610
Richard Smith027bf112011-11-17 22:56:20 +00003611 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3612 switch (E->getOpcode()) {
3613 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003614 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003615
3616 case BO_Comma:
3617 VisitIgnoredValue(E->getLHS());
3618 return StmtVisitorTy::Visit(E->getRHS());
3619
3620 case BO_PtrMemD:
3621 case BO_PtrMemI: {
3622 LValue Obj;
3623 if (!HandleMemberPointerAccess(Info, E, Obj))
3624 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003625 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003626 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003627 return false;
3628 return DerivedSuccess(Result, E);
3629 }
3630 }
3631 }
3632
Peter Collingbournee9200682011-05-13 03:29:01 +00003633 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003634 // Evaluate and cache the common expression. We treat it as a temporary,
3635 // even though it's not quite the same thing.
3636 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3637 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003638 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003639
Richard Smith17100ba2012-02-16 02:46:34 +00003640 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003641 }
3642
3643 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003644 bool IsBcpCall = false;
3645 // If the condition (ignoring parens) is a __builtin_constant_p call,
3646 // the result is a constant expression if it can be folded without
3647 // side-effects. This is an important GNU extension. See GCC PR38377
3648 // for discussion.
3649 if (const CallExpr *CallCE =
3650 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3651 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3652 IsBcpCall = true;
3653
3654 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3655 // constant expression; we can't check whether it's potentially foldable.
3656 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3657 return false;
3658
3659 FoldConstant Fold(Info);
3660
Richard Smith17100ba2012-02-16 02:46:34 +00003661 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003662 return false;
3663
3664 if (IsBcpCall)
3665 Fold.Fold(Info);
3666
3667 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003668 }
3669
3670 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003671 APValue &Value = Info.CurrentCall->Temporaries[E];
3672 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003673 const Expr *Source = E->getSourceExpr();
3674 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003675 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003676 if (Source == E) { // sanity checking.
3677 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003678 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003679 }
3680 return StmtVisitorTy::Visit(Source);
3681 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003682 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003683 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003684
Richard Smith254a73d2011-10-28 22:34:42 +00003685 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003686 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003687 QualType CalleeType = Callee->getType();
3688
Richard Smith254a73d2011-10-28 22:34:42 +00003689 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003690 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003691 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003692 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003693
Richard Smithe97cbd72011-11-11 04:05:33 +00003694 // Extract function decl and 'this' pointer from the callee.
3695 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003696 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003697 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3698 // Explicit bound member calls, such as x.f() or p->g();
3699 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003700 return false;
3701 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003702 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003703 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003704 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3705 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003706 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3707 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003708 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003709 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003710 return Error(Callee);
3711
3712 FD = dyn_cast<FunctionDecl>(Member);
3713 if (!FD)
3714 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003715 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003716 LValue Call;
3717 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003718 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003719
Richard Smitha8105bc2012-01-06 16:39:00 +00003720 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003721 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003722 FD = dyn_cast_or_null<FunctionDecl>(
3723 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003724 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003725 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003726
3727 // Overloaded operator calls to member functions are represented as normal
3728 // calls with '*this' as the first argument.
3729 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3730 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003731 // FIXME: When selecting an implicit conversion for an overloaded
3732 // operator delete, we sometimes try to evaluate calls to conversion
3733 // operators without a 'this' parameter!
3734 if (Args.empty())
3735 return Error(E);
3736
Richard Smithe97cbd72011-11-11 04:05:33 +00003737 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3738 return false;
3739 This = &ThisVal;
3740 Args = Args.slice(1);
3741 }
3742
3743 // Don't call function pointers which have been cast to some other type.
3744 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003746 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003747 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003748
Richard Smith47b34932012-02-01 02:39:43 +00003749 if (This && !This->checkSubobject(Info, E, CSK_This))
3750 return false;
3751
Richard Smith3607ffe2012-02-13 03:54:03 +00003752 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3753 // calls to such functions in constant expressions.
3754 if (This && !HasQualifier &&
3755 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3756 return Error(E, diag::note_constexpr_virtual_call);
3757
Richard Smith357362d2011-12-13 06:39:58 +00003758 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003759 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003760 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003761
Richard Smith357362d2011-12-13 06:39:58 +00003762 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003763 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3764 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003765 return false;
3766
Richard Smithb228a862012-02-15 02:18:13 +00003767 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003768 }
3769
Richard Smith11562c52011-10-28 17:51:58 +00003770 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3771 return StmtVisitorTy::Visit(E->getInitializer());
3772 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003773 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003774 if (E->getNumInits() == 0)
3775 return DerivedZeroInitialization(E);
3776 if (E->getNumInits() == 1)
3777 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003778 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003779 }
3780 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003781 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003782 }
3783 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003784 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003785 }
Richard Smith027bf112011-11-17 22:56:20 +00003786 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003787 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003788 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003789
Richard Smithd62306a2011-11-10 06:34:14 +00003790 /// A member expression where the object is a prvalue is itself a prvalue.
3791 RetTy VisitMemberExpr(const MemberExpr *E) {
3792 assert(!E->isArrow() && "missing call to bound member function?");
3793
Richard Smith2e312c82012-03-03 22:46:17 +00003794 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003795 if (!Evaluate(Val, Info, E->getBase()))
3796 return false;
3797
3798 QualType BaseTy = E->getBase()->getType();
3799
3800 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003801 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003802 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003803 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003804 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3805
Richard Smith3229b742013-05-05 21:17:10 +00003806 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003807 SubobjectDesignator Designator(BaseTy);
3808 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003809
Richard Smith3229b742013-05-05 21:17:10 +00003810 APValue Result;
3811 return extractSubobject(Info, E, Obj, Designator, Result) &&
3812 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003813 }
3814
Richard Smith11562c52011-10-28 17:51:58 +00003815 RetTy VisitCastExpr(const CastExpr *E) {
3816 switch (E->getCastKind()) {
3817 default:
3818 break;
3819
Richard Smitha23ab512013-05-23 00:30:41 +00003820 case CK_AtomicToNonAtomic: {
3821 APValue AtomicVal;
3822 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3823 return false;
3824 return DerivedSuccess(AtomicVal, E);
3825 }
3826
Richard Smith11562c52011-10-28 17:51:58 +00003827 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003828 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003829 return StmtVisitorTy::Visit(E->getSubExpr());
3830
3831 case CK_LValueToRValue: {
3832 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003833 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3834 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003835 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003836 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003837 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003838 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003839 return false;
3840 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003841 }
3842 }
3843
Richard Smithf57d8cb2011-12-09 22:58:01 +00003844 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003845 }
3846
Richard Smith243ef902013-05-05 23:31:59 +00003847 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3848 return VisitUnaryPostIncDec(UO);
3849 }
3850 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3851 return VisitUnaryPostIncDec(UO);
3852 }
3853 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3854 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3855 return Error(UO);
3856
3857 LValue LVal;
3858 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3859 return false;
3860 APValue RVal;
3861 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3862 UO->isIncrementOp(), &RVal))
3863 return false;
3864 return DerivedSuccess(RVal, UO);
3865 }
3866
Richard Smith51f03172013-06-20 03:00:05 +00003867 RetTy VisitStmtExpr(const StmtExpr *E) {
3868 // We will have checked the full-expressions inside the statement expression
3869 // when they were completed, and don't need to check them again now.
3870 if (Info.getIntOverflowCheckMode())
3871 return Error(E);
3872
3873 const CompoundStmt *CS = E->getSubStmt();
3874 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3875 BE = CS->body_end();
3876 /**/; ++BI) {
3877 if (BI + 1 == BE) {
3878 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
3879 if (!FinalExpr) {
3880 Info.Diag((*BI)->getLocStart(),
3881 diag::note_constexpr_stmt_expr_unsupported);
3882 return false;
3883 }
3884 return this->Visit(FinalExpr);
3885 }
3886
3887 APValue ReturnValue;
3888 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
3889 if (ESR != ESR_Succeeded) {
3890 // FIXME: If the statement-expression terminated due to 'return',
3891 // 'break', or 'continue', it would be nice to propagate that to
3892 // the outer statement evaluation rather than bailing out.
3893 if (ESR != ESR_Failed)
3894 Info.Diag((*BI)->getLocStart(),
3895 diag::note_constexpr_stmt_expr_unsupported);
3896 return false;
3897 }
3898 }
3899 }
3900
Richard Smith4a678122011-10-24 18:44:57 +00003901 /// Visit a value which is evaluated, but whose value is ignored.
3902 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003903 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003904 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003905};
3906
3907}
3908
3909//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003910// Common base class for lvalue and temporary evaluation.
3911//===----------------------------------------------------------------------===//
3912namespace {
3913template<class Derived>
3914class LValueExprEvaluatorBase
3915 : public ExprEvaluatorBase<Derived, bool> {
3916protected:
3917 LValue &Result;
3918 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3919 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3920
3921 bool Success(APValue::LValueBase B) {
3922 Result.set(B);
3923 return true;
3924 }
3925
3926public:
3927 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3928 ExprEvaluatorBaseTy(Info), Result(Result) {}
3929
Richard Smith2e312c82012-03-03 22:46:17 +00003930 bool Success(const APValue &V, const Expr *E) {
3931 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003932 return true;
3933 }
Richard Smith027bf112011-11-17 22:56:20 +00003934
Richard Smith027bf112011-11-17 22:56:20 +00003935 bool VisitMemberExpr(const MemberExpr *E) {
3936 // Handle non-static data members.
3937 QualType BaseTy;
3938 if (E->isArrow()) {
3939 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3940 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003941 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003942 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003943 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003944 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3945 return false;
3946 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003947 } else {
3948 if (!this->Visit(E->getBase()))
3949 return false;
3950 BaseTy = E->getBase()->getType();
3951 }
Richard Smith027bf112011-11-17 22:56:20 +00003952
Richard Smith1b78b3d2012-01-25 22:15:11 +00003953 const ValueDecl *MD = E->getMemberDecl();
3954 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3955 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3956 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3957 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003958 if (!HandleLValueMember(this->Info, E, Result, FD))
3959 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003960 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003961 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3962 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003963 } else
3964 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003965
Richard Smith1b78b3d2012-01-25 22:15:11 +00003966 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003967 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003968 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003969 RefValue))
3970 return false;
3971 return Success(RefValue, E);
3972 }
3973 return true;
3974 }
3975
3976 bool VisitBinaryOperator(const BinaryOperator *E) {
3977 switch (E->getOpcode()) {
3978 default:
3979 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3980
3981 case BO_PtrMemD:
3982 case BO_PtrMemI:
3983 return HandleMemberPointerAccess(this->Info, E, Result);
3984 }
3985 }
3986
3987 bool VisitCastExpr(const CastExpr *E) {
3988 switch (E->getCastKind()) {
3989 default:
3990 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3991
3992 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00003993 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00003994 if (!this->Visit(E->getSubExpr()))
3995 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003996
3997 // Now figure out the necessary offset to add to the base LV to get from
3998 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00003999 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4000 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004001 }
4002 }
4003};
4004}
4005
4006//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004007// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004008//
4009// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4010// function designators (in C), decl references to void objects (in C), and
4011// temporaries (if building with -Wno-address-of-temporary).
4012//
4013// LValue evaluation produces values comprising a base expression of one of the
4014// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004015// - Declarations
4016// * VarDecl
4017// * FunctionDecl
4018// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004019// * CompoundLiteralExpr in C
4020// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004021// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004022// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004023// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004024// * ObjCEncodeExpr
4025// * AddrLabelExpr
4026// * BlockExpr
4027// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004028// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004029// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004030// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004031// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4032// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004033// * A MaterializeTemporaryExpr that has static storage duration, with no
4034// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004035// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004036//===----------------------------------------------------------------------===//
4037namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004038class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004039 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004040public:
Richard Smith027bf112011-11-17 22:56:20 +00004041 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4042 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004043
Richard Smith11562c52011-10-28 17:51:58 +00004044 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004045 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004046
Peter Collingbournee9200682011-05-13 03:29:01 +00004047 bool VisitDeclRefExpr(const DeclRefExpr *E);
4048 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004049 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004050 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4051 bool VisitMemberExpr(const MemberExpr *E);
4052 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4053 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004054 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004055 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004056 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4057 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004058 bool VisitUnaryReal(const UnaryOperator *E);
4059 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004060 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4061 return VisitUnaryPreIncDec(UO);
4062 }
4063 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4064 return VisitUnaryPreIncDec(UO);
4065 }
Richard Smith3229b742013-05-05 21:17:10 +00004066 bool VisitBinAssign(const BinaryOperator *BO);
4067 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004068
Peter Collingbournee9200682011-05-13 03:29:01 +00004069 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004070 switch (E->getCastKind()) {
4071 default:
Richard Smith027bf112011-11-17 22:56:20 +00004072 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004073
Eli Friedmance3e02a2011-10-11 00:13:24 +00004074 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004075 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004076 if (!Visit(E->getSubExpr()))
4077 return false;
4078 Result.Designator.setInvalid();
4079 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004080
Richard Smith027bf112011-11-17 22:56:20 +00004081 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004082 if (!Visit(E->getSubExpr()))
4083 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004084 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004085 }
4086 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004087};
4088} // end anonymous namespace
4089
Richard Smith11562c52011-10-28 17:51:58 +00004090/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004091/// expressions which are not glvalues, in two cases:
4092/// * function designators in C, and
4093/// * "extern void" objects
4094static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4095 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4096 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004097 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004098}
4099
Peter Collingbournee9200682011-05-13 03:29:01 +00004100bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4102 return Success(FD);
4103 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004104 return VisitVarDecl(E, VD);
4105 return Error(E);
4106}
Richard Smith733237d2011-10-24 23:14:33 +00004107
Richard Smith11562c52011-10-28 17:51:58 +00004108bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004109 CallStackFrame *Frame = 0;
4110 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4111 Frame = Info.CurrentCall;
4112
Richard Smithfec09922011-11-01 16:57:24 +00004113 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004114 if (Frame) {
4115 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004116 return true;
4117 }
Richard Smithce40ad62011-11-12 22:28:03 +00004118 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004119 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004120
Richard Smith3229b742013-05-05 21:17:10 +00004121 APValue *V;
4122 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004123 return false;
Richard Smith3229b742013-05-05 21:17:10 +00004124 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004125}
4126
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004127bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4128 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004129 // Walk through the expression to find the materialized temporary itself.
4130 SmallVector<const Expr *, 2> CommaLHSs;
4131 SmallVector<SubobjectAdjustment, 2> Adjustments;
4132 const Expr *Inner = E->GetTemporaryExpr()->
4133 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004134
Richard Smith84401042013-06-03 05:03:02 +00004135 // If we passed any comma operators, evaluate their LHSs.
4136 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4137 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4138 return false;
4139
Richard Smithe6c01442013-06-05 00:46:14 +00004140 // A materialized temporary with static storage duration can appear within the
4141 // result of a constant expression evaluation, so we need to preserve its
4142 // value for use outside this evaluation.
4143 APValue *Value;
4144 if (E->getStorageDuration() == SD_Static) {
4145 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004146 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004147 Result.set(E);
4148 } else {
4149 Value = &Info.CurrentCall->Temporaries[E];
4150 Result.set(E, Info.CurrentCall->Index);
4151 }
4152
Richard Smithea4ad5d2013-06-06 08:19:16 +00004153 QualType Type = Inner->getType();
4154
Richard Smith84401042013-06-03 05:03:02 +00004155 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004156 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4157 (E->getStorageDuration() == SD_Static &&
4158 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4159 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004160 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004161 }
Richard Smith84401042013-06-03 05:03:02 +00004162
4163 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004164 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4165 --I;
4166 switch (Adjustments[I].Kind) {
4167 case SubobjectAdjustment::DerivedToBaseAdjustment:
4168 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4169 Type, Result))
4170 return false;
4171 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4172 break;
4173
4174 case SubobjectAdjustment::FieldAdjustment:
4175 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4176 return false;
4177 Type = Adjustments[I].Field->getType();
4178 break;
4179
4180 case SubobjectAdjustment::MemberPointerAdjustment:
4181 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4182 Adjustments[I].Ptr.RHS))
4183 return false;
4184 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4185 break;
4186 }
4187 }
4188
4189 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004190}
4191
Peter Collingbournee9200682011-05-13 03:29:01 +00004192bool
4193LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004194 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4195 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4196 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004197 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004198}
4199
Richard Smith6e525142011-12-27 12:18:28 +00004200bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004201 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004202 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004203
4204 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4205 << E->getExprOperand()->getType()
4206 << E->getExprOperand()->getSourceRange();
4207 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004208}
4209
Francois Pichet0066db92012-04-16 04:08:35 +00004210bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4211 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004212}
Francois Pichet0066db92012-04-16 04:08:35 +00004213
Peter Collingbournee9200682011-05-13 03:29:01 +00004214bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004215 // Handle static data members.
4216 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4217 VisitIgnoredValue(E->getBase());
4218 return VisitVarDecl(E, VD);
4219 }
4220
Richard Smith254a73d2011-10-28 22:34:42 +00004221 // Handle static member functions.
4222 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4223 if (MD->isStatic()) {
4224 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004225 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004226 }
4227 }
4228
Richard Smithd62306a2011-11-10 06:34:14 +00004229 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004230 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004231}
4232
Peter Collingbournee9200682011-05-13 03:29:01 +00004233bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004234 // FIXME: Deal with vectors as array subscript bases.
4235 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004236 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004237
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004238 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004239 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004240
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004241 APSInt Index;
4242 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004243 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004244
Richard Smith861b5b52013-05-07 23:34:45 +00004245 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4246 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004247}
Eli Friedman9a156e52008-11-12 09:44:48 +00004248
Peter Collingbournee9200682011-05-13 03:29:01 +00004249bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004250 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004251}
4252
Richard Smith66c96992012-02-18 22:04:06 +00004253bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4254 if (!Visit(E->getSubExpr()))
4255 return false;
4256 // __real is a no-op on scalar lvalues.
4257 if (E->getSubExpr()->getType()->isAnyComplexType())
4258 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4259 return true;
4260}
4261
4262bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4263 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4264 "lvalue __imag__ on scalar?");
4265 if (!Visit(E->getSubExpr()))
4266 return false;
4267 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4268 return true;
4269}
4270
Richard Smith243ef902013-05-05 23:31:59 +00004271bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4272 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004273 return Error(UO);
4274
4275 if (!this->Visit(UO->getSubExpr()))
4276 return false;
4277
Richard Smith243ef902013-05-05 23:31:59 +00004278 return handleIncDec(
4279 this->Info, UO, Result, UO->getSubExpr()->getType(),
4280 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004281}
4282
4283bool LValueExprEvaluator::VisitCompoundAssignOperator(
4284 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004285 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004286 return Error(CAO);
4287
Richard Smith3229b742013-05-05 21:17:10 +00004288 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004289
4290 // The overall lvalue result is the result of evaluating the LHS.
4291 if (!this->Visit(CAO->getLHS())) {
4292 if (Info.keepEvaluatingAfterFailure())
4293 Evaluate(RHS, this->Info, CAO->getRHS());
4294 return false;
4295 }
4296
Richard Smith3229b742013-05-05 21:17:10 +00004297 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4298 return false;
4299
Richard Smith43e77732013-05-07 04:50:00 +00004300 return handleCompoundAssignment(
4301 this->Info, CAO,
4302 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4303 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004304}
4305
4306bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004307 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4308 return Error(E);
4309
Richard Smith3229b742013-05-05 21:17:10 +00004310 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004311
4312 if (!this->Visit(E->getLHS())) {
4313 if (Info.keepEvaluatingAfterFailure())
4314 Evaluate(NewVal, this->Info, E->getRHS());
4315 return false;
4316 }
4317
Richard Smith3229b742013-05-05 21:17:10 +00004318 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4319 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004320
4321 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004322 NewVal);
4323}
4324
Eli Friedman9a156e52008-11-12 09:44:48 +00004325//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004326// Pointer Evaluation
4327//===----------------------------------------------------------------------===//
4328
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004329namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004330class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004331 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004332 LValue &Result;
4333
Peter Collingbournee9200682011-05-13 03:29:01 +00004334 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004335 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004336 return true;
4337 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004338public:
Mike Stump11289f42009-09-09 15:08:12 +00004339
John McCall45d55e42010-05-07 21:00:08 +00004340 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004341 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004342
Richard Smith2e312c82012-03-03 22:46:17 +00004343 bool Success(const APValue &V, const Expr *E) {
4344 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004345 return true;
4346 }
Richard Smithfddd3842011-12-30 21:15:51 +00004347 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004348 return Success((Expr*)0);
4349 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004350
John McCall45d55e42010-05-07 21:00:08 +00004351 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004352 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004353 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004355 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004356 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004357 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004358 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004359 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004360 bool VisitCallExpr(const CallExpr *E);
4361 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004362 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004363 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004364 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004365 }
Richard Smithd62306a2011-11-10 06:34:14 +00004366 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004367 // Can't look at 'this' when checking a potential constant expression.
4368 if (Info.CheckingPotentialConstantExpression)
4369 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004370 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004371 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004372 Result = *Info.CurrentCall->This;
4373 return true;
4374 }
John McCallc07a0c72011-02-17 10:25:35 +00004375
Eli Friedman449fe542009-03-23 04:56:01 +00004376 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004377};
Chris Lattner05706e882008-07-11 18:11:29 +00004378} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004379
John McCall45d55e42010-05-07 21:00:08 +00004380static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004381 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004382 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004383}
4384
John McCall45d55e42010-05-07 21:00:08 +00004385bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004386 if (E->getOpcode() != BO_Add &&
4387 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004388 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattner05706e882008-07-11 18:11:29 +00004390 const Expr *PExp = E->getLHS();
4391 const Expr *IExp = E->getRHS();
4392 if (IExp->getType()->isPointerType())
4393 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004394
Richard Smith253c2a32012-01-27 01:14:48 +00004395 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4396 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004397 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004398
John McCall45d55e42010-05-07 21:00:08 +00004399 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004400 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004401 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004402
4403 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004404 if (E->getOpcode() == BO_Sub)
4405 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004406
Ted Kremenek28831752012-08-23 20:46:57 +00004407 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004408 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4409 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004410}
Eli Friedman9a156e52008-11-12 09:44:48 +00004411
John McCall45d55e42010-05-07 21:00:08 +00004412bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4413 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004414}
Mike Stump11289f42009-09-09 15:08:12 +00004415
Peter Collingbournee9200682011-05-13 03:29:01 +00004416bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4417 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004418
Eli Friedman847a2bc2009-12-27 05:43:15 +00004419 switch (E->getCastKind()) {
4420 default:
4421 break;
4422
John McCalle3027922010-08-25 11:45:40 +00004423 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004424 case CK_CPointerToObjCPointerCast:
4425 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004426 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004427 if (!Visit(SubExpr))
4428 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004429 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4430 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4431 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004432 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004433 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004434 if (SubExpr->getType()->isVoidPointerType())
4435 CCEDiag(E, diag::note_constexpr_invalid_cast)
4436 << 3 << SubExpr->getType();
4437 else
4438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4439 }
Richard Smith96e0c102011-11-04 02:25:55 +00004440 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004441
Anders Carlsson18275092010-10-31 20:41:46 +00004442 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004443 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004444 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004445 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004446 if (!Result.Base && Result.Offset.isZero())
4447 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004448
Richard Smithd62306a2011-11-10 06:34:14 +00004449 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004450 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004451 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4452 castAs<PointerType>()->getPointeeType(),
4453 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004454
Richard Smith027bf112011-11-17 22:56:20 +00004455 case CK_BaseToDerived:
4456 if (!Visit(E->getSubExpr()))
4457 return false;
4458 if (!Result.Base && Result.Offset.isZero())
4459 return true;
4460 return HandleBaseToDerivedCast(Info, E, Result);
4461
Richard Smith0b0a0b62011-10-29 20:57:55 +00004462 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004463 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004464 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004465
John McCalle3027922010-08-25 11:45:40 +00004466 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004467 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4468
Richard Smith2e312c82012-03-03 22:46:17 +00004469 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004470 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004471 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004472
John McCall45d55e42010-05-07 21:00:08 +00004473 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004474 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4475 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004476 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004477 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004478 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004479 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004480 return true;
4481 } else {
4482 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004483 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004484 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004485 }
4486 }
John McCalle3027922010-08-25 11:45:40 +00004487 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004488 if (SubExpr->isGLValue()) {
4489 if (!EvaluateLValue(SubExpr, Result, Info))
4490 return false;
4491 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004492 Result.set(SubExpr, Info.CurrentCall->Index);
4493 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4494 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004495 return false;
4496 }
Richard Smith96e0c102011-11-04 02:25:55 +00004497 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004498 if (const ConstantArrayType *CAT
4499 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4500 Result.addArray(Info, E, CAT);
4501 else
4502 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004503 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004504
John McCalle3027922010-08-25 11:45:40 +00004505 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004506 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004507 }
4508
Richard Smith11562c52011-10-28 17:51:58 +00004509 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004510}
Chris Lattner05706e882008-07-11 18:11:29 +00004511
Peter Collingbournee9200682011-05-13 03:29:01 +00004512bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004513 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004514 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004515
Richard Smith6cbd65d2013-07-11 02:27:57 +00004516 switch (E->isBuiltinCall()) {
4517 case Builtin::BI__builtin_addressof:
4518 return EvaluateLValue(E->getArg(0), Result, Info);
4519
4520 default:
4521 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4522 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004523}
Chris Lattner05706e882008-07-11 18:11:29 +00004524
4525//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004526// Member Pointer Evaluation
4527//===----------------------------------------------------------------------===//
4528
4529namespace {
4530class MemberPointerExprEvaluator
4531 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4532 MemberPtr &Result;
4533
4534 bool Success(const ValueDecl *D) {
4535 Result = MemberPtr(D);
4536 return true;
4537 }
4538public:
4539
4540 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4541 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4542
Richard Smith2e312c82012-03-03 22:46:17 +00004543 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004544 Result.setFrom(V);
4545 return true;
4546 }
Richard Smithfddd3842011-12-30 21:15:51 +00004547 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004548 return Success((const ValueDecl*)0);
4549 }
4550
4551 bool VisitCastExpr(const CastExpr *E);
4552 bool VisitUnaryAddrOf(const UnaryOperator *E);
4553};
4554} // end anonymous namespace
4555
4556static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4557 EvalInfo &Info) {
4558 assert(E->isRValue() && E->getType()->isMemberPointerType());
4559 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4560}
4561
4562bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4563 switch (E->getCastKind()) {
4564 default:
4565 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4566
4567 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004568 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004569 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004570
4571 case CK_BaseToDerivedMemberPointer: {
4572 if (!Visit(E->getSubExpr()))
4573 return false;
4574 if (E->path_empty())
4575 return true;
4576 // Base-to-derived member pointer casts store the path in derived-to-base
4577 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4578 // the wrong end of the derived->base arc, so stagger the path by one class.
4579 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4580 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4581 PathI != PathE; ++PathI) {
4582 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4583 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4584 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004585 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004586 }
4587 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4588 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004590 return true;
4591 }
4592
4593 case CK_DerivedToBaseMemberPointer:
4594 if (!Visit(E->getSubExpr()))
4595 return false;
4596 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4597 PathE = E->path_end(); PathI != PathE; ++PathI) {
4598 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4599 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4600 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004601 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004602 }
4603 return true;
4604 }
4605}
4606
4607bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4608 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4609 // member can be formed.
4610 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4611}
4612
4613//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004614// Record Evaluation
4615//===----------------------------------------------------------------------===//
4616
4617namespace {
4618 class RecordExprEvaluator
4619 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4620 const LValue &This;
4621 APValue &Result;
4622 public:
4623
4624 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4625 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4626
Richard Smith2e312c82012-03-03 22:46:17 +00004627 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004628 Result = V;
4629 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004630 }
Richard Smithfddd3842011-12-30 21:15:51 +00004631 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004632
Richard Smithe97cbd72011-11-11 04:05:33 +00004633 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004634 bool VisitInitListExpr(const InitListExpr *E);
4635 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004636 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004637 };
4638}
4639
Richard Smithfddd3842011-12-30 21:15:51 +00004640/// Perform zero-initialization on an object of non-union class type.
4641/// C++11 [dcl.init]p5:
4642/// To zero-initialize an object or reference of type T means:
4643/// [...]
4644/// -- if T is a (possibly cv-qualified) non-union class type,
4645/// each non-static data member and each base-class subobject is
4646/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004647static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4648 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004649 const LValue &This, APValue &Result) {
4650 assert(!RD->isUnion() && "Expected non-union class type");
4651 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4652 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4653 std::distance(RD->field_begin(), RD->field_end()));
4654
John McCalld7bca762012-05-01 00:38:49 +00004655 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004656 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4657
4658 if (CD) {
4659 unsigned Index = 0;
4660 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004661 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004662 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4663 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004664 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4665 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004666 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004667 Result.getStructBase(Index)))
4668 return false;
4669 }
4670 }
4671
Richard Smitha8105bc2012-01-06 16:39:00 +00004672 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4673 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004674 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004675 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004676 continue;
4677
4678 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004679 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004680 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004681
David Blaikie2d7c57e2012-04-30 02:36:29 +00004682 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004683 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004684 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004685 return false;
4686 }
4687
4688 return true;
4689}
4690
4691bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4692 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004693 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004694 if (RD->isUnion()) {
4695 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4696 // object's first non-static named data member is zero-initialized
4697 RecordDecl::field_iterator I = RD->field_begin();
4698 if (I == RD->field_end()) {
4699 Result = APValue((const FieldDecl*)0);
4700 return true;
4701 }
4702
4703 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004704 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004705 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004706 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004707 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004708 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004709 }
4710
Richard Smith5d108602012-02-17 00:44:16 +00004711 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004712 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004713 return false;
4714 }
4715
Richard Smitha8105bc2012-01-06 16:39:00 +00004716 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004717}
4718
Richard Smithe97cbd72011-11-11 04:05:33 +00004719bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4720 switch (E->getCastKind()) {
4721 default:
4722 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4723
4724 case CK_ConstructorConversion:
4725 return Visit(E->getSubExpr());
4726
4727 case CK_DerivedToBase:
4728 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004729 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004731 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004732 if (!DerivedObject.isStruct())
4733 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004734
4735 // Derived-to-base rvalue conversion: just slice off the derived part.
4736 APValue *Value = &DerivedObject;
4737 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4738 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4739 PathE = E->path_end(); PathI != PathE; ++PathI) {
4740 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4741 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4742 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4743 RD = Base;
4744 }
4745 Result = *Value;
4746 return true;
4747 }
4748 }
4749}
4750
Richard Smithd62306a2011-11-10 06:34:14 +00004751bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4752 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004753 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004754 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4755
4756 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004757 const FieldDecl *Field = E->getInitializedFieldInUnion();
4758 Result = APValue(Field);
4759 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004760 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004761
4762 // If the initializer list for a union does not contain any elements, the
4763 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004764 // FIXME: The element should be initialized from an initializer list.
4765 // Is this difference ever observable for initializer lists which
4766 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004767 ImplicitValueInitExpr VIE(Field->getType());
4768 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4769
Richard Smithd62306a2011-11-10 06:34:14 +00004770 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004771 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4772 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004773
4774 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4775 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4776 isa<CXXDefaultInitExpr>(InitExpr));
4777
Richard Smithb228a862012-02-15 02:18:13 +00004778 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004779 }
4780
4781 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4782 "initializer list for class with base classes");
4783 Result = APValue(APValue::UninitStruct(), 0,
4784 std::distance(RD->field_begin(), RD->field_end()));
4785 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004786 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004787 for (RecordDecl::field_iterator Field = RD->field_begin(),
4788 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4789 // Anonymous bit-fields are not considered members of the class for
4790 // purposes of aggregate initialization.
4791 if (Field->isUnnamedBitfield())
4792 continue;
4793
4794 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004795
Richard Smith253c2a32012-01-27 01:14:48 +00004796 bool HaveInit = ElementNo < E->getNumInits();
4797
4798 // FIXME: Diagnostics here should point to the end of the initializer
4799 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004800 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004801 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004802 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004803
4804 // Perform an implicit value-initialization for members beyond the end of
4805 // the initializer list.
4806 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004807 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004808
Richard Smith852c9db2013-04-20 22:23:05 +00004809 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4810 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4811 isa<CXXDefaultInitExpr>(Init));
4812
4813 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4814 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004815 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004816 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004817 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004818 }
4819 }
4820
Richard Smith253c2a32012-01-27 01:14:48 +00004821 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004822}
4823
4824bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4825 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004826 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4827
Richard Smithfddd3842011-12-30 21:15:51 +00004828 bool ZeroInit = E->requiresZeroInitialization();
4829 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004830 // If we've already performed zero-initialization, we're already done.
4831 if (!Result.isUninit())
4832 return true;
4833
Richard Smithfddd3842011-12-30 21:15:51 +00004834 if (ZeroInit)
4835 return ZeroInitialization(E);
4836
Richard Smithcc36f692011-12-22 02:22:31 +00004837 const CXXRecordDecl *RD = FD->getParent();
4838 if (RD->isUnion())
4839 Result = APValue((FieldDecl*)0);
4840 else
4841 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4842 std::distance(RD->field_begin(), RD->field_end()));
4843 return true;
4844 }
4845
Richard Smithd62306a2011-11-10 06:34:14 +00004846 const FunctionDecl *Definition = 0;
4847 FD->getBody(Definition);
4848
Richard Smith357362d2011-12-13 06:39:58 +00004849 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4850 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004851
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004852 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004853 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004854 if (const MaterializeTemporaryExpr *ME
4855 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4856 return Visit(ME->GetTemporaryExpr());
4857
Richard Smithfddd3842011-12-30 21:15:51 +00004858 if (ZeroInit && !ZeroInitialization(E))
4859 return false;
4860
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004861 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004862 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004863 cast<CXXConstructorDecl>(Definition), Info,
4864 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004865}
4866
Richard Smithcc1b96d2013-06-12 22:31:48 +00004867bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
4868 const CXXStdInitializerListExpr *E) {
4869 const ConstantArrayType *ArrayType =
4870 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
4871
4872 LValue Array;
4873 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
4874 return false;
4875
4876 // Get a pointer to the first element of the array.
4877 Array.addArray(Info, E, ArrayType);
4878
4879 // FIXME: Perform the checks on the field types in SemaInit.
4880 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
4881 RecordDecl::field_iterator Field = Record->field_begin();
4882 if (Field == Record->field_end())
4883 return Error(E);
4884
4885 // Start pointer.
4886 if (!Field->getType()->isPointerType() ||
4887 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4888 ArrayType->getElementType()))
4889 return Error(E);
4890
4891 // FIXME: What if the initializer_list type has base classes, etc?
4892 Result = APValue(APValue::UninitStruct(), 0, 2);
4893 Array.moveInto(Result.getStructField(0));
4894
4895 if (++Field == Record->field_end())
4896 return Error(E);
4897
4898 if (Field->getType()->isPointerType() &&
4899 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
4900 ArrayType->getElementType())) {
4901 // End pointer.
4902 if (!HandleLValueArrayAdjustment(Info, E, Array,
4903 ArrayType->getElementType(),
4904 ArrayType->getSize().getZExtValue()))
4905 return false;
4906 Array.moveInto(Result.getStructField(1));
4907 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
4908 // Length.
4909 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
4910 else
4911 return Error(E);
4912
4913 if (++Field != Record->field_end())
4914 return Error(E);
4915
4916 return true;
4917}
4918
Richard Smithd62306a2011-11-10 06:34:14 +00004919static bool EvaluateRecord(const Expr *E, const LValue &This,
4920 APValue &Result, EvalInfo &Info) {
4921 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004922 "can't evaluate expression as a record rvalue");
4923 return RecordExprEvaluator(Info, This, Result).Visit(E);
4924}
4925
4926//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004927// Temporary Evaluation
4928//
4929// Temporaries are represented in the AST as rvalues, but generally behave like
4930// lvalues. The full-object of which the temporary is a subobject is implicitly
4931// materialized so that a reference can bind to it.
4932//===----------------------------------------------------------------------===//
4933namespace {
4934class TemporaryExprEvaluator
4935 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4936public:
4937 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4938 LValueExprEvaluatorBaseTy(Info, Result) {}
4939
4940 /// Visit an expression which constructs the value of this temporary.
4941 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004942 Result.set(E, Info.CurrentCall->Index);
4943 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004944 }
4945
4946 bool VisitCastExpr(const CastExpr *E) {
4947 switch (E->getCastKind()) {
4948 default:
4949 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4950
4951 case CK_ConstructorConversion:
4952 return VisitConstructExpr(E->getSubExpr());
4953 }
4954 }
4955 bool VisitInitListExpr(const InitListExpr *E) {
4956 return VisitConstructExpr(E);
4957 }
4958 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4959 return VisitConstructExpr(E);
4960 }
4961 bool VisitCallExpr(const CallExpr *E) {
4962 return VisitConstructExpr(E);
4963 }
4964};
4965} // end anonymous namespace
4966
4967/// Evaluate an expression of record type as a temporary.
4968static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004969 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004970 return TemporaryExprEvaluator(Info, Result).Visit(E);
4971}
4972
4973//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004974// Vector Evaluation
4975//===----------------------------------------------------------------------===//
4976
4977namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004978 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004979 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4980 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004981 public:
Mike Stump11289f42009-09-09 15:08:12 +00004982
Richard Smith2d406342011-10-22 21:10:00 +00004983 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4984 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004985
Richard Smith2d406342011-10-22 21:10:00 +00004986 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4987 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4988 // FIXME: remove this APValue copy.
4989 Result = APValue(V.data(), V.size());
4990 return true;
4991 }
Richard Smith2e312c82012-03-03 22:46:17 +00004992 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004993 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004994 Result = V;
4995 return true;
4996 }
Richard Smithfddd3842011-12-30 21:15:51 +00004997 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004998
Richard Smith2d406342011-10-22 21:10:00 +00004999 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005000 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005001 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005002 bool VisitInitListExpr(const InitListExpr *E);
5003 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005004 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005005 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005006 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005007 };
5008} // end anonymous namespace
5009
5010static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005011 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005012 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005013}
5014
Richard Smith2d406342011-10-22 21:10:00 +00005015bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5016 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005017 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005018
Richard Smith161f09a2011-12-06 22:44:34 +00005019 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005020 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005021
Eli Friedmanc757de22011-03-25 00:43:55 +00005022 switch (E->getCastKind()) {
5023 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005024 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005025 if (SETy->isIntegerType()) {
5026 APSInt IntResult;
5027 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005028 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005029 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005030 } else if (SETy->isRealFloatingType()) {
5031 APFloat F(0.0);
5032 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005033 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005034 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005035 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005036 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005037 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005038
5039 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005040 SmallVector<APValue, 4> Elts(NElts, Val);
5041 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005042 }
Eli Friedman803acb32011-12-22 03:51:45 +00005043 case CK_BitCast: {
5044 // Evaluate the operand into an APInt we can extract from.
5045 llvm::APInt SValInt;
5046 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5047 return false;
5048 // Extract the elements
5049 QualType EltTy = VTy->getElementType();
5050 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5051 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5052 SmallVector<APValue, 4> Elts;
5053 if (EltTy->isRealFloatingType()) {
5054 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005055 unsigned FloatEltSize = EltSize;
5056 if (&Sem == &APFloat::x87DoubleExtended)
5057 FloatEltSize = 80;
5058 for (unsigned i = 0; i < NElts; i++) {
5059 llvm::APInt Elt;
5060 if (BigEndian)
5061 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5062 else
5063 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005064 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005065 }
5066 } else if (EltTy->isIntegerType()) {
5067 for (unsigned i = 0; i < NElts; i++) {
5068 llvm::APInt Elt;
5069 if (BigEndian)
5070 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5071 else
5072 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5073 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5074 }
5075 } else {
5076 return Error(E);
5077 }
5078 return Success(Elts, E);
5079 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005080 default:
Richard Smith11562c52011-10-28 17:51:58 +00005081 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005082 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005083}
5084
Richard Smith2d406342011-10-22 21:10:00 +00005085bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005086VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005087 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005088 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005089 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005090
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005091 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005092 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005093
Eli Friedmanb9c71292012-01-03 23:24:20 +00005094 // The number of initializers can be less than the number of
5095 // vector elements. For OpenCL, this can be due to nested vector
5096 // initialization. For GCC compatibility, missing trailing elements
5097 // should be initialized with zeroes.
5098 unsigned CountInits = 0, CountElts = 0;
5099 while (CountElts < NumElements) {
5100 // Handle nested vector initialization.
5101 if (CountInits < NumInits
5102 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5103 APValue v;
5104 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5105 return Error(E);
5106 unsigned vlen = v.getVectorLength();
5107 for (unsigned j = 0; j < vlen; j++)
5108 Elements.push_back(v.getVectorElt(j));
5109 CountElts += vlen;
5110 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005111 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005112 if (CountInits < NumInits) {
5113 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005114 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005115 } else // trailing integer zero.
5116 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5117 Elements.push_back(APValue(sInt));
5118 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005119 } else {
5120 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005121 if (CountInits < NumInits) {
5122 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005123 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005124 } else // trailing float zero.
5125 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5126 Elements.push_back(APValue(f));
5127 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005128 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005129 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005130 }
Richard Smith2d406342011-10-22 21:10:00 +00005131 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005132}
5133
Richard Smith2d406342011-10-22 21:10:00 +00005134bool
Richard Smithfddd3842011-12-30 21:15:51 +00005135VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005136 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005137 QualType EltTy = VT->getElementType();
5138 APValue ZeroElement;
5139 if (EltTy->isIntegerType())
5140 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5141 else
5142 ZeroElement =
5143 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5144
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005145 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005146 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005147}
5148
Richard Smith2d406342011-10-22 21:10:00 +00005149bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005150 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005151 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005152}
5153
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005154//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005155// Array Evaluation
5156//===----------------------------------------------------------------------===//
5157
5158namespace {
5159 class ArrayExprEvaluator
5160 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005161 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005162 APValue &Result;
5163 public:
5164
Richard Smithd62306a2011-11-10 06:34:14 +00005165 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5166 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005167
5168 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005169 assert((V.isArray() || V.isLValue()) &&
5170 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005171 Result = V;
5172 return true;
5173 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005174
Richard Smithfddd3842011-12-30 21:15:51 +00005175 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005176 const ConstantArrayType *CAT =
5177 Info.Ctx.getAsConstantArrayType(E->getType());
5178 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005179 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005180
5181 Result = APValue(APValue::UninitArray(), 0,
5182 CAT->getSize().getZExtValue());
5183 if (!Result.hasArrayFiller()) return true;
5184
Richard Smithfddd3842011-12-30 21:15:51 +00005185 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005186 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005187 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005188 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005189 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005190 }
5191
Richard Smithf3e9e432011-11-07 09:22:26 +00005192 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005193 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005194 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5195 const LValue &Subobject,
5196 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005197 };
5198} // end anonymous namespace
5199
Richard Smithd62306a2011-11-10 06:34:14 +00005200static bool EvaluateArray(const Expr *E, const LValue &This,
5201 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005202 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005203 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005204}
5205
5206bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5207 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5208 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005209 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005210
Richard Smithca2cfbf2011-12-22 01:07:19 +00005211 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5212 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005213 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005214 LValue LV;
5215 if (!EvaluateLValue(E->getInit(0), LV, Info))
5216 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005217 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005218 LV.moveInto(Val);
5219 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005220 }
5221
Richard Smith253c2a32012-01-27 01:14:48 +00005222 bool Success = true;
5223
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005224 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5225 "zero-initialized array shouldn't have any initialized elts");
5226 APValue Filler;
5227 if (Result.isArray() && Result.hasArrayFiller())
5228 Filler = Result.getArrayFiller();
5229
Richard Smith9543c5e2013-04-22 14:44:29 +00005230 unsigned NumEltsToInit = E->getNumInits();
5231 unsigned NumElts = CAT->getSize().getZExtValue();
5232 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5233
5234 // If the initializer might depend on the array index, run it for each
5235 // array element. For now, just whitelist non-class value-initialization.
5236 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5237 NumEltsToInit = NumElts;
5238
5239 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005240
5241 // If the array was previously zero-initialized, preserve the
5242 // zero-initialized values.
5243 if (!Filler.isUninit()) {
5244 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5245 Result.getArrayInitializedElt(I) = Filler;
5246 if (Result.hasArrayFiller())
5247 Result.getArrayFiller() = Filler;
5248 }
5249
Richard Smithd62306a2011-11-10 06:34:14 +00005250 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005251 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005252 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5253 const Expr *Init =
5254 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005255 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005256 Info, Subobject, Init) ||
5257 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005258 CAT->getElementType(), 1)) {
5259 if (!Info.keepEvaluatingAfterFailure())
5260 return false;
5261 Success = false;
5262 }
Richard Smithd62306a2011-11-10 06:34:14 +00005263 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005264
Richard Smith9543c5e2013-04-22 14:44:29 +00005265 if (!Result.hasArrayFiller())
5266 return Success;
5267
5268 // If we get here, we have a trivial filler, which we can just evaluate
5269 // once and splat over the rest of the array elements.
5270 assert(FillerExpr && "no array filler for incomplete init list");
5271 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5272 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005273}
5274
Richard Smith027bf112011-11-17 22:56:20 +00005275bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005276 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5277}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005278
Richard Smith9543c5e2013-04-22 14:44:29 +00005279bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5280 const LValue &Subobject,
5281 APValue *Value,
5282 QualType Type) {
5283 bool HadZeroInit = !Value->isUninit();
5284
5285 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5286 unsigned N = CAT->getSize().getZExtValue();
5287
5288 // Preserve the array filler if we had prior zero-initialization.
5289 APValue Filler =
5290 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5291 : APValue();
5292
5293 *Value = APValue(APValue::UninitArray(), N, N);
5294
5295 if (HadZeroInit)
5296 for (unsigned I = 0; I != N; ++I)
5297 Value->getArrayInitializedElt(I) = Filler;
5298
5299 // Initialize the elements.
5300 LValue ArrayElt = Subobject;
5301 ArrayElt.addArray(Info, E, CAT);
5302 for (unsigned I = 0; I != N; ++I)
5303 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5304 CAT->getElementType()) ||
5305 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5306 CAT->getElementType(), 1))
5307 return false;
5308
5309 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005310 }
Richard Smith027bf112011-11-17 22:56:20 +00005311
Richard Smith9543c5e2013-04-22 14:44:29 +00005312 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005313 return Error(E);
5314
Richard Smith027bf112011-11-17 22:56:20 +00005315 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005316
Richard Smithfddd3842011-12-30 21:15:51 +00005317 bool ZeroInit = E->requiresZeroInitialization();
5318 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005319 if (HadZeroInit)
5320 return true;
5321
Richard Smithfddd3842011-12-30 21:15:51 +00005322 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005323 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005324 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005325 }
5326
Richard Smithcc36f692011-12-22 02:22:31 +00005327 const CXXRecordDecl *RD = FD->getParent();
5328 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005329 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005330 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005331 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005332 APValue(APValue::UninitStruct(), RD->getNumBases(),
5333 std::distance(RD->field_begin(), RD->field_end()));
5334 return true;
5335 }
5336
Richard Smith027bf112011-11-17 22:56:20 +00005337 const FunctionDecl *Definition = 0;
5338 FD->getBody(Definition);
5339
Richard Smith357362d2011-12-13 06:39:58 +00005340 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5341 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005342
Richard Smith9eae7232012-01-12 18:54:33 +00005343 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005344 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005345 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005346 return false;
5347 }
5348
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005349 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005350 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005351 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005352 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005353}
5354
Richard Smithf3e9e432011-11-07 09:22:26 +00005355//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005356// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005357//
5358// As a GNU extension, we support casting pointers to sufficiently-wide integer
5359// types and back in constant folding. Integer values are thus represented
5360// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005361//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005362
5363namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005364class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005365 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005366 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005367public:
Richard Smith2e312c82012-03-03 22:46:17 +00005368 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005369 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005370
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005371 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005372 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005373 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005374 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005375 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005376 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005377 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005378 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005379 return true;
5380 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005381 bool Success(const llvm::APSInt &SI, const Expr *E) {
5382 return Success(SI, E, Result);
5383 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005384
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005385 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005386 assert(E->getType()->isIntegralOrEnumerationType() &&
5387 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005388 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005389 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005390 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005391 Result.getInt().setIsUnsigned(
5392 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005393 return true;
5394 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005395 bool Success(const llvm::APInt &I, const Expr *E) {
5396 return Success(I, E, Result);
5397 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005398
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005399 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005400 assert(E->getType()->isIntegralOrEnumerationType() &&
5401 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005402 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005403 return true;
5404 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005405 bool Success(uint64_t Value, const Expr *E) {
5406 return Success(Value, E, Result);
5407 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005408
Ken Dyckdbc01912011-03-11 02:13:43 +00005409 bool Success(CharUnits Size, const Expr *E) {
5410 return Success(Size.getQuantity(), E);
5411 }
5412
Richard Smith2e312c82012-03-03 22:46:17 +00005413 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005414 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005415 Result = V;
5416 return true;
5417 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005418 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005419 }
Mike Stump11289f42009-09-09 15:08:12 +00005420
Richard Smithfddd3842011-12-30 21:15:51 +00005421 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005422
Peter Collingbournee9200682011-05-13 03:29:01 +00005423 //===--------------------------------------------------------------------===//
5424 // Visitor Methods
5425 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005426
Chris Lattner7174bf32008-07-12 00:38:25 +00005427 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005428 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005429 }
5430 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005431 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005432 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005433
5434 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5435 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005436 if (CheckReferencedDecl(E, E->getDecl()))
5437 return true;
5438
5439 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005440 }
5441 bool VisitMemberExpr(const MemberExpr *E) {
5442 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005443 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005444 return true;
5445 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005446
5447 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005448 }
5449
Peter Collingbournee9200682011-05-13 03:29:01 +00005450 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005451 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005452 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005453 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005454
Peter Collingbournee9200682011-05-13 03:29:01 +00005455 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005456 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005457
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005458 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005459 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005460 }
Mike Stump11289f42009-09-09 15:08:12 +00005461
Ted Kremeneke65b0862012-03-06 20:05:56 +00005462 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5463 return Success(E->getValue(), E);
5464 }
5465
Richard Smith4ce706a2011-10-11 21:43:33 +00005466 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005467 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005468 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005469 }
5470
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005471 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005472 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005473 }
5474
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005475 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5476 return Success(E->getValue(), E);
5477 }
5478
Douglas Gregor29c42f22012-02-24 07:38:34 +00005479 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5480 return Success(E->getValue(), E);
5481 }
5482
John Wiegley6242b6a2011-04-28 00:16:57 +00005483 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5484 return Success(E->getValue(), E);
5485 }
5486
John Wiegleyf9f65842011-04-25 06:54:41 +00005487 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5488 return Success(E->getValue(), E);
5489 }
5490
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005491 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005492 bool VisitUnaryImag(const UnaryOperator *E);
5493
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005494 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005495 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005496
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005497private:
Ken Dyck160146e2010-01-27 17:10:57 +00005498 CharUnits GetAlignOfExpr(const Expr *E);
5499 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005500 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005501 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005502 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005503};
Chris Lattner05706e882008-07-11 18:11:29 +00005504} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005505
Richard Smith11562c52011-10-28 17:51:58 +00005506/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5507/// produce either the integer value or a pointer.
5508///
5509/// GCC has a heinous extension which folds casts between pointer types and
5510/// pointer-sized integral types. We support this by allowing the evaluation of
5511/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5512/// Some simple arithmetic on such values is supported (they are treated much
5513/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005514static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005515 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005516 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005517 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005518}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005519
Richard Smithf57d8cb2011-12-09 22:58:01 +00005520static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005521 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005522 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005523 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005524 if (!Val.isInt()) {
5525 // FIXME: It would be better to produce the diagnostic for casting
5526 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005527 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005528 return false;
5529 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005530 Result = Val.getInt();
5531 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005532}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005533
Richard Smithf57d8cb2011-12-09 22:58:01 +00005534/// Check whether the given declaration can be directly converted to an integral
5535/// rvalue. If not, no diagnostic is produced; there are other things we can
5536/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005537bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005538 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005539 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005540 // Check for signedness/width mismatches between E type and ECD value.
5541 bool SameSign = (ECD->getInitVal().isSigned()
5542 == E->getType()->isSignedIntegerOrEnumerationType());
5543 bool SameWidth = (ECD->getInitVal().getBitWidth()
5544 == Info.Ctx.getIntWidth(E->getType()));
5545 if (SameSign && SameWidth)
5546 return Success(ECD->getInitVal(), E);
5547 else {
5548 // Get rid of mismatch (otherwise Success assertions will fail)
5549 // by computing a new value matching the type of E.
5550 llvm::APSInt Val = ECD->getInitVal();
5551 if (!SameSign)
5552 Val.setIsSigned(!ECD->getInitVal().isSigned());
5553 if (!SameWidth)
5554 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5555 return Success(Val, E);
5556 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005557 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005558 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005559}
5560
Chris Lattner86ee2862008-10-06 06:40:35 +00005561/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5562/// as GCC.
5563static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5564 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005565 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005566 enum gcc_type_class {
5567 no_type_class = -1,
5568 void_type_class, integer_type_class, char_type_class,
5569 enumeral_type_class, boolean_type_class,
5570 pointer_type_class, reference_type_class, offset_type_class,
5571 real_type_class, complex_type_class,
5572 function_type_class, method_type_class,
5573 record_type_class, union_type_class,
5574 array_type_class, string_type_class,
5575 lang_type_class
5576 };
Mike Stump11289f42009-09-09 15:08:12 +00005577
5578 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005579 // ideal, however it is what gcc does.
5580 if (E->getNumArgs() == 0)
5581 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005582
Chris Lattner86ee2862008-10-06 06:40:35 +00005583 QualType ArgTy = E->getArg(0)->getType();
5584 if (ArgTy->isVoidType())
5585 return void_type_class;
5586 else if (ArgTy->isEnumeralType())
5587 return enumeral_type_class;
5588 else if (ArgTy->isBooleanType())
5589 return boolean_type_class;
5590 else if (ArgTy->isCharType())
5591 return string_type_class; // gcc doesn't appear to use char_type_class
5592 else if (ArgTy->isIntegerType())
5593 return integer_type_class;
5594 else if (ArgTy->isPointerType())
5595 return pointer_type_class;
5596 else if (ArgTy->isReferenceType())
5597 return reference_type_class;
5598 else if (ArgTy->isRealType())
5599 return real_type_class;
5600 else if (ArgTy->isComplexType())
5601 return complex_type_class;
5602 else if (ArgTy->isFunctionType())
5603 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005604 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005605 return record_type_class;
5606 else if (ArgTy->isUnionType())
5607 return union_type_class;
5608 else if (ArgTy->isArrayType())
5609 return array_type_class;
5610 else if (ArgTy->isUnionType())
5611 return union_type_class;
5612 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005613 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005614}
5615
Richard Smith5fab0c92011-12-28 19:48:30 +00005616/// EvaluateBuiltinConstantPForLValue - Determine the result of
5617/// __builtin_constant_p when applied to the given lvalue.
5618///
5619/// An lvalue is only "constant" if it is a pointer or reference to the first
5620/// character of a string literal.
5621template<typename LValue>
5622static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005623 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005624 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5625}
5626
5627/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5628/// GCC as we can manage.
5629static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5630 QualType ArgType = Arg->getType();
5631
5632 // __builtin_constant_p always has one operand. The rules which gcc follows
5633 // are not precisely documented, but are as follows:
5634 //
5635 // - If the operand is of integral, floating, complex or enumeration type,
5636 // and can be folded to a known value of that type, it returns 1.
5637 // - If the operand and can be folded to a pointer to the first character
5638 // of a string literal (or such a pointer cast to an integral type), it
5639 // returns 1.
5640 //
5641 // Otherwise, it returns 0.
5642 //
5643 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5644 // its support for this does not currently work.
5645 if (ArgType->isIntegralOrEnumerationType()) {
5646 Expr::EvalResult Result;
5647 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5648 return false;
5649
5650 APValue &V = Result.Val;
5651 if (V.getKind() == APValue::Int)
5652 return true;
5653
5654 return EvaluateBuiltinConstantPForLValue(V);
5655 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5656 return Arg->isEvaluatable(Ctx);
5657 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5658 LValue LV;
5659 Expr::EvalStatus Status;
5660 EvalInfo Info(Ctx, Status);
5661 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5662 : EvaluatePointer(Arg, LV, Info)) &&
5663 !Status.HasSideEffects)
5664 return EvaluateBuiltinConstantPForLValue(LV);
5665 }
5666
5667 // Anything else isn't considered to be sufficiently constant.
5668 return false;
5669}
5670
John McCall95007602010-05-10 23:27:23 +00005671/// Retrieves the "underlying object type" of the given expression,
5672/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005673QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5674 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5675 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005676 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005677 } else if (const Expr *E = B.get<const Expr*>()) {
5678 if (isa<CompoundLiteralExpr>(E))
5679 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005680 }
5681
5682 return QualType();
5683}
5684
Peter Collingbournee9200682011-05-13 03:29:01 +00005685bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005686 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005687
5688 {
5689 // The operand of __builtin_object_size is never evaluated for side-effects.
5690 // If there are any, but we can determine the pointed-to object anyway, then
5691 // ignore the side-effects.
5692 SpeculativeEvaluationRAII SpeculativeEval(Info);
5693 if (!EvaluatePointer(E->getArg(0), Base, Info))
5694 return false;
5695 }
John McCall95007602010-05-10 23:27:23 +00005696
5697 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005698 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005699
Richard Smithce40ad62011-11-12 22:28:03 +00005700 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005701 if (T.isNull() ||
5702 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005703 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005704 T->isVariablyModifiedType() ||
5705 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005706 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005707
5708 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5709 CharUnits Offset = Base.getLValueOffset();
5710
5711 if (!Offset.isNegative() && Offset <= Size)
5712 Size -= Offset;
5713 else
5714 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005715 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005716}
5717
Peter Collingbournee9200682011-05-13 03:29:01 +00005718bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005719 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005720 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005721 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005722
5723 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005724 if (TryEvaluateBuiltinObjectSize(E))
5725 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005726
Richard Smith0421ce72012-08-07 04:16:51 +00005727 // If evaluating the argument has side-effects, we can't determine the size
5728 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5729 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005730 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005731 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005732 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005733 return Success(0, E);
5734 }
Mike Stump876387b2009-10-27 22:09:17 +00005735
Richard Smith01ade172012-05-23 04:13:20 +00005736 // Expression had no side effects, but we couldn't statically determine the
5737 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005738 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005739 }
5740
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005741 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005742 case Builtin::BI__builtin_bswap32:
5743 case Builtin::BI__builtin_bswap64: {
5744 APSInt Val;
5745 if (!EvaluateInteger(E->getArg(0), Val, Info))
5746 return false;
5747
5748 return Success(Val.byteSwap(), E);
5749 }
5750
Richard Smith8889a3d2013-06-13 06:26:32 +00005751 case Builtin::BI__builtin_classify_type:
5752 return Success(EvaluateBuiltinClassifyType(E), E);
5753
5754 // FIXME: BI__builtin_clrsb
5755 // FIXME: BI__builtin_clrsbl
5756 // FIXME: BI__builtin_clrsbll
5757
Richard Smith80b3c8e2013-06-13 05:04:16 +00005758 case Builtin::BI__builtin_clz:
5759 case Builtin::BI__builtin_clzl:
5760 case Builtin::BI__builtin_clzll: {
5761 APSInt Val;
5762 if (!EvaluateInteger(E->getArg(0), Val, Info))
5763 return false;
5764 if (!Val)
5765 return Error(E);
5766
5767 return Success(Val.countLeadingZeros(), E);
5768 }
5769
Richard Smith8889a3d2013-06-13 06:26:32 +00005770 case Builtin::BI__builtin_constant_p:
5771 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5772
Richard Smith80b3c8e2013-06-13 05:04:16 +00005773 case Builtin::BI__builtin_ctz:
5774 case Builtin::BI__builtin_ctzl:
5775 case Builtin::BI__builtin_ctzll: {
5776 APSInt Val;
5777 if (!EvaluateInteger(E->getArg(0), Val, Info))
5778 return false;
5779 if (!Val)
5780 return Error(E);
5781
5782 return Success(Val.countTrailingZeros(), E);
5783 }
5784
Richard Smith8889a3d2013-06-13 06:26:32 +00005785 case Builtin::BI__builtin_eh_return_data_regno: {
5786 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5787 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5788 return Success(Operand, E);
5789 }
5790
5791 case Builtin::BI__builtin_expect:
5792 return Visit(E->getArg(0));
5793
5794 case Builtin::BI__builtin_ffs:
5795 case Builtin::BI__builtin_ffsl:
5796 case Builtin::BI__builtin_ffsll: {
5797 APSInt Val;
5798 if (!EvaluateInteger(E->getArg(0), Val, Info))
5799 return false;
5800
5801 unsigned N = Val.countTrailingZeros();
5802 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5803 }
5804
5805 case Builtin::BI__builtin_fpclassify: {
5806 APFloat Val(0.0);
5807 if (!EvaluateFloat(E->getArg(5), Val, Info))
5808 return false;
5809 unsigned Arg;
5810 switch (Val.getCategory()) {
5811 case APFloat::fcNaN: Arg = 0; break;
5812 case APFloat::fcInfinity: Arg = 1; break;
5813 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5814 case APFloat::fcZero: Arg = 4; break;
5815 }
5816 return Visit(E->getArg(Arg));
5817 }
5818
5819 case Builtin::BI__builtin_isinf_sign: {
5820 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00005821 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00005822 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5823 }
5824
5825 case Builtin::BI__builtin_parity:
5826 case Builtin::BI__builtin_parityl:
5827 case Builtin::BI__builtin_parityll: {
5828 APSInt Val;
5829 if (!EvaluateInteger(E->getArg(0), Val, Info))
5830 return false;
5831
5832 return Success(Val.countPopulation() % 2, E);
5833 }
5834
Richard Smith80b3c8e2013-06-13 05:04:16 +00005835 case Builtin::BI__builtin_popcount:
5836 case Builtin::BI__builtin_popcountl:
5837 case Builtin::BI__builtin_popcountll: {
5838 APSInt Val;
5839 if (!EvaluateInteger(E->getArg(0), Val, Info))
5840 return false;
5841
5842 return Success(Val.countPopulation(), E);
5843 }
5844
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005845 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005846 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005847 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005848 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005849 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5850 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005851 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005852 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005853 case Builtin::BI__builtin_strlen:
5854 // As an extension, we support strlen() and __builtin_strlen() as constant
5855 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005856 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005857 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5858 // The string literal may have embedded null characters. Find the first
5859 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005860 StringRef Str = S->getString();
5861 StringRef::size_type Pos = Str.find(0);
5862 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005863 Str = Str.substr(0, Pos);
5864
5865 return Success(Str.size(), E);
5866 }
5867
Richard Smithf57d8cb2011-12-09 22:58:01 +00005868 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005869
Richard Smith01ba47d2012-04-13 00:45:38 +00005870 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005871 case Builtin::BI__atomic_is_lock_free:
5872 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005873 APSInt SizeVal;
5874 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5875 return false;
5876
5877 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5878 // of two less than the maximum inline atomic width, we know it is
5879 // lock-free. If the size isn't a power of two, or greater than the
5880 // maximum alignment where we promote atomics, we know it is not lock-free
5881 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5882 // the answer can only be determined at runtime; for example, 16-byte
5883 // atomics have lock-free implementations on some, but not all,
5884 // x86-64 processors.
5885
5886 // Check power-of-two.
5887 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005888 if (Size.isPowerOfTwo()) {
5889 // Check against inlining width.
5890 unsigned InlineWidthBits =
5891 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5892 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5893 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5894 Size == CharUnits::One() ||
5895 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5896 Expr::NPC_NeverValueDependent))
5897 // OK, we will inline appropriately-aligned operations of this size,
5898 // and _Atomic(T) is appropriately-aligned.
5899 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005900
Richard Smith01ba47d2012-04-13 00:45:38 +00005901 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5902 castAs<PointerType>()->getPointeeType();
5903 if (!PointeeType->isIncompleteType() &&
5904 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5905 // OK, we will inline operations on this object.
5906 return Success(1, E);
5907 }
5908 }
5909 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005910
Richard Smith01ba47d2012-04-13 00:45:38 +00005911 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5912 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005913 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005914 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005915}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005916
Richard Smith8b3497e2011-10-31 01:37:14 +00005917static bool HasSameBase(const LValue &A, const LValue &B) {
5918 if (!A.getLValueBase())
5919 return !B.getLValueBase();
5920 if (!B.getLValueBase())
5921 return false;
5922
Richard Smithce40ad62011-11-12 22:28:03 +00005923 if (A.getLValueBase().getOpaqueValue() !=
5924 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005925 const Decl *ADecl = GetLValueBaseDecl(A);
5926 if (!ADecl)
5927 return false;
5928 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005929 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005930 return false;
5931 }
5932
5933 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005934 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005935}
5936
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005937namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005938
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005939/// \brief Data recursive integer evaluator of certain binary operators.
5940///
5941/// We use a data recursive algorithm for binary operators so that we are able
5942/// to handle extreme cases of chained binary operators without causing stack
5943/// overflow.
5944class DataRecursiveIntBinOpEvaluator {
5945 struct EvalResult {
5946 APValue Val;
5947 bool Failed;
5948
5949 EvalResult() : Failed(false) { }
5950
5951 void swap(EvalResult &RHS) {
5952 Val.swap(RHS.Val);
5953 Failed = RHS.Failed;
5954 RHS.Failed = false;
5955 }
5956 };
5957
5958 struct Job {
5959 const Expr *E;
5960 EvalResult LHSResult; // meaningful only for binary operator expression.
5961 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5962
5963 Job() : StoredInfo(0) { }
5964 void startSpeculativeEval(EvalInfo &Info) {
5965 OldEvalStatus = Info.EvalStatus;
5966 Info.EvalStatus.Diag = 0;
5967 StoredInfo = &Info;
5968 }
5969 ~Job() {
5970 if (StoredInfo) {
5971 StoredInfo->EvalStatus = OldEvalStatus;
5972 }
5973 }
5974 private:
5975 EvalInfo *StoredInfo; // non-null if status changed.
5976 Expr::EvalStatus OldEvalStatus;
5977 };
5978
5979 SmallVector<Job, 16> Queue;
5980
5981 IntExprEvaluator &IntEval;
5982 EvalInfo &Info;
5983 APValue &FinalResult;
5984
5985public:
5986 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5987 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5988
5989 /// \brief True if \param E is a binary operator that we are going to handle
5990 /// data recursively.
5991 /// We handle binary operators that are comma, logical, or that have operands
5992 /// with integral or enumeration type.
5993 static bool shouldEnqueue(const BinaryOperator *E) {
5994 return E->getOpcode() == BO_Comma ||
5995 E->isLogicalOp() ||
5996 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5997 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005998 }
5999
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006000 bool Traverse(const BinaryOperator *E) {
6001 enqueue(E);
6002 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006003 while (!Queue.empty())
6004 process(PrevResult);
6005
6006 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006007
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006008 FinalResult.swap(PrevResult.Val);
6009 return true;
6010 }
6011
6012private:
6013 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6014 return IntEval.Success(Value, E, Result);
6015 }
6016 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6017 return IntEval.Success(Value, E, Result);
6018 }
6019 bool Error(const Expr *E) {
6020 return IntEval.Error(E);
6021 }
6022 bool Error(const Expr *E, diag::kind D) {
6023 return IntEval.Error(E, D);
6024 }
6025
6026 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6027 return Info.CCEDiag(E, D);
6028 }
6029
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006030 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6031 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006032 bool &SuppressRHSDiags);
6033
6034 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6035 const BinaryOperator *E, APValue &Result);
6036
6037 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6038 Result.Failed = !Evaluate(Result.Val, Info, E);
6039 if (Result.Failed)
6040 Result.Val = APValue();
6041 }
6042
Richard Trieuba4d0872012-03-21 23:30:30 +00006043 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006044
6045 void enqueue(const Expr *E) {
6046 E = E->IgnoreParens();
6047 Queue.resize(Queue.size()+1);
6048 Queue.back().E = E;
6049 Queue.back().Kind = Job::AnyExprKind;
6050 }
6051};
6052
6053}
6054
6055bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006056 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006057 bool &SuppressRHSDiags) {
6058 if (E->getOpcode() == BO_Comma) {
6059 // Ignore LHS but note if we could not evaluate it.
6060 if (LHSResult.Failed)
6061 Info.EvalStatus.HasSideEffects = true;
6062 return true;
6063 }
6064
6065 if (E->isLogicalOp()) {
6066 bool lhsResult;
6067 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006068 // We were able to evaluate the LHS, see if we can get away with not
6069 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006070 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006071 Success(lhsResult, E, LHSResult.Val);
6072 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006073 }
6074 } else {
6075 // Since we weren't able to evaluate the left hand side, it
6076 // must have had side effects.
6077 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006078
6079 // We can't evaluate the LHS; however, sometimes the result
6080 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6081 // Don't ignore RHS and suppress diagnostics from this arm.
6082 SuppressRHSDiags = true;
6083 }
6084
6085 return true;
6086 }
6087
6088 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6089 E->getRHS()->getType()->isIntegralOrEnumerationType());
6090
6091 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006092 return false; // Ignore RHS;
6093
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006094 return true;
6095}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006096
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006097bool DataRecursiveIntBinOpEvaluator::
6098 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6099 const BinaryOperator *E, APValue &Result) {
6100 if (E->getOpcode() == BO_Comma) {
6101 if (RHSResult.Failed)
6102 return false;
6103 Result = RHSResult.Val;
6104 return true;
6105 }
6106
6107 if (E->isLogicalOp()) {
6108 bool lhsResult, rhsResult;
6109 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6110 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6111
6112 if (LHSIsOK) {
6113 if (RHSIsOK) {
6114 if (E->getOpcode() == BO_LOr)
6115 return Success(lhsResult || rhsResult, E, Result);
6116 else
6117 return Success(lhsResult && rhsResult, E, Result);
6118 }
6119 } else {
6120 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006121 // We can't evaluate the LHS; however, sometimes the result
6122 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6123 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006124 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006125 }
6126 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006127
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006128 return false;
6129 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006130
6131 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6132 E->getRHS()->getType()->isIntegralOrEnumerationType());
6133
6134 if (LHSResult.Failed || RHSResult.Failed)
6135 return false;
6136
6137 const APValue &LHSVal = LHSResult.Val;
6138 const APValue &RHSVal = RHSResult.Val;
6139
6140 // Handle cases like (unsigned long)&a + 4.
6141 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6142 Result = LHSVal;
6143 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6144 RHSVal.getInt().getZExtValue());
6145 if (E->getOpcode() == BO_Add)
6146 Result.getLValueOffset() += AdditionalOffset;
6147 else
6148 Result.getLValueOffset() -= AdditionalOffset;
6149 return true;
6150 }
6151
6152 // Handle cases like 4 + (unsigned long)&a
6153 if (E->getOpcode() == BO_Add &&
6154 RHSVal.isLValue() && LHSVal.isInt()) {
6155 Result = RHSVal;
6156 Result.getLValueOffset() += CharUnits::fromQuantity(
6157 LHSVal.getInt().getZExtValue());
6158 return true;
6159 }
6160
6161 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6162 // Handle (intptr_t)&&A - (intptr_t)&&B.
6163 if (!LHSVal.getLValueOffset().isZero() ||
6164 !RHSVal.getLValueOffset().isZero())
6165 return false;
6166 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6167 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6168 if (!LHSExpr || !RHSExpr)
6169 return false;
6170 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6171 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6172 if (!LHSAddrExpr || !RHSAddrExpr)
6173 return false;
6174 // Make sure both labels come from the same function.
6175 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6176 RHSAddrExpr->getLabel()->getDeclContext())
6177 return false;
6178 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6179 return true;
6180 }
Richard Smith43e77732013-05-07 04:50:00 +00006181
6182 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006183 if (!LHSVal.isInt() || !RHSVal.isInt())
6184 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006185
6186 // Set up the width and signedness manually, in case it can't be deduced
6187 // from the operation we're performing.
6188 // FIXME: Don't do this in the cases where we can deduce it.
6189 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6190 E->getType()->isUnsignedIntegerOrEnumerationType());
6191 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6192 RHSVal.getInt(), Value))
6193 return false;
6194 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006195}
6196
Richard Trieuba4d0872012-03-21 23:30:30 +00006197void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006198 Job &job = Queue.back();
6199
6200 switch (job.Kind) {
6201 case Job::AnyExprKind: {
6202 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6203 if (shouldEnqueue(Bop)) {
6204 job.Kind = Job::BinOpKind;
6205 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006206 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006207 }
6208 }
6209
6210 EvaluateExpr(job.E, Result);
6211 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006212 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006213 }
6214
6215 case Job::BinOpKind: {
6216 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006217 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006218 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006219 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006220 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006221 }
6222 if (SuppressRHSDiags)
6223 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006224 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006225 job.Kind = Job::BinOpVisitedLHSKind;
6226 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006227 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006228 }
6229
6230 case Job::BinOpVisitedLHSKind: {
6231 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6232 EvalResult RHS;
6233 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006234 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006235 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006236 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006237 }
6238 }
6239
6240 llvm_unreachable("Invalid Job::Kind!");
6241}
6242
6243bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6244 if (E->isAssignmentOp())
6245 return Error(E);
6246
6247 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6248 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006249
Anders Carlssonacc79812008-11-16 07:17:21 +00006250 QualType LHSTy = E->getLHS()->getType();
6251 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006252
6253 if (LHSTy->isAnyComplexType()) {
6254 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006255 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006256
Richard Smith253c2a32012-01-27 01:14:48 +00006257 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6258 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006259 return false;
6260
Richard Smith253c2a32012-01-27 01:14:48 +00006261 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006262 return false;
6263
6264 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006265 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006266 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006267 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006268 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6269
John McCalle3027922010-08-25 11:45:40 +00006270 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006271 return Success((CR_r == APFloat::cmpEqual &&
6272 CR_i == APFloat::cmpEqual), E);
6273 else {
John McCalle3027922010-08-25 11:45:40 +00006274 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006275 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006276 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006277 CR_r == APFloat::cmpLessThan ||
6278 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006279 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006280 CR_i == APFloat::cmpLessThan ||
6281 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006282 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006283 } else {
John McCalle3027922010-08-25 11:45:40 +00006284 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006285 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6286 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6287 else {
John McCalle3027922010-08-25 11:45:40 +00006288 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006289 "Invalid compex comparison.");
6290 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6291 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6292 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006293 }
6294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295
Anders Carlssonacc79812008-11-16 07:17:21 +00006296 if (LHSTy->isRealFloatingType() &&
6297 RHSTy->isRealFloatingType()) {
6298 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006299
Richard Smith253c2a32012-01-27 01:14:48 +00006300 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6301 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006302 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006303
Richard Smith253c2a32012-01-27 01:14:48 +00006304 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006305 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006306
Anders Carlssonacc79812008-11-16 07:17:21 +00006307 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006308
Anders Carlssonacc79812008-11-16 07:17:21 +00006309 switch (E->getOpcode()) {
6310 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006311 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006312 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006313 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006314 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006315 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006316 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006317 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006318 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006319 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006320 E);
John McCalle3027922010-08-25 11:45:40 +00006321 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006322 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006323 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006324 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006325 || CR == APFloat::cmpLessThan
6326 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006327 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006328 }
Mike Stump11289f42009-09-09 15:08:12 +00006329
Eli Friedmana38da572009-04-28 19:17:36 +00006330 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006331 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006332 LValue LHSValue, RHSValue;
6333
6334 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6335 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006336 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006337
Richard Smith253c2a32012-01-27 01:14:48 +00006338 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006339 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006340
Richard Smith8b3497e2011-10-31 01:37:14 +00006341 // Reject differing bases from the normal codepath; we special-case
6342 // comparisons to null.
6343 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006344 if (E->getOpcode() == BO_Sub) {
6345 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006346 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6347 return false;
6348 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006349 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006350 if (!LHSExpr || !RHSExpr)
6351 return false;
6352 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6353 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6354 if (!LHSAddrExpr || !RHSAddrExpr)
6355 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006356 // Make sure both labels come from the same function.
6357 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6358 RHSAddrExpr->getLabel()->getDeclContext())
6359 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006360 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006361 return true;
6362 }
Richard Smith83c68212011-10-31 05:11:32 +00006363 // Inequalities and subtractions between unrelated pointers have
6364 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006365 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006366 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006367 // A constant address may compare equal to the address of a symbol.
6368 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006369 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006370 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6371 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006372 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006373 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006374 // distinct addresses. In clang, the result of such a comparison is
6375 // unspecified, so it is not a constant expression. However, we do know
6376 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006377 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6378 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006379 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006380 // We can't tell whether weak symbols will end up pointing to the same
6381 // object.
6382 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006383 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006384 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006385 // (Note that clang defaults to -fmerge-all-constants, which can
6386 // lead to inconsistent results for comparisons involving the address
6387 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006388 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006389 }
Eli Friedman64004332009-03-23 04:38:34 +00006390
Richard Smith1b470412012-02-01 08:10:20 +00006391 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6392 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6393
Richard Smith84f6dcf2012-02-02 01:16:57 +00006394 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6395 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6396
John McCalle3027922010-08-25 11:45:40 +00006397 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006398 // C++11 [expr.add]p6:
6399 // Unless both pointers point to elements of the same array object, or
6400 // one past the last element of the array object, the behavior is
6401 // undefined.
6402 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6403 !AreElementsOfSameArray(getType(LHSValue.Base),
6404 LHSDesignator, RHSDesignator))
6405 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6406
Chris Lattner882bdf22010-04-20 17:13:14 +00006407 QualType Type = E->getLHS()->getType();
6408 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006409
Richard Smithd62306a2011-11-10 06:34:14 +00006410 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006411 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006412 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006413
Richard Smith1b470412012-02-01 08:10:20 +00006414 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6415 // and produce incorrect results when it overflows. Such behavior
6416 // appears to be non-conforming, but is common, so perhaps we should
6417 // assume the standard intended for such cases to be undefined behavior
6418 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006419
Richard Smith1b470412012-02-01 08:10:20 +00006420 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6421 // overflow in the final conversion to ptrdiff_t.
6422 APSInt LHS(
6423 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6424 APSInt RHS(
6425 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6426 APSInt ElemSize(
6427 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6428 APSInt TrueResult = (LHS - RHS) / ElemSize;
6429 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6430
6431 if (Result.extend(65) != TrueResult)
6432 HandleOverflow(Info, E, TrueResult, E->getType());
6433 return Success(Result, E);
6434 }
Richard Smithde21b242012-01-31 06:41:30 +00006435
6436 // C++11 [expr.rel]p3:
6437 // Pointers to void (after pointer conversions) can be compared, with a
6438 // result defined as follows: If both pointers represent the same
6439 // address or are both the null pointer value, the result is true if the
6440 // operator is <= or >= and false otherwise; otherwise the result is
6441 // unspecified.
6442 // We interpret this as applying to pointers to *cv* void.
6443 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006444 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006445 CCEDiag(E, diag::note_constexpr_void_comparison);
6446
Richard Smith84f6dcf2012-02-02 01:16:57 +00006447 // C++11 [expr.rel]p2:
6448 // - If two pointers point to non-static data members of the same object,
6449 // or to subobjects or array elements fo such members, recursively, the
6450 // pointer to the later declared member compares greater provided the
6451 // two members have the same access control and provided their class is
6452 // not a union.
6453 // [...]
6454 // - Otherwise pointer comparisons are unspecified.
6455 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6456 E->isRelationalOp()) {
6457 bool WasArrayIndex;
6458 unsigned Mismatch =
6459 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6460 RHSDesignator, WasArrayIndex);
6461 // At the point where the designators diverge, the comparison has a
6462 // specified value if:
6463 // - we are comparing array indices
6464 // - we are comparing fields of a union, or fields with the same access
6465 // Otherwise, the result is unspecified and thus the comparison is not a
6466 // constant expression.
6467 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6468 Mismatch < RHSDesignator.Entries.size()) {
6469 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6470 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6471 if (!LF && !RF)
6472 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6473 else if (!LF)
6474 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6475 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6476 << RF->getParent() << RF;
6477 else if (!RF)
6478 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6479 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6480 << LF->getParent() << LF;
6481 else if (!LF->getParent()->isUnion() &&
6482 LF->getAccess() != RF->getAccess())
6483 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6484 << LF << LF->getAccess() << RF << RF->getAccess()
6485 << LF->getParent();
6486 }
6487 }
6488
Eli Friedman6c31cb42012-04-16 04:30:08 +00006489 // The comparison here must be unsigned, and performed with the same
6490 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006491 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6492 uint64_t CompareLHS = LHSOffset.getQuantity();
6493 uint64_t CompareRHS = RHSOffset.getQuantity();
6494 assert(PtrSize <= 64 && "Unexpected pointer width");
6495 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6496 CompareLHS &= Mask;
6497 CompareRHS &= Mask;
6498
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006499 // If there is a base and this is a relational operator, we can only
6500 // compare pointers within the object in question; otherwise, the result
6501 // depends on where the object is located in memory.
6502 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6503 QualType BaseTy = getType(LHSValue.Base);
6504 if (BaseTy->isIncompleteType())
6505 return Error(E);
6506 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6507 uint64_t OffsetLimit = Size.getQuantity();
6508 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6509 return Error(E);
6510 }
6511
Richard Smith8b3497e2011-10-31 01:37:14 +00006512 switch (E->getOpcode()) {
6513 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006514 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6515 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6516 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6517 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6518 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6519 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006520 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006521 }
6522 }
Richard Smith7bb00672012-02-01 01:42:44 +00006523
6524 if (LHSTy->isMemberPointerType()) {
6525 assert(E->isEqualityOp() && "unexpected member pointer operation");
6526 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6527
6528 MemberPtr LHSValue, RHSValue;
6529
6530 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6531 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6532 return false;
6533
6534 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6535 return false;
6536
6537 // C++11 [expr.eq]p2:
6538 // If both operands are null, they compare equal. Otherwise if only one is
6539 // null, they compare unequal.
6540 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6541 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6542 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6543 }
6544
6545 // Otherwise if either is a pointer to a virtual member function, the
6546 // result is unspecified.
6547 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6548 if (MD->isVirtual())
6549 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6550 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6551 if (MD->isVirtual())
6552 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6553
6554 // Otherwise they compare equal if and only if they would refer to the
6555 // same member of the same most derived object or the same subobject if
6556 // they were dereferenced with a hypothetical object of the associated
6557 // class type.
6558 bool Equal = LHSValue == RHSValue;
6559 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6560 }
6561
Richard Smithab44d9b2012-02-14 22:35:28 +00006562 if (LHSTy->isNullPtrType()) {
6563 assert(E->isComparisonOp() && "unexpected nullptr operation");
6564 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6565 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6566 // are compared, the result is true of the operator is <=, >= or ==, and
6567 // false otherwise.
6568 BinaryOperator::Opcode Opcode = E->getOpcode();
6569 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6570 }
6571
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006572 assert((!LHSTy->isIntegralOrEnumerationType() ||
6573 !RHSTy->isIntegralOrEnumerationType()) &&
6574 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6575 // We can't continue from here for non-integral types.
6576 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006577}
6578
Ken Dyck160146e2010-01-27 17:10:57 +00006579CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006580 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6581 // result shall be the alignment of the referenced type."
6582 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6583 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006584
6585 // __alignof is defined to return the preferred alignment.
6586 return Info.Ctx.toCharUnitsFromBits(
6587 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006588}
6589
Ken Dyck160146e2010-01-27 17:10:57 +00006590CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006591 E = E->IgnoreParens();
6592
John McCall768439e2013-05-06 07:40:34 +00006593 // The kinds of expressions that we have special-case logic here for
6594 // should be kept up to date with the special checks for those
6595 // expressions in Sema.
6596
Chris Lattner68061312009-01-24 21:53:27 +00006597 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006598 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006599 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006600 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6601 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006602
Chris Lattner68061312009-01-24 21:53:27 +00006603 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006604 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6605 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006606
Chris Lattner24aeeab2009-01-24 21:09:06 +00006607 return GetAlignOfType(E->getType());
6608}
6609
6610
Peter Collingbournee190dee2011-03-11 19:24:49 +00006611/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6612/// a result as the expression's type.
6613bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6614 const UnaryExprOrTypeTraitExpr *E) {
6615 switch(E->getKind()) {
6616 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006617 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006618 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006619 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006620 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006621 }
Eli Friedman64004332009-03-23 04:38:34 +00006622
Peter Collingbournee190dee2011-03-11 19:24:49 +00006623 case UETT_VecStep: {
6624 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006625
Peter Collingbournee190dee2011-03-11 19:24:49 +00006626 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006627 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006628
Peter Collingbournee190dee2011-03-11 19:24:49 +00006629 // The vec_step built-in functions that take a 3-component
6630 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6631 if (n == 3)
6632 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006633
Peter Collingbournee190dee2011-03-11 19:24:49 +00006634 return Success(n, E);
6635 } else
6636 return Success(1, E);
6637 }
6638
6639 case UETT_SizeOf: {
6640 QualType SrcTy = E->getTypeOfArgument();
6641 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6642 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006643 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6644 SrcTy = Ref->getPointeeType();
6645
Richard Smithd62306a2011-11-10 06:34:14 +00006646 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006647 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006648 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006649 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006650 }
6651 }
6652
6653 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006654}
6655
Peter Collingbournee9200682011-05-13 03:29:01 +00006656bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006657 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006658 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006659 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006660 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006661 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006662 for (unsigned i = 0; i != n; ++i) {
6663 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6664 switch (ON.getKind()) {
6665 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006666 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006667 APSInt IdxResult;
6668 if (!EvaluateInteger(Idx, IdxResult, Info))
6669 return false;
6670 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6671 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006672 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006673 CurrentType = AT->getElementType();
6674 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6675 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006676 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006677 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006678
Douglas Gregor882211c2010-04-28 22:16:22 +00006679 case OffsetOfExpr::OffsetOfNode::Field: {
6680 FieldDecl *MemberDecl = ON.getField();
6681 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006682 if (!RT)
6683 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006684 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006685 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006686 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006687 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006688 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006689 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006690 CurrentType = MemberDecl->getType().getNonReferenceType();
6691 break;
6692 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006693
Douglas Gregor882211c2010-04-28 22:16:22 +00006694 case OffsetOfExpr::OffsetOfNode::Identifier:
6695 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006696
Douglas Gregord1702062010-04-29 00:18:15 +00006697 case OffsetOfExpr::OffsetOfNode::Base: {
6698 CXXBaseSpecifier *BaseSpec = ON.getBase();
6699 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006700 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006701
6702 // Find the layout of the class whose base we are looking into.
6703 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006704 if (!RT)
6705 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006706 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006707 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006708 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6709
6710 // Find the base class itself.
6711 CurrentType = BaseSpec->getType();
6712 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6713 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006714 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006715
6716 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006717 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006718 break;
6719 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006720 }
6721 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006722 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006723}
6724
Chris Lattnere13042c2008-07-11 19:10:17 +00006725bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006726 switch (E->getOpcode()) {
6727 default:
6728 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6729 // See C99 6.6p3.
6730 return Error(E);
6731 case UO_Extension:
6732 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6733 // If so, we could clear the diagnostic ID.
6734 return Visit(E->getSubExpr());
6735 case UO_Plus:
6736 // The result is just the value.
6737 return Visit(E->getSubExpr());
6738 case UO_Minus: {
6739 if (!Visit(E->getSubExpr()))
6740 return false;
6741 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006742 const APSInt &Value = Result.getInt();
6743 if (Value.isSigned() && Value.isMinSignedValue())
6744 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6745 E->getType());
6746 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006747 }
6748 case UO_Not: {
6749 if (!Visit(E->getSubExpr()))
6750 return false;
6751 if (!Result.isInt()) return Error(E);
6752 return Success(~Result.getInt(), E);
6753 }
6754 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006755 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006756 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006757 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006758 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006759 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006760 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006761}
Mike Stump11289f42009-09-09 15:08:12 +00006762
Chris Lattner477c4be2008-07-12 01:15:53 +00006763/// HandleCast - This is used to evaluate implicit or explicit casts where the
6764/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006765bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6766 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006767 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006768 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006769
Eli Friedmanc757de22011-03-25 00:43:55 +00006770 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006771 case CK_BaseToDerived:
6772 case CK_DerivedToBase:
6773 case CK_UncheckedDerivedToBase:
6774 case CK_Dynamic:
6775 case CK_ToUnion:
6776 case CK_ArrayToPointerDecay:
6777 case CK_FunctionToPointerDecay:
6778 case CK_NullToPointer:
6779 case CK_NullToMemberPointer:
6780 case CK_BaseToDerivedMemberPointer:
6781 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006782 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006783 case CK_ConstructorConversion:
6784 case CK_IntegralToPointer:
6785 case CK_ToVoid:
6786 case CK_VectorSplat:
6787 case CK_IntegralToFloating:
6788 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006789 case CK_CPointerToObjCPointerCast:
6790 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006791 case CK_AnyPointerToBlockPointerCast:
6792 case CK_ObjCObjectLValueCast:
6793 case CK_FloatingRealToComplex:
6794 case CK_FloatingComplexToReal:
6795 case CK_FloatingComplexCast:
6796 case CK_FloatingComplexToIntegralComplex:
6797 case CK_IntegralRealToComplex:
6798 case CK_IntegralComplexCast:
6799 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006800 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006801 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006802 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006803 llvm_unreachable("invalid cast kind for integral value");
6804
Eli Friedman9faf2f92011-03-25 19:07:11 +00006805 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006806 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006807 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006808 case CK_ARCProduceObject:
6809 case CK_ARCConsumeObject:
6810 case CK_ARCReclaimReturnedObject:
6811 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006812 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006813 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006814
Richard Smith4ef685b2012-01-17 21:17:26 +00006815 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006816 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006817 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006818 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006819 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006820
6821 case CK_MemberPointerToBoolean:
6822 case CK_PointerToBoolean:
6823 case CK_IntegralToBoolean:
6824 case CK_FloatingToBoolean:
6825 case CK_FloatingComplexToBoolean:
6826 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006827 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006828 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006829 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006830 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006831 }
6832
Eli Friedmanc757de22011-03-25 00:43:55 +00006833 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006834 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006835 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006836
Eli Friedman742421e2009-02-20 01:15:07 +00006837 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006838 // Allow casts of address-of-label differences if they are no-ops
6839 // or narrowing. (The narrowing case isn't actually guaranteed to
6840 // be constant-evaluatable except in some narrow cases which are hard
6841 // to detect here. We let it through on the assumption the user knows
6842 // what they are doing.)
6843 if (Result.isAddrLabelDiff())
6844 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006845 // Only allow casts of lvalues if they are lossless.
6846 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6847 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006848
Richard Smith911e1422012-01-30 22:27:01 +00006849 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6850 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006851 }
Mike Stump11289f42009-09-09 15:08:12 +00006852
Eli Friedmanc757de22011-03-25 00:43:55 +00006853 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006854 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6855
John McCall45d55e42010-05-07 21:00:08 +00006856 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006857 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006858 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006859
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006860 if (LV.getLValueBase()) {
6861 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006862 // FIXME: Allow a larger integer size than the pointer size, and allow
6863 // narrowing back down to pointer width in subsequent integral casts.
6864 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006865 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006866 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006867
Richard Smithcf74da72011-11-16 07:18:12 +00006868 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006869 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006870 return true;
6871 }
6872
Ken Dyck02990832010-01-15 12:37:54 +00006873 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6874 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006875 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006876 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006877
Eli Friedmanc757de22011-03-25 00:43:55 +00006878 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006879 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006880 if (!EvaluateComplex(SubExpr, C, Info))
6881 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006882 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006883 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006884
Eli Friedmanc757de22011-03-25 00:43:55 +00006885 case CK_FloatingToIntegral: {
6886 APFloat F(0.0);
6887 if (!EvaluateFloat(SubExpr, F, Info))
6888 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006889
Richard Smith357362d2011-12-13 06:39:58 +00006890 APSInt Value;
6891 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6892 return false;
6893 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006894 }
6895 }
Mike Stump11289f42009-09-09 15:08:12 +00006896
Eli Friedmanc757de22011-03-25 00:43:55 +00006897 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006898}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006899
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006900bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6901 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006902 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006903 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6904 return false;
6905 if (!LV.isComplexInt())
6906 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006907 return Success(LV.getComplexIntReal(), E);
6908 }
6909
6910 return Visit(E->getSubExpr());
6911}
6912
Eli Friedman4e7a2412009-02-27 04:45:43 +00006913bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006914 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006915 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006916 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6917 return false;
6918 if (!LV.isComplexInt())
6919 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006920 return Success(LV.getComplexIntImag(), E);
6921 }
6922
Richard Smith4a678122011-10-24 18:44:57 +00006923 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006924 return Success(0, E);
6925}
6926
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006927bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6928 return Success(E->getPackLength(), E);
6929}
6930
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006931bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6932 return Success(E->getValue(), E);
6933}
6934
Chris Lattner05706e882008-07-11 18:11:29 +00006935//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006936// Float Evaluation
6937//===----------------------------------------------------------------------===//
6938
6939namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006940class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006941 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006942 APFloat &Result;
6943public:
6944 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006945 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006946
Richard Smith2e312c82012-03-03 22:46:17 +00006947 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006948 Result = V.getFloat();
6949 return true;
6950 }
Eli Friedman24c01542008-08-22 00:06:13 +00006951
Richard Smithfddd3842011-12-30 21:15:51 +00006952 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006953 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6954 return true;
6955 }
6956
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006957 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006958
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006959 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006960 bool VisitBinaryOperator(const BinaryOperator *E);
6961 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006962 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006963
John McCallb1fb0d32010-05-07 22:08:54 +00006964 bool VisitUnaryReal(const UnaryOperator *E);
6965 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006966
Richard Smithfddd3842011-12-30 21:15:51 +00006967 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006968};
6969} // end anonymous namespace
6970
6971static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006972 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006973 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006974}
6975
Jay Foad39c79802011-01-12 09:06:06 +00006976static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006977 QualType ResultTy,
6978 const Expr *Arg,
6979 bool SNaN,
6980 llvm::APFloat &Result) {
6981 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6982 if (!S) return false;
6983
6984 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6985
6986 llvm::APInt fill;
6987
6988 // Treat empty strings as if they were zero.
6989 if (S->getString().empty())
6990 fill = llvm::APInt(32, 0);
6991 else if (S->getString().getAsInteger(0, fill))
6992 return false;
6993
6994 if (SNaN)
6995 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6996 else
6997 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6998 return true;
6999}
7000
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007001bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007002 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007003 default:
7004 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7005
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007006 case Builtin::BI__builtin_huge_val:
7007 case Builtin::BI__builtin_huge_valf:
7008 case Builtin::BI__builtin_huge_vall:
7009 case Builtin::BI__builtin_inf:
7010 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007011 case Builtin::BI__builtin_infl: {
7012 const llvm::fltSemantics &Sem =
7013 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007014 Result = llvm::APFloat::getInf(Sem);
7015 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007016 }
Mike Stump11289f42009-09-09 15:08:12 +00007017
John McCall16291492010-02-28 13:00:19 +00007018 case Builtin::BI__builtin_nans:
7019 case Builtin::BI__builtin_nansf:
7020 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007021 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7022 true, Result))
7023 return Error(E);
7024 return true;
John McCall16291492010-02-28 13:00:19 +00007025
Chris Lattner0b7282e2008-10-06 06:31:58 +00007026 case Builtin::BI__builtin_nan:
7027 case Builtin::BI__builtin_nanf:
7028 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007029 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007030 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007031 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7032 false, Result))
7033 return Error(E);
7034 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007035
7036 case Builtin::BI__builtin_fabs:
7037 case Builtin::BI__builtin_fabsf:
7038 case Builtin::BI__builtin_fabsl:
7039 if (!EvaluateFloat(E->getArg(0), Result, Info))
7040 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007041
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007042 if (Result.isNegative())
7043 Result.changeSign();
7044 return true;
7045
Richard Smith8889a3d2013-06-13 06:26:32 +00007046 // FIXME: Builtin::BI__builtin_powi
7047 // FIXME: Builtin::BI__builtin_powif
7048 // FIXME: Builtin::BI__builtin_powil
7049
Mike Stump11289f42009-09-09 15:08:12 +00007050 case Builtin::BI__builtin_copysign:
7051 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007052 case Builtin::BI__builtin_copysignl: {
7053 APFloat RHS(0.);
7054 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7055 !EvaluateFloat(E->getArg(1), RHS, Info))
7056 return false;
7057 Result.copySign(RHS);
7058 return true;
7059 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007060 }
7061}
7062
John McCallb1fb0d32010-05-07 22:08:54 +00007063bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007064 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7065 ComplexValue CV;
7066 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7067 return false;
7068 Result = CV.FloatReal;
7069 return true;
7070 }
7071
7072 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007073}
7074
7075bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007076 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7077 ComplexValue CV;
7078 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7079 return false;
7080 Result = CV.FloatImag;
7081 return true;
7082 }
7083
Richard Smith4a678122011-10-24 18:44:57 +00007084 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007085 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7086 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007087 return true;
7088}
7089
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007090bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007091 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007092 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007093 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007094 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007095 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007096 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7097 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007098 Result.changeSign();
7099 return true;
7100 }
7101}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007102
Eli Friedman24c01542008-08-22 00:06:13 +00007103bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007104 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7105 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007106
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007107 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007108 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7109 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007110 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007111 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7112 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007113}
7114
7115bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7116 Result = E->getValue();
7117 return true;
7118}
7119
Peter Collingbournee9200682011-05-13 03:29:01 +00007120bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7121 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007122
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007123 switch (E->getCastKind()) {
7124 default:
Richard Smith11562c52011-10-28 17:51:58 +00007125 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007126
7127 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007128 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007129 return EvaluateInteger(SubExpr, IntResult, Info) &&
7130 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7131 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007132 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007133
7134 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007135 if (!Visit(SubExpr))
7136 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007137 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7138 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007139 }
John McCalld7646252010-11-14 08:17:51 +00007140
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007141 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007142 ComplexValue V;
7143 if (!EvaluateComplex(SubExpr, V, Info))
7144 return false;
7145 Result = V.getComplexFloatReal();
7146 return true;
7147 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007148 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007149}
7150
Eli Friedman24c01542008-08-22 00:06:13 +00007151//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007152// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007153//===----------------------------------------------------------------------===//
7154
7155namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007156class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007157 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007158 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007159
Anders Carlsson537969c2008-11-16 20:27:53 +00007160public:
John McCall93d91dc2010-05-07 17:22:02 +00007161 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007162 : ExprEvaluatorBaseTy(info), Result(Result) {}
7163
Richard Smith2e312c82012-03-03 22:46:17 +00007164 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007165 Result.setFrom(V);
7166 return true;
7167 }
Mike Stump11289f42009-09-09 15:08:12 +00007168
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007169 bool ZeroInitialization(const Expr *E);
7170
Anders Carlsson537969c2008-11-16 20:27:53 +00007171 //===--------------------------------------------------------------------===//
7172 // Visitor Methods
7173 //===--------------------------------------------------------------------===//
7174
Peter Collingbournee9200682011-05-13 03:29:01 +00007175 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007176 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007177 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007178 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007179 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007180};
7181} // end anonymous namespace
7182
John McCall93d91dc2010-05-07 17:22:02 +00007183static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7184 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007185 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007186 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007187}
7188
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007189bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007190 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007191 if (ElemTy->isRealFloatingType()) {
7192 Result.makeComplexFloat();
7193 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7194 Result.FloatReal = Zero;
7195 Result.FloatImag = Zero;
7196 } else {
7197 Result.makeComplexInt();
7198 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7199 Result.IntReal = Zero;
7200 Result.IntImag = Zero;
7201 }
7202 return true;
7203}
7204
Peter Collingbournee9200682011-05-13 03:29:01 +00007205bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7206 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007207
7208 if (SubExpr->getType()->isRealFloatingType()) {
7209 Result.makeComplexFloat();
7210 APFloat &Imag = Result.FloatImag;
7211 if (!EvaluateFloat(SubExpr, Imag, Info))
7212 return false;
7213
7214 Result.FloatReal = APFloat(Imag.getSemantics());
7215 return true;
7216 } else {
7217 assert(SubExpr->getType()->isIntegerType() &&
7218 "Unexpected imaginary literal.");
7219
7220 Result.makeComplexInt();
7221 APSInt &Imag = Result.IntImag;
7222 if (!EvaluateInteger(SubExpr, Imag, Info))
7223 return false;
7224
7225 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7226 return true;
7227 }
7228}
7229
Peter Collingbournee9200682011-05-13 03:29:01 +00007230bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007231
John McCallfcef3cf2010-12-14 17:51:41 +00007232 switch (E->getCastKind()) {
7233 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007234 case CK_BaseToDerived:
7235 case CK_DerivedToBase:
7236 case CK_UncheckedDerivedToBase:
7237 case CK_Dynamic:
7238 case CK_ToUnion:
7239 case CK_ArrayToPointerDecay:
7240 case CK_FunctionToPointerDecay:
7241 case CK_NullToPointer:
7242 case CK_NullToMemberPointer:
7243 case CK_BaseToDerivedMemberPointer:
7244 case CK_DerivedToBaseMemberPointer:
7245 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007246 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007247 case CK_ConstructorConversion:
7248 case CK_IntegralToPointer:
7249 case CK_PointerToIntegral:
7250 case CK_PointerToBoolean:
7251 case CK_ToVoid:
7252 case CK_VectorSplat:
7253 case CK_IntegralCast:
7254 case CK_IntegralToBoolean:
7255 case CK_IntegralToFloating:
7256 case CK_FloatingToIntegral:
7257 case CK_FloatingToBoolean:
7258 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007259 case CK_CPointerToObjCPointerCast:
7260 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007261 case CK_AnyPointerToBlockPointerCast:
7262 case CK_ObjCObjectLValueCast:
7263 case CK_FloatingComplexToReal:
7264 case CK_FloatingComplexToBoolean:
7265 case CK_IntegralComplexToReal:
7266 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007267 case CK_ARCProduceObject:
7268 case CK_ARCConsumeObject:
7269 case CK_ARCReclaimReturnedObject:
7270 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007271 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007272 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007273 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007274 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007275 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007276
John McCallfcef3cf2010-12-14 17:51:41 +00007277 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007278 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007279 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007280 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007281
7282 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007283 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007284 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007285 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007286
7287 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007288 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007289 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007290 return false;
7291
John McCallfcef3cf2010-12-14 17:51:41 +00007292 Result.makeComplexFloat();
7293 Result.FloatImag = APFloat(Real.getSemantics());
7294 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007295 }
7296
John McCallfcef3cf2010-12-14 17:51:41 +00007297 case CK_FloatingComplexCast: {
7298 if (!Visit(E->getSubExpr()))
7299 return false;
7300
7301 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7302 QualType From
7303 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7304
Richard Smith357362d2011-12-13 06:39:58 +00007305 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7306 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007307 }
7308
7309 case CK_FloatingComplexToIntegralComplex: {
7310 if (!Visit(E->getSubExpr()))
7311 return false;
7312
7313 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7314 QualType From
7315 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7316 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007317 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7318 To, Result.IntReal) &&
7319 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7320 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007321 }
7322
7323 case CK_IntegralRealToComplex: {
7324 APSInt &Real = Result.IntReal;
7325 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7326 return false;
7327
7328 Result.makeComplexInt();
7329 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7330 return true;
7331 }
7332
7333 case CK_IntegralComplexCast: {
7334 if (!Visit(E->getSubExpr()))
7335 return false;
7336
7337 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7338 QualType From
7339 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7340
Richard Smith911e1422012-01-30 22:27:01 +00007341 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7342 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007343 return true;
7344 }
7345
7346 case CK_IntegralComplexToFloatingComplex: {
7347 if (!Visit(E->getSubExpr()))
7348 return false;
7349
Ted Kremenek28831752012-08-23 20:46:57 +00007350 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007351 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007352 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007353 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007354 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7355 To, Result.FloatReal) &&
7356 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7357 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007358 }
7359 }
7360
7361 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007362}
7363
John McCall93d91dc2010-05-07 17:22:02 +00007364bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007365 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007366 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7367
Richard Smith253c2a32012-01-27 01:14:48 +00007368 bool LHSOK = Visit(E->getLHS());
7369 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007370 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007371
John McCall93d91dc2010-05-07 17:22:02 +00007372 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007373 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007374 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007375
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007376 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7377 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007378 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007379 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007380 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007381 if (Result.isComplexFloat()) {
7382 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7383 APFloat::rmNearestTiesToEven);
7384 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7385 APFloat::rmNearestTiesToEven);
7386 } else {
7387 Result.getComplexIntReal() += RHS.getComplexIntReal();
7388 Result.getComplexIntImag() += RHS.getComplexIntImag();
7389 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007390 break;
John McCalle3027922010-08-25 11:45:40 +00007391 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007392 if (Result.isComplexFloat()) {
7393 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7394 APFloat::rmNearestTiesToEven);
7395 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7396 APFloat::rmNearestTiesToEven);
7397 } else {
7398 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7399 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7400 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007401 break;
John McCalle3027922010-08-25 11:45:40 +00007402 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007403 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007404 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007405 APFloat &LHS_r = LHS.getComplexFloatReal();
7406 APFloat &LHS_i = LHS.getComplexFloatImag();
7407 APFloat &RHS_r = RHS.getComplexFloatReal();
7408 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007409
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007410 APFloat Tmp = LHS_r;
7411 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7412 Result.getComplexFloatReal() = Tmp;
7413 Tmp = LHS_i;
7414 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7415 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7416
7417 Tmp = LHS_r;
7418 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7419 Result.getComplexFloatImag() = Tmp;
7420 Tmp = LHS_i;
7421 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7422 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7423 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007424 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007425 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007426 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7427 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007428 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007429 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7430 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7431 }
7432 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007433 case BO_Div:
7434 if (Result.isComplexFloat()) {
7435 ComplexValue LHS = Result;
7436 APFloat &LHS_r = LHS.getComplexFloatReal();
7437 APFloat &LHS_i = LHS.getComplexFloatImag();
7438 APFloat &RHS_r = RHS.getComplexFloatReal();
7439 APFloat &RHS_i = RHS.getComplexFloatImag();
7440 APFloat &Res_r = Result.getComplexFloatReal();
7441 APFloat &Res_i = Result.getComplexFloatImag();
7442
7443 APFloat Den = RHS_r;
7444 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7445 APFloat Tmp = RHS_i;
7446 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7447 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7448
7449 Res_r = LHS_r;
7450 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7451 Tmp = LHS_i;
7452 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7453 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7454 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7455
7456 Res_i = LHS_i;
7457 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7458 Tmp = LHS_r;
7459 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7460 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7461 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7462 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007463 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7464 return Error(E, diag::note_expr_divide_by_zero);
7465
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007466 ComplexValue LHS = Result;
7467 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7468 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7469 Result.getComplexIntReal() =
7470 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7471 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7472 Result.getComplexIntImag() =
7473 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7474 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7475 }
7476 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007477 }
7478
John McCall93d91dc2010-05-07 17:22:02 +00007479 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007480}
7481
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007482bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7483 // Get the operand value into 'Result'.
7484 if (!Visit(E->getSubExpr()))
7485 return false;
7486
7487 switch (E->getOpcode()) {
7488 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007489 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007490 case UO_Extension:
7491 return true;
7492 case UO_Plus:
7493 // The result is always just the subexpr.
7494 return true;
7495 case UO_Minus:
7496 if (Result.isComplexFloat()) {
7497 Result.getComplexFloatReal().changeSign();
7498 Result.getComplexFloatImag().changeSign();
7499 }
7500 else {
7501 Result.getComplexIntReal() = -Result.getComplexIntReal();
7502 Result.getComplexIntImag() = -Result.getComplexIntImag();
7503 }
7504 return true;
7505 case UO_Not:
7506 if (Result.isComplexFloat())
7507 Result.getComplexFloatImag().changeSign();
7508 else
7509 Result.getComplexIntImag() = -Result.getComplexIntImag();
7510 return true;
7511 }
7512}
7513
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007514bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7515 if (E->getNumInits() == 2) {
7516 if (E->getType()->isComplexType()) {
7517 Result.makeComplexFloat();
7518 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7519 return false;
7520 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7521 return false;
7522 } else {
7523 Result.makeComplexInt();
7524 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7525 return false;
7526 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7527 return false;
7528 }
7529 return true;
7530 }
7531 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7532}
7533
Anders Carlsson537969c2008-11-16 20:27:53 +00007534//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007535// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7536// implicit conversion.
7537//===----------------------------------------------------------------------===//
7538
7539namespace {
7540class AtomicExprEvaluator :
7541 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7542 APValue &Result;
7543public:
7544 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7545 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7546
7547 bool Success(const APValue &V, const Expr *E) {
7548 Result = V;
7549 return true;
7550 }
7551
7552 bool ZeroInitialization(const Expr *E) {
7553 ImplicitValueInitExpr VIE(
7554 E->getType()->castAs<AtomicType>()->getValueType());
7555 return Evaluate(Result, Info, &VIE);
7556 }
7557
7558 bool VisitCastExpr(const CastExpr *E) {
7559 switch (E->getCastKind()) {
7560 default:
7561 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7562 case CK_NonAtomicToAtomic:
7563 return Evaluate(Result, Info, E->getSubExpr());
7564 }
7565 }
7566};
7567} // end anonymous namespace
7568
7569static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7570 assert(E->isRValue() && E->getType()->isAtomicType());
7571 return AtomicExprEvaluator(Info, Result).Visit(E);
7572}
7573
7574//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007575// Void expression evaluation, primarily for a cast to void on the LHS of a
7576// comma operator
7577//===----------------------------------------------------------------------===//
7578
7579namespace {
7580class VoidExprEvaluator
7581 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7582public:
7583 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7584
Richard Smith2e312c82012-03-03 22:46:17 +00007585 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007586
7587 bool VisitCastExpr(const CastExpr *E) {
7588 switch (E->getCastKind()) {
7589 default:
7590 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7591 case CK_ToVoid:
7592 VisitIgnoredValue(E->getSubExpr());
7593 return true;
7594 }
7595 }
7596};
7597} // end anonymous namespace
7598
7599static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7600 assert(E->isRValue() && E->getType()->isVoidType());
7601 return VoidExprEvaluator(Info).Visit(E);
7602}
7603
7604//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007605// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007606//===----------------------------------------------------------------------===//
7607
Richard Smith2e312c82012-03-03 22:46:17 +00007608static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007609 // In C, function designators are not lvalues, but we evaluate them as if they
7610 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007611 QualType T = E->getType();
7612 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007613 LValue LV;
7614 if (!EvaluateLValue(E, LV, Info))
7615 return false;
7616 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007617 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007618 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007619 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007620 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007621 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007622 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007623 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007624 LValue LV;
7625 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007626 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007627 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007628 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007629 llvm::APFloat F(0.0);
7630 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007631 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007632 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007633 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007634 ComplexValue C;
7635 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007636 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007637 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007638 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007639 MemberPtr P;
7640 if (!EvaluateMemberPointer(E, P, Info))
7641 return false;
7642 P.moveInto(Result);
7643 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007644 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007645 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007646 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007647 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007648 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007649 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007650 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007651 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007652 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007653 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7654 return false;
7655 Result = Info.CurrentCall->Temporaries[E];
Richard Smitha23ab512013-05-23 00:30:41 +00007656 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007657 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007658 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007659 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007660 if (!EvaluateVoid(E, Info))
7661 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007662 } else if (T->isAtomicType()) {
7663 if (!EvaluateAtomic(E, Result, Info))
7664 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007665 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007666 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007667 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007668 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007669 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007670 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007671 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007672
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007673 return true;
7674}
7675
Richard Smithb228a862012-02-15 02:18:13 +00007676/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7677/// cases, the in-place evaluation is essential, since later initializers for
7678/// an object can indirectly refer to subobjects which were initialized earlier.
7679static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007680 const Expr *E, bool AllowNonLiteralTypes) {
7681 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007682 return false;
7683
7684 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007685 // Evaluate arrays and record types in-place, so that later initializers can
7686 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007687 if (E->getType()->isArrayType())
7688 return EvaluateArray(E, This, Result, Info);
7689 else if (E->getType()->isRecordType())
7690 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007691 }
7692
7693 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007694 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007695}
7696
Richard Smithf57d8cb2011-12-09 22:58:01 +00007697/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7698/// lvalue-to-rvalue cast if it is an lvalue.
7699static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007700 if (!CheckLiteralType(Info, E))
7701 return false;
7702
Richard Smith2e312c82012-03-03 22:46:17 +00007703 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007704 return false;
7705
7706 if (E->isGLValue()) {
7707 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007708 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007709 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007710 return false;
7711 }
7712
Richard Smith2e312c82012-03-03 22:46:17 +00007713 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007714 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007715}
Richard Smith11562c52011-10-28 17:51:58 +00007716
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007717static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7718 const ASTContext &Ctx, bool &IsConst) {
7719 // Fast-path evaluations of integer literals, since we sometimes see files
7720 // containing vast quantities of these.
7721 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7722 Result.Val = APValue(APSInt(L->getValue(),
7723 L->getType()->isUnsignedIntegerType()));
7724 IsConst = true;
7725 return true;
7726 }
7727
7728 // FIXME: Evaluating values of large array and record types can cause
7729 // performance problems. Only do so in C++11 for now.
7730 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7731 Exp->getType()->isRecordType()) &&
7732 !Ctx.getLangOpts().CPlusPlus11) {
7733 IsConst = false;
7734 return true;
7735 }
7736 return false;
7737}
7738
7739
Richard Smith7b553f12011-10-29 00:50:52 +00007740/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007741/// any crazy technique (that has nothing to do with language standards) that
7742/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007743/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7744/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007745bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007746 bool IsConst;
7747 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7748 return IsConst;
7749
Richard Smithf57d8cb2011-12-09 22:58:01 +00007750 EvalInfo Info(Ctx, Result);
7751 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007752}
7753
Jay Foad39c79802011-01-12 09:06:06 +00007754bool Expr::EvaluateAsBooleanCondition(bool &Result,
7755 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007756 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007757 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007758 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007759}
7760
Richard Smith5fab0c92011-12-28 19:48:30 +00007761bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7762 SideEffectsKind AllowSideEffects) const {
7763 if (!getType()->isIntegralOrEnumerationType())
7764 return false;
7765
Richard Smith11562c52011-10-28 17:51:58 +00007766 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007767 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7768 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007769 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007770
Richard Smith11562c52011-10-28 17:51:58 +00007771 Result = ExprResult.Val.getInt();
7772 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007773}
7774
Jay Foad39c79802011-01-12 09:06:06 +00007775bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007776 EvalInfo Info(Ctx, Result);
7777
John McCall45d55e42010-05-07 21:00:08 +00007778 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007779 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7780 !CheckLValueConstantExpression(Info, getExprLoc(),
7781 Ctx.getLValueReferenceType(getType()), LV))
7782 return false;
7783
Richard Smith2e312c82012-03-03 22:46:17 +00007784 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007785 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007786}
7787
Richard Smithd0b4dd62011-12-19 06:19:21 +00007788bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7789 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007790 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007791 // FIXME: Evaluating initializers for large array and record types can cause
7792 // performance problems. Only do so in C++11 for now.
7793 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007794 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007795 return false;
7796
Richard Smithd0b4dd62011-12-19 06:19:21 +00007797 Expr::EvalStatus EStatus;
7798 EStatus.Diag = &Notes;
7799
7800 EvalInfo InitInfo(Ctx, EStatus);
7801 InitInfo.setEvaluatingDecl(VD, Value);
7802
7803 LValue LVal;
7804 LVal.set(VD);
7805
Richard Smithfddd3842011-12-30 21:15:51 +00007806 // C++11 [basic.start.init]p2:
7807 // Variables with static storage duration or thread storage duration shall be
7808 // zero-initialized before any other initialization takes place.
7809 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007810 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007811 !VD->getType()->isReferenceType()) {
7812 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007813 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007814 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007815 return false;
7816 }
7817
Richard Smith7525ff62013-05-09 07:14:00 +00007818 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7819 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007820 EStatus.HasSideEffects)
7821 return false;
7822
7823 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7824 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007825}
7826
Richard Smith7b553f12011-10-29 00:50:52 +00007827/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7828/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007829bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007830 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007831 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007832}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007833
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007834APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007835 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007836 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007837 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007838 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007839 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007840 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007841 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007842
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007843 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007844}
John McCall864e3962010-05-07 05:32:02 +00007845
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007846void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7847 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7848 bool IsConst;
7849 EvalResult EvalResult;
7850 EvalResult.Diag = Diags;
7851 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7852 EvalInfo Info(Ctx, EvalResult, true);
7853 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7854 }
7855}
7856
Richard Smithe6c01442013-06-05 00:46:14 +00007857bool Expr::EvalResult::isGlobalLValue() const {
7858 assert(Val.isLValue());
7859 return IsGlobalLValue(Val.getLValueBase());
7860}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007861
7862
John McCall864e3962010-05-07 05:32:02 +00007863/// isIntegerConstantExpr - this recursive routine will test if an expression is
7864/// an integer constant expression.
7865
7866/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7867/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007868
7869// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007870// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7871// and a (possibly null) SourceLocation indicating the location of the problem.
7872//
John McCall864e3962010-05-07 05:32:02 +00007873// Note that to reduce code duplication, this helper does no evaluation
7874// itself; the caller checks whether the expression is evaluatable, and
7875// in the rare cases where CheckICE actually cares about the evaluated
7876// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007877
Dan Gohman28ade552010-07-26 21:25:24 +00007878namespace {
7879
Richard Smith9e575da2012-12-28 13:25:52 +00007880enum ICEKind {
7881 /// This expression is an ICE.
7882 IK_ICE,
7883 /// This expression is not an ICE, but if it isn't evaluated, it's
7884 /// a legal subexpression for an ICE. This return value is used to handle
7885 /// the comma operator in C99 mode, and non-constant subexpressions.
7886 IK_ICEIfUnevaluated,
7887 /// This expression is not an ICE, and is not a legal subexpression for one.
7888 IK_NotICE
7889};
7890
John McCall864e3962010-05-07 05:32:02 +00007891struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007892 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007893 SourceLocation Loc;
7894
Richard Smith9e575da2012-12-28 13:25:52 +00007895 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007896};
7897
Dan Gohman28ade552010-07-26 21:25:24 +00007898}
7899
Richard Smith9e575da2012-12-28 13:25:52 +00007900static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7901
7902static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007903
7904static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7905 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007906 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007907 !EVResult.Val.isInt())
7908 return ICEDiag(IK_NotICE, E->getLocStart());
7909
John McCall864e3962010-05-07 05:32:02 +00007910 return NoDiag();
7911}
7912
7913static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7914 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007915 if (!E->getType()->isIntegralOrEnumerationType())
7916 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007917
7918 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007919#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007920#define STMT(Node, Base) case Expr::Node##Class:
7921#define EXPR(Node, Base)
7922#include "clang/AST/StmtNodes.inc"
7923 case Expr::PredefinedExprClass:
7924 case Expr::FloatingLiteralClass:
7925 case Expr::ImaginaryLiteralClass:
7926 case Expr::StringLiteralClass:
7927 case Expr::ArraySubscriptExprClass:
7928 case Expr::MemberExprClass:
7929 case Expr::CompoundAssignOperatorClass:
7930 case Expr::CompoundLiteralExprClass:
7931 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007932 case Expr::DesignatedInitExprClass:
7933 case Expr::ImplicitValueInitExprClass:
7934 case Expr::ParenListExprClass:
7935 case Expr::VAArgExprClass:
7936 case Expr::AddrLabelExprClass:
7937 case Expr::StmtExprClass:
7938 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007939 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007940 case Expr::CXXDynamicCastExprClass:
7941 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007942 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007943 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007944 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007945 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007946 case Expr::CXXThisExprClass:
7947 case Expr::CXXThrowExprClass:
7948 case Expr::CXXNewExprClass:
7949 case Expr::CXXDeleteExprClass:
7950 case Expr::CXXPseudoDestructorExprClass:
7951 case Expr::UnresolvedLookupExprClass:
7952 case Expr::DependentScopeDeclRefExprClass:
7953 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00007954 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00007955 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007956 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007957 case Expr::CXXTemporaryObjectExprClass:
7958 case Expr::CXXUnresolvedConstructExprClass:
7959 case Expr::CXXDependentScopeMemberExprClass:
7960 case Expr::UnresolvedMemberExprClass:
7961 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007962 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007963 case Expr::ObjCArrayLiteralClass:
7964 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007965 case Expr::ObjCEncodeExprClass:
7966 case Expr::ObjCMessageExprClass:
7967 case Expr::ObjCSelectorExprClass:
7968 case Expr::ObjCProtocolExprClass:
7969 case Expr::ObjCIvarRefExprClass:
7970 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007971 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007972 case Expr::ObjCIsaExprClass:
7973 case Expr::ShuffleVectorExprClass:
7974 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007975 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007976 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007977 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007978 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007979 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007980 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007981 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007982 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007983 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007984 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007985 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007986 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007987 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007988
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007989 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007990 case Expr::GNUNullExprClass:
7991 // GCC considers the GNU __null value to be an integral constant expression.
7992 return NoDiag();
7993
John McCall7c454bb2011-07-15 05:09:51 +00007994 case Expr::SubstNonTypeTemplateParmExprClass:
7995 return
7996 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7997
John McCall864e3962010-05-07 05:32:02 +00007998 case Expr::ParenExprClass:
7999 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008000 case Expr::GenericSelectionExprClass:
8001 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008002 case Expr::IntegerLiteralClass:
8003 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008004 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008005 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008006 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008007 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008008 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008009 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008010 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008011 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008012 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008013 return NoDiag();
8014 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008015 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008016 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8017 // constant expressions, but they can never be ICEs because an ICE cannot
8018 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008019 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008020 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008021 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008022 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008023 }
Richard Smith6365c912012-02-24 22:12:32 +00008024 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008025 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8026 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008027 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008028 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008029 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008030 // Parameter variables are never constants. Without this check,
8031 // getAnyInitializer() can find a default argument, which leads
8032 // to chaos.
8033 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008034 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008035
8036 // C++ 7.1.5.1p2
8037 // A variable of non-volatile const-qualified integral or enumeration
8038 // type initialized by an ICE can be used in ICEs.
8039 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008040 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008041 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008042
Richard Smithd0b4dd62011-12-19 06:19:21 +00008043 const VarDecl *VD;
8044 // Look for a declaration of this variable that has an initializer, and
8045 // check whether it is an ICE.
8046 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8047 return NoDiag();
8048 else
Richard Smith9e575da2012-12-28 13:25:52 +00008049 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008050 }
8051 }
Richard Smith9e575da2012-12-28 13:25:52 +00008052 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008053 }
John McCall864e3962010-05-07 05:32:02 +00008054 case Expr::UnaryOperatorClass: {
8055 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8056 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008057 case UO_PostInc:
8058 case UO_PostDec:
8059 case UO_PreInc:
8060 case UO_PreDec:
8061 case UO_AddrOf:
8062 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008063 // C99 6.6/3 allows increment and decrement within unevaluated
8064 // subexpressions of constant expressions, but they can never be ICEs
8065 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008066 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008067 case UO_Extension:
8068 case UO_LNot:
8069 case UO_Plus:
8070 case UO_Minus:
8071 case UO_Not:
8072 case UO_Real:
8073 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008074 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008075 }
Richard Smith9e575da2012-12-28 13:25:52 +00008076
John McCall864e3962010-05-07 05:32:02 +00008077 // OffsetOf falls through here.
8078 }
8079 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008080 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8081 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8082 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8083 // compliance: we should warn earlier for offsetof expressions with
8084 // array subscripts that aren't ICEs, and if the array subscripts
8085 // are ICEs, the value of the offsetof must be an integer constant.
8086 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008087 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008088 case Expr::UnaryExprOrTypeTraitExprClass: {
8089 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8090 if ((Exp->getKind() == UETT_SizeOf) &&
8091 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008092 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008093 return NoDiag();
8094 }
8095 case Expr::BinaryOperatorClass: {
8096 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8097 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008098 case BO_PtrMemD:
8099 case BO_PtrMemI:
8100 case BO_Assign:
8101 case BO_MulAssign:
8102 case BO_DivAssign:
8103 case BO_RemAssign:
8104 case BO_AddAssign:
8105 case BO_SubAssign:
8106 case BO_ShlAssign:
8107 case BO_ShrAssign:
8108 case BO_AndAssign:
8109 case BO_XorAssign:
8110 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008111 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8112 // constant expressions, but they can never be ICEs because an ICE cannot
8113 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008114 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008115
John McCalle3027922010-08-25 11:45:40 +00008116 case BO_Mul:
8117 case BO_Div:
8118 case BO_Rem:
8119 case BO_Add:
8120 case BO_Sub:
8121 case BO_Shl:
8122 case BO_Shr:
8123 case BO_LT:
8124 case BO_GT:
8125 case BO_LE:
8126 case BO_GE:
8127 case BO_EQ:
8128 case BO_NE:
8129 case BO_And:
8130 case BO_Xor:
8131 case BO_Or:
8132 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008133 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8134 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008135 if (Exp->getOpcode() == BO_Div ||
8136 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008137 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008138 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008139 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008140 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008141 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008142 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008143 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008144 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008145 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008146 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008147 }
8148 }
8149 }
John McCalle3027922010-08-25 11:45:40 +00008150 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008151 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008152 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8153 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008154 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8155 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008156 } else {
8157 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008158 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008159 }
8160 }
Richard Smith9e575da2012-12-28 13:25:52 +00008161 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008162 }
John McCalle3027922010-08-25 11:45:40 +00008163 case BO_LAnd:
8164 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008165 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8166 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008167 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008168 // Rare case where the RHS has a comma "side-effect"; we need
8169 // to actually check the condition to see whether the side
8170 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008171 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008172 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008173 return RHSResult;
8174 return NoDiag();
8175 }
8176
Richard Smith9e575da2012-12-28 13:25:52 +00008177 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008178 }
8179 }
8180 }
8181 case Expr::ImplicitCastExprClass:
8182 case Expr::CStyleCastExprClass:
8183 case Expr::CXXFunctionalCastExprClass:
8184 case Expr::CXXStaticCastExprClass:
8185 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008186 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008187 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008188 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008189 if (isa<ExplicitCastExpr>(E)) {
8190 if (const FloatingLiteral *FL
8191 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8192 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8193 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8194 APSInt IgnoredVal(DestWidth, !DestSigned);
8195 bool Ignored;
8196 // If the value does not fit in the destination type, the behavior is
8197 // undefined, so we are not required to treat it as a constant
8198 // expression.
8199 if (FL->getValue().convertToInteger(IgnoredVal,
8200 llvm::APFloat::rmTowardZero,
8201 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008202 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008203 return NoDiag();
8204 }
8205 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008206 switch (cast<CastExpr>(E)->getCastKind()) {
8207 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008208 case CK_AtomicToNonAtomic:
8209 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008210 case CK_NoOp:
8211 case CK_IntegralToBoolean:
8212 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008213 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008214 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008215 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008216 }
John McCall864e3962010-05-07 05:32:02 +00008217 }
John McCallc07a0c72011-02-17 10:25:35 +00008218 case Expr::BinaryConditionalOperatorClass: {
8219 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8220 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008221 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008222 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008223 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8224 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8225 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008226 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008227 return FalseResult;
8228 }
John McCall864e3962010-05-07 05:32:02 +00008229 case Expr::ConditionalOperatorClass: {
8230 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8231 // If the condition (ignoring parens) is a __builtin_constant_p call,
8232 // then only the true side is actually considered in an integer constant
8233 // expression, and it is fully evaluated. This is an important GNU
8234 // extension. See GCC PR38377 for discussion.
8235 if (const CallExpr *CallCE
8236 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008237 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8238 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008239 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008240 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008241 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008242
Richard Smithf57d8cb2011-12-09 22:58:01 +00008243 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8244 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008245
Richard Smith9e575da2012-12-28 13:25:52 +00008246 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008247 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008248 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008249 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008250 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008251 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008252 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008253 return NoDiag();
8254 // Rare case where the diagnostics depend on which side is evaluated
8255 // Note that if we get here, CondResult is 0, and at least one of
8256 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008257 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008258 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008259 return TrueResult;
8260 }
8261 case Expr::CXXDefaultArgExprClass:
8262 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008263 case Expr::CXXDefaultInitExprClass:
8264 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008265 case Expr::ChooseExprClass: {
8266 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
8267 }
8268 }
8269
David Blaikiee4d798f2012-01-20 21:50:17 +00008270 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008271}
8272
Richard Smithf57d8cb2011-12-09 22:58:01 +00008273/// Evaluate an expression as a C++11 integral constant expression.
8274static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
8275 const Expr *E,
8276 llvm::APSInt *Value,
8277 SourceLocation *Loc) {
8278 if (!E->getType()->isIntegralOrEnumerationType()) {
8279 if (Loc) *Loc = E->getExprLoc();
8280 return false;
8281 }
8282
Richard Smith66e05fe2012-01-18 05:21:49 +00008283 APValue Result;
8284 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008285 return false;
8286
Richard Smith66e05fe2012-01-18 05:21:49 +00008287 assert(Result.isInt() && "pointer cast to int is not an ICE");
8288 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008289 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008290}
8291
Richard Smith92b1ce02011-12-12 09:28:41 +00008292bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008293 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008294 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8295
Richard Smith9e575da2012-12-28 13:25:52 +00008296 ICEDiag D = CheckICE(this, Ctx);
8297 if (D.Kind != IK_ICE) {
8298 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008299 return false;
8300 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008301 return true;
8302}
8303
8304bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
8305 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008306 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008307 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8308
8309 if (!isIntegerConstantExpr(Ctx, Loc))
8310 return false;
8311 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008312 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008313 return true;
8314}
Richard Smith66e05fe2012-01-18 05:21:49 +00008315
Richard Smith98a0a492012-02-14 21:38:30 +00008316bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008317 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008318}
8319
Richard Smith66e05fe2012-01-18 05:21:49 +00008320bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
8321 SourceLocation *Loc) const {
8322 // We support this checking in C++98 mode in order to diagnose compatibility
8323 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008324 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008325
Richard Smith98a0a492012-02-14 21:38:30 +00008326 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008327 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008328 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008329 Status.Diag = &Diags;
8330 EvalInfo Info(Ctx, Status);
8331
8332 APValue Scratch;
8333 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8334
8335 if (!Diags.empty()) {
8336 IsConstExpr = false;
8337 if (Loc) *Loc = Diags[0].first;
8338 } else if (!IsConstExpr) {
8339 // FIXME: This shouldn't happen.
8340 if (Loc) *Loc = getExprLoc();
8341 }
8342
8343 return IsConstExpr;
8344}
Richard Smith253c2a32012-01-27 01:14:48 +00008345
8346bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008347 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008348 PartialDiagnosticAt> &Diags) {
8349 // FIXME: It would be useful to check constexpr function templates, but at the
8350 // moment the constant expression evaluator cannot cope with the non-rigorous
8351 // ASTs which we build for dependent expressions.
8352 if (FD->isDependentContext())
8353 return true;
8354
8355 Expr::EvalStatus Status;
8356 Status.Diag = &Diags;
8357
8358 EvalInfo Info(FD->getASTContext(), Status);
8359 Info.CheckingPotentialConstantExpression = true;
8360
8361 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8362 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8363
Richard Smith7525ff62013-05-09 07:14:00 +00008364 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008365 // is a temporary being used as the 'this' pointer.
8366 LValue This;
8367 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008368 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008369
Richard Smith253c2a32012-01-27 01:14:48 +00008370 ArrayRef<const Expr*> Args;
8371
8372 SourceLocation Loc = FD->getLocation();
8373
Richard Smith2e312c82012-03-03 22:46:17 +00008374 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008375 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8376 // Evaluate the call as a constant initializer, to allow the construction
8377 // of objects of non-literal types.
8378 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008379 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008380 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008381 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8382 Args, FD->getBody(), Info, Scratch);
8383
8384 return Diags.empty();
8385}