blob: b6602145e28c681c87184f0b52df5bb23c2d35fa [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 Smith08d6a2c2013-07-24 07:11:57 +0000320
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
323 return I == Temporaries.end() ? 0 : &I->second;
324 }
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000326 };
327
Richard Smith852c9db2013-04-20 22:23:05 +0000328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
330 public:
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
333 if (Enable)
334 Frame.This = NewThis;
335 }
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
338 }
339 private:
340 CallStackFrame &Frame;
341 const LValue *OldThis;
342 };
343
Richard Smith92b1ce02011-12-12 09:28:41 +0000344 /// A partial diagnostic which we might know in advance that we are not going
345 /// to emit.
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
348
349 public:
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
351
352 template<typename T>
353 OptionalDiagnostic &operator<<(const T &v) {
354 if (Diag)
355 *Diag << v;
356 return *this;
357 }
Richard Smithfe800032012-01-31 04:08:20 +0000358
359 OptionalDiagnostic &operator<<(const APSInt &I) {
360 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000361 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000362 I.toString(Buffer);
363 *Diag << StringRef(Buffer.data(), Buffer.size());
364 }
365 return *this;
366 }
367
368 OptionalDiagnostic &operator<<(const APFloat &F) {
369 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
376 unsigned precision =
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000379 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000380 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000381 *Diag << StringRef(Buffer.data(), Buffer.size());
382 }
383 return *this;
384 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000385 };
386
Richard Smith08d6a2c2013-07-24 07:11:57 +0000387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
388 class Cleanup {
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
390
391 public:
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
394
395 bool isLifetimeExtended() const { return Value.getInt(); }
396 void endLifetime() {
397 *Value.getPointer() = APValue();
398 }
399 };
400
Richard Smithb228a862012-02-15 02:18:13 +0000401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
404 /// expression.
405 ///
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
409 ///
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000415 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000416 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000417
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
420
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
423
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
426
Richard Smithb228a862012-02-15 02:18:13 +0000427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
429
Richard Smitha3d3bd22013-05-08 02:12:03 +0000430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
433 unsigned StepsLeft;
434
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000435 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000436 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 CallStackFrame BottomFrame;
438
Richard Smith08d6a2c2013-07-24 07:11:57 +0000439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
442
Richard Smithd62306a2011-11-10 06:34:14 +0000443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000445 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000446
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
450
Richard Smith357362d2011-12-13 06:39:58 +0000451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
454
Richard Smith253c2a32012-01-27 01:14:48 +0000455 /// CheckingPotentialConstantExpression - Are we checking whether the
456 /// expression is a potential constant expression? If so, some diagnostics
457 /// are suppressed.
458 bool CheckingPotentialConstantExpression;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000459
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000460 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000461
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000462 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000463 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000464 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000465 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000466 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000467 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000468 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
469 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000470 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000471
Richard Smith7525ff62013-05-09 07:14:00 +0000472 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
473 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000474 EvaluatingDeclValue = &Value;
475 }
476
David Blaikiebbafb8a2012-03-11 07:00:24 +0000477 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000478
Richard Smith357362d2011-12-13 06:39:58 +0000479 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000480 // Don't perform any constexpr calls (other than the call we're checking)
481 // when checking a potential constant expression.
482 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
483 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000484 if (NextCallIndex == 0) {
485 // NextCallIndex has wrapped around.
486 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
487 return false;
488 }
Richard Smith357362d2011-12-13 06:39:58 +0000489 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
490 return true;
491 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
492 << getLangOpts().ConstexprCallDepth;
493 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000494 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000495
Richard Smithb228a862012-02-15 02:18:13 +0000496 CallStackFrame *getCallFrame(unsigned CallIndex) {
497 assert(CallIndex && "no call index in getCallFrame");
498 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
499 // be null in this loop.
500 CallStackFrame *Frame = CurrentCall;
501 while (Frame->Index > CallIndex)
502 Frame = Frame->Caller;
503 return (Frame->Index == CallIndex) ? Frame : 0;
504 }
505
Richard Smitha3d3bd22013-05-08 02:12:03 +0000506 bool nextStep(const Stmt *S) {
507 if (!StepsLeft) {
508 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
509 return false;
510 }
511 --StepsLeft;
512 return true;
513 }
514
Richard Smith357362d2011-12-13 06:39:58 +0000515 private:
516 /// Add a diagnostic to the diagnostics list.
517 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
518 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
519 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
520 return EvalStatus.Diag->back().second;
521 }
522
Richard Smithf6f003a2011-12-16 19:06:07 +0000523 /// Add notes containing a call stack to the current point of evaluation.
524 void addCallStack(unsigned Limit);
525
Richard Smith357362d2011-12-13 06:39:58 +0000526 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000527 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000528 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
529 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000530 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000531 // If we have a prior diagnostic, it will be noting that the expression
532 // isn't a constant expression. This diagnostic is more important.
533 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000534 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000535 unsigned CallStackNotes = CallStackDepth - 1;
536 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
537 if (Limit)
538 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000539 if (CheckingPotentialConstantExpression)
540 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000541
Richard Smith357362d2011-12-13 06:39:58 +0000542 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000543 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000544 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
545 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000546 if (!CheckingPotentialConstantExpression)
547 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000548 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000549 }
Richard Smith357362d2011-12-13 06:39:58 +0000550 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000551 return OptionalDiagnostic();
552 }
553
Richard Smithce1ec5e2012-03-15 04:53:45 +0000554 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
555 = diag::note_invalid_subexpr_in_const_expr,
556 unsigned ExtraNotes = 0) {
557 if (EvalStatus.Diag)
558 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
559 HasActiveDiagnostic = false;
560 return OptionalDiagnostic();
561 }
562
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000563 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
564
Richard Smith92b1ce02011-12-12 09:28:41 +0000565 /// Diagnose that the evaluation does not produce a C++11 core constant
566 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000567 template<typename LocArg>
568 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000569 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000570 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000571 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000572 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
573 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000574 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000575 }
Richard Smith357362d2011-12-13 06:39:58 +0000576 return Diag(Loc, DiagId, ExtraNotes);
577 }
578
579 /// Add a note to a prior diagnostic.
580 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
581 if (!HasActiveDiagnostic)
582 return OptionalDiagnostic();
583 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000584 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000585
586 /// Add a stack of notes to a prior diagnostic.
587 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
588 if (HasActiveDiagnostic) {
589 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
590 Diags.begin(), Diags.end());
591 }
592 }
Richard Smith253c2a32012-01-27 01:14:48 +0000593
594 /// Should we continue evaluation as much as possible after encountering a
595 /// construct which can't be folded?
596 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000597 // Should return true in IntOverflowCheckMode, so that we check for
598 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000599 return StepsLeft && (IntOverflowCheckMode ||
600 (CheckingPotentialConstantExpression &&
601 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000602 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000603 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000604
605 /// Object used to treat all foldable expressions as constant expressions.
606 struct FoldConstant {
607 bool Enabled;
608
609 explicit FoldConstant(EvalInfo &Info)
610 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
611 !Info.EvalStatus.HasSideEffects) {
612 }
613 // Treat the value we've computed since this object was created as constant.
614 void Fold(EvalInfo &Info) {
615 if (Enabled && !Info.EvalStatus.Diag->empty() &&
616 !Info.EvalStatus.HasSideEffects)
617 Info.EvalStatus.Diag->clear();
618 }
619 };
Richard Smith17100ba2012-02-16 02:46:34 +0000620
621 /// RAII object used to suppress diagnostics and side-effects from a
622 /// speculative evaluation.
623 class SpeculativeEvaluationRAII {
624 EvalInfo &Info;
625 Expr::EvalStatus Old;
626
627 public:
628 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000629 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000630 : Info(Info), Old(Info.EvalStatus) {
631 Info.EvalStatus.Diag = NewDiag;
632 }
633 ~SpeculativeEvaluationRAII() {
634 Info.EvalStatus = Old;
635 }
636 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000637
638 /// RAII object wrapping a full-expression or block scope, and handling
639 /// the ending of the lifetime of temporaries created within it.
640 template<bool IsFullExpression>
641 class ScopeRAII {
642 EvalInfo &Info;
643 unsigned OldStackSize;
644 public:
645 ScopeRAII(EvalInfo &Info)
646 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
647 ~ScopeRAII() {
648 // Body moved to a static method to encourage the compiler to inline away
649 // instances of this class.
650 cleanup(Info, OldStackSize);
651 }
652 private:
653 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
654 unsigned NewEnd = OldStackSize;
655 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
656 I != N; ++I) {
657 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
658 // Full-expression cleanup of a lifetime-extended temporary: nothing
659 // to do, just move this cleanup to the right place in the stack.
660 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
661 ++NewEnd;
662 } else {
663 // End the lifetime of the object.
664 Info.CleanupStack[I].endLifetime();
665 }
666 }
667 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
668 Info.CleanupStack.end());
669 }
670 };
671 typedef ScopeRAII<false> BlockScopeRAII;
672 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000673}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000674
Richard Smitha8105bc2012-01-06 16:39:00 +0000675bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
676 CheckSubobjectKind CSK) {
677 if (Invalid)
678 return false;
679 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000680 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000681 << CSK;
682 setInvalid();
683 return false;
684 }
685 return true;
686}
687
688void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
689 const Expr *E, uint64_t N) {
690 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000691 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000692 << static_cast<int>(N) << /*array*/ 0
693 << static_cast<unsigned>(MostDerivedArraySize);
694 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000695 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000696 << static_cast<int>(N) << /*non-array*/ 1;
697 setInvalid();
698}
699
Richard Smithf6f003a2011-12-16 19:06:07 +0000700CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
701 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000702 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000703 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000704 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000705 Info.CurrentCall = this;
706 ++Info.CallStackDepth;
707}
708
709CallStackFrame::~CallStackFrame() {
710 assert(Info.CurrentCall == this && "calls retired out of order");
711 --Info.CallStackDepth;
712 Info.CurrentCall = Caller;
713}
714
Richard Smith08d6a2c2013-07-24 07:11:57 +0000715APValue &CallStackFrame::createTemporary(const void *Key,
716 bool IsLifetimeExtended) {
717 APValue &Result = Temporaries[Key];
718 assert(Result.isUninit() && "temporary created multiple times");
719 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
720 return Result;
721}
722
Richard Smith84401042013-06-03 05:03:02 +0000723static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000724
725void EvalInfo::addCallStack(unsigned Limit) {
726 // Determine which calls to skip, if any.
727 unsigned ActiveCalls = CallStackDepth - 1;
728 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
729 if (Limit && Limit < ActiveCalls) {
730 SkipStart = Limit / 2 + Limit % 2;
731 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000732 }
733
Richard Smithf6f003a2011-12-16 19:06:07 +0000734 // Walk the call stack and add the diagnostics.
735 unsigned CallIdx = 0;
736 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
737 Frame = Frame->Caller, ++CallIdx) {
738 // Skip this call?
739 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
740 if (CallIdx == SkipStart) {
741 // Note that we're skipping calls.
742 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
743 << unsigned(ActiveCalls - Limit);
744 }
745 continue;
746 }
747
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000748 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000749 llvm::raw_svector_ostream Out(Buffer);
750 describeCall(Frame, Out);
751 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
752 }
753}
754
755namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000756 struct ComplexValue {
757 private:
758 bool IsInt;
759
760 public:
761 APSInt IntReal, IntImag;
762 APFloat FloatReal, FloatImag;
763
764 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
765
766 void makeComplexFloat() { IsInt = false; }
767 bool isComplexFloat() const { return !IsInt; }
768 APFloat &getComplexFloatReal() { return FloatReal; }
769 APFloat &getComplexFloatImag() { return FloatImag; }
770
771 void makeComplexInt() { IsInt = true; }
772 bool isComplexInt() const { return IsInt; }
773 APSInt &getComplexIntReal() { return IntReal; }
774 APSInt &getComplexIntImag() { return IntImag; }
775
Richard Smith2e312c82012-03-03 22:46:17 +0000776 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000777 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000778 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000779 else
Richard Smith2e312c82012-03-03 22:46:17 +0000780 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000781 }
Richard Smith2e312c82012-03-03 22:46:17 +0000782 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000783 assert(v.isComplexFloat() || v.isComplexInt());
784 if (v.isComplexFloat()) {
785 makeComplexFloat();
786 FloatReal = v.getComplexFloatReal();
787 FloatImag = v.getComplexFloatImag();
788 } else {
789 makeComplexInt();
790 IntReal = v.getComplexIntReal();
791 IntImag = v.getComplexIntImag();
792 }
793 }
John McCall93d91dc2010-05-07 17:22:02 +0000794 };
John McCall45d55e42010-05-07 21:00:08 +0000795
796 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000797 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000798 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000799 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000800 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000801
Richard Smithce40ad62011-11-12 22:28:03 +0000802 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000803 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000804 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000805 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000806 SubobjectDesignator &getLValueDesignator() { return Designator; }
807 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000808
Richard Smith2e312c82012-03-03 22:46:17 +0000809 void moveInto(APValue &V) const {
810 if (Designator.Invalid)
811 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
812 else
813 V = APValue(Base, Offset, Designator.Entries,
814 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000815 }
Richard Smith2e312c82012-03-03 22:46:17 +0000816 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000817 assert(V.isLValue());
818 Base = V.getLValueBase();
819 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000820 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000821 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000822 }
823
Richard Smithb228a862012-02-15 02:18:13 +0000824 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000825 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000826 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000827 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000828 Designator = SubobjectDesignator(getType(B));
829 }
830
831 // Check that this LValue is not based on a null pointer. If it is, produce
832 // a diagnostic and mark the designator as invalid.
833 bool checkNullPointer(EvalInfo &Info, const Expr *E,
834 CheckSubobjectKind CSK) {
835 if (Designator.Invalid)
836 return false;
837 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000838 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000839 << CSK;
840 Designator.setInvalid();
841 return false;
842 }
843 return true;
844 }
845
846 // Check this LValue refers to an object. If not, set the designator to be
847 // invalid and emit a diagnostic.
848 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000849 // Outside C++11, do not build a designator referring to a subobject of
850 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000851 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000852 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000853 return checkNullPointer(Info, E, CSK) &&
854 Designator.checkSubobject(Info, E, CSK);
855 }
856
857 void addDecl(EvalInfo &Info, const Expr *E,
858 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000859 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
860 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000861 }
862 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000863 if (checkSubobject(Info, E, CSK_ArrayToPointer))
864 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000865 }
Richard Smith66c96992012-02-18 22:04:06 +0000866 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000867 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
868 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000869 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000870 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000871 if (checkNullPointer(Info, E, CSK_ArrayIndex))
872 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000873 }
John McCall45d55e42010-05-07 21:00:08 +0000874 };
Richard Smith027bf112011-11-17 22:56:20 +0000875
876 struct MemberPtr {
877 MemberPtr() {}
878 explicit MemberPtr(const ValueDecl *Decl) :
879 DeclAndIsDerivedMember(Decl, false), Path() {}
880
881 /// The member or (direct or indirect) field referred to by this member
882 /// pointer, or 0 if this is a null member pointer.
883 const ValueDecl *getDecl() const {
884 return DeclAndIsDerivedMember.getPointer();
885 }
886 /// Is this actually a member of some type derived from the relevant class?
887 bool isDerivedMember() const {
888 return DeclAndIsDerivedMember.getInt();
889 }
890 /// Get the class which the declaration actually lives in.
891 const CXXRecordDecl *getContainingRecord() const {
892 return cast<CXXRecordDecl>(
893 DeclAndIsDerivedMember.getPointer()->getDeclContext());
894 }
895
Richard Smith2e312c82012-03-03 22:46:17 +0000896 void moveInto(APValue &V) const {
897 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000898 }
Richard Smith2e312c82012-03-03 22:46:17 +0000899 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000900 assert(V.isMemberPointer());
901 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
902 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
903 Path.clear();
904 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
905 Path.insert(Path.end(), P.begin(), P.end());
906 }
907
908 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
909 /// whether the member is a member of some class derived from the class type
910 /// of the member pointer.
911 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
912 /// Path - The path of base/derived classes from the member declaration's
913 /// class (exclusive) to the class type of the member pointer (inclusive).
914 SmallVector<const CXXRecordDecl*, 4> Path;
915
916 /// Perform a cast towards the class of the Decl (either up or down the
917 /// hierarchy).
918 bool castBack(const CXXRecordDecl *Class) {
919 assert(!Path.empty());
920 const CXXRecordDecl *Expected;
921 if (Path.size() >= 2)
922 Expected = Path[Path.size() - 2];
923 else
924 Expected = getContainingRecord();
925 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
926 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
927 // if B does not contain the original member and is not a base or
928 // derived class of the class containing the original member, the result
929 // of the cast is undefined.
930 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
931 // (D::*). We consider that to be a language defect.
932 return false;
933 }
934 Path.pop_back();
935 return true;
936 }
937 /// Perform a base-to-derived member pointer cast.
938 bool castToDerived(const CXXRecordDecl *Derived) {
939 if (!getDecl())
940 return true;
941 if (!isDerivedMember()) {
942 Path.push_back(Derived);
943 return true;
944 }
945 if (!castBack(Derived))
946 return false;
947 if (Path.empty())
948 DeclAndIsDerivedMember.setInt(false);
949 return true;
950 }
951 /// Perform a derived-to-base member pointer cast.
952 bool castToBase(const CXXRecordDecl *Base) {
953 if (!getDecl())
954 return true;
955 if (Path.empty())
956 DeclAndIsDerivedMember.setInt(true);
957 if (isDerivedMember()) {
958 Path.push_back(Base);
959 return true;
960 }
961 return castBack(Base);
962 }
963 };
Richard Smith357362d2011-12-13 06:39:58 +0000964
Richard Smith7bb00672012-02-01 01:42:44 +0000965 /// Compare two member pointers, which are assumed to be of the same type.
966 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
967 if (!LHS.getDecl() || !RHS.getDecl())
968 return !LHS.getDecl() && !RHS.getDecl();
969 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
970 return false;
971 return LHS.Path == RHS.Path;
972 }
John McCall93d91dc2010-05-07 17:22:02 +0000973}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000974
Richard Smith2e312c82012-03-03 22:46:17 +0000975static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000976static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
977 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000978 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000979static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
980static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000981static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
982 EvalInfo &Info);
983static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000984static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000985static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000986 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000987static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000988static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +0000989static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000990
991//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000992// Misc utilities
993//===----------------------------------------------------------------------===//
994
Richard Smith84401042013-06-03 05:03:02 +0000995/// Produce a string describing the given constexpr call.
996static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
997 unsigned ArgIndex = 0;
998 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
999 !isa<CXXConstructorDecl>(Frame->Callee) &&
1000 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1001
1002 if (!IsMemberCall)
1003 Out << *Frame->Callee << '(';
1004
1005 if (Frame->This && IsMemberCall) {
1006 APValue Val;
1007 Frame->This->moveInto(Val);
1008 Val.printPretty(Out, Frame->Info.Ctx,
1009 Frame->This->Designator.MostDerivedType);
1010 // FIXME: Add parens around Val if needed.
1011 Out << "->" << *Frame->Callee << '(';
1012 IsMemberCall = false;
1013 }
1014
1015 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1016 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1017 if (ArgIndex > (unsigned)IsMemberCall)
1018 Out << ", ";
1019
1020 const ParmVarDecl *Param = *I;
1021 const APValue &Arg = Frame->Arguments[ArgIndex];
1022 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1023
1024 if (ArgIndex == 0 && IsMemberCall)
1025 Out << "->" << *Frame->Callee << '(';
1026 }
1027
1028 Out << ')';
1029}
1030
Richard Smithd9f663b2013-04-22 15:31:51 +00001031/// Evaluate an expression to see if it had side-effects, and discard its
1032/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001033/// \return \c true if the caller should keep evaluating.
1034static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001035 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +00001036 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001037 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +00001038 return Info.keepEvaluatingAfterFailure();
1039 }
1040 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001041}
1042
Richard Smith861b5b52013-05-07 23:34:45 +00001043/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1044/// return its existing value.
1045static int64_t getExtValue(const APSInt &Value) {
1046 return Value.isSigned() ? Value.getSExtValue()
1047 : static_cast<int64_t>(Value.getZExtValue());
1048}
1049
Richard Smithd62306a2011-11-10 06:34:14 +00001050/// Should this call expression be treated as a string literal?
1051static bool IsStringLiteralCall(const CallExpr *E) {
1052 unsigned Builtin = E->isBuiltinCall();
1053 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1054 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1055}
1056
Richard Smithce40ad62011-11-12 22:28:03 +00001057static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001058 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1059 // constant expression of pointer type that evaluates to...
1060
1061 // ... a null pointer value, or a prvalue core constant expression of type
1062 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001063 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001064
Richard Smithce40ad62011-11-12 22:28:03 +00001065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1066 // ... the address of an object with static storage duration,
1067 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1068 return VD->hasGlobalStorage();
1069 // ... the address of a function,
1070 return isa<FunctionDecl>(D);
1071 }
1072
1073 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001074 switch (E->getStmtClass()) {
1075 default:
1076 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001077 case Expr::CompoundLiteralExprClass: {
1078 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1079 return CLE->isFileScope() && CLE->isLValue();
1080 }
Richard Smithe6c01442013-06-05 00:46:14 +00001081 case Expr::MaterializeTemporaryExprClass:
1082 // A materialized temporary might have been lifetime-extended to static
1083 // storage duration.
1084 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001085 // A string literal has static storage duration.
1086 case Expr::StringLiteralClass:
1087 case Expr::PredefinedExprClass:
1088 case Expr::ObjCStringLiteralClass:
1089 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001090 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001091 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001092 return true;
1093 case Expr::CallExprClass:
1094 return IsStringLiteralCall(cast<CallExpr>(E));
1095 // For GCC compatibility, &&label has static storage duration.
1096 case Expr::AddrLabelExprClass:
1097 return true;
1098 // A Block literal expression may be used as the initialization value for
1099 // Block variables at global or local static scope.
1100 case Expr::BlockExprClass:
1101 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001102 case Expr::ImplicitValueInitExprClass:
1103 // FIXME:
1104 // We can never form an lvalue with an implicit value initialization as its
1105 // base through expression evaluation, so these only appear in one case: the
1106 // implicit variable declaration we invent when checking whether a constexpr
1107 // constructor can produce a constant expression. We must assume that such
1108 // an expression might be a global lvalue.
1109 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001110 }
John McCall95007602010-05-10 23:27:23 +00001111}
1112
Richard Smithb228a862012-02-15 02:18:13 +00001113static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1114 assert(Base && "no location for a null lvalue");
1115 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1116 if (VD)
1117 Info.Note(VD->getLocation(), diag::note_declared_at);
1118 else
Ted Kremenek28831752012-08-23 20:46:57 +00001119 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001120 diag::note_constexpr_temporary_here);
1121}
1122
Richard Smith80815602011-11-07 05:07:52 +00001123/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001124/// value for an address or reference constant expression. Return true if we
1125/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001126static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1127 QualType Type, const LValue &LVal) {
1128 bool IsReferenceType = Type->isReferenceType();
1129
Richard Smith357362d2011-12-13 06:39:58 +00001130 APValue::LValueBase Base = LVal.getLValueBase();
1131 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1132
Richard Smith0dea49e2012-02-18 04:58:18 +00001133 // Check that the object is a global. Note that the fake 'this' object we
1134 // manufacture when checking potential constant expressions is conservatively
1135 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001136 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001137 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001138 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001139 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1140 << IsReferenceType << !Designator.Entries.empty()
1141 << !!VD << VD;
1142 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001143 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001144 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001145 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001146 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001147 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001148 }
Richard Smithb228a862012-02-15 02:18:13 +00001149 assert((Info.CheckingPotentialConstantExpression ||
1150 LVal.getLValueCallIndex() == 0) &&
1151 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001152
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001153 // Check if this is a thread-local variable.
1154 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1155 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001156 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001157 return false;
1158 }
1159 }
1160
Richard Smitha8105bc2012-01-06 16:39:00 +00001161 // Allow address constant expressions to be past-the-end pointers. This is
1162 // an extension: the standard requires them to point to an object.
1163 if (!IsReferenceType)
1164 return true;
1165
1166 // A reference constant expression must refer to an object.
1167 if (!Base) {
1168 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001169 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001170 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001171 }
1172
Richard Smith357362d2011-12-13 06:39:58 +00001173 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001174 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001175 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001176 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001177 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001178 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001179 }
1180
Richard Smith80815602011-11-07 05:07:52 +00001181 return true;
1182}
1183
Richard Smithfddd3842011-12-30 21:15:51 +00001184/// Check that this core constant expression is of literal type, and if not,
1185/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001186static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1187 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001188 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001189 return true;
1190
Richard Smith7525ff62013-05-09 07:14:00 +00001191 // C++1y: A constant initializer for an object o [...] may also invoke
1192 // constexpr constructors for o and its subobjects even if those objects
1193 // are of non-literal class types.
1194 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001195 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001196 return true;
1197
Richard Smithfddd3842011-12-30 21:15:51 +00001198 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001199 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001200 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001201 << E->getType();
1202 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001203 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001204 return false;
1205}
1206
Richard Smith0b0a0b62011-10-29 20:57:55 +00001207/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001208/// constant expression. If not, report an appropriate diagnostic. Does not
1209/// check that the expression is of literal type.
1210static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1211 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001212 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001213 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1214 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001215 return false;
1216 }
1217
Richard Smithb228a862012-02-15 02:18:13 +00001218 // Core issue 1454: For a literal constant expression of array or class type,
1219 // each subobject of its value shall have been initialized by a constant
1220 // expression.
1221 if (Value.isArray()) {
1222 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1223 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1224 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1225 Value.getArrayInitializedElt(I)))
1226 return false;
1227 }
1228 if (!Value.hasArrayFiller())
1229 return true;
1230 return CheckConstantExpression(Info, DiagLoc, EltTy,
1231 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001232 }
Richard Smithb228a862012-02-15 02:18:13 +00001233 if (Value.isUnion() && Value.getUnionField()) {
1234 return CheckConstantExpression(Info, DiagLoc,
1235 Value.getUnionField()->getType(),
1236 Value.getUnionValue());
1237 }
1238 if (Value.isStruct()) {
1239 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1240 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1241 unsigned BaseIndex = 0;
1242 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1243 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1244 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1245 Value.getStructBase(BaseIndex)))
1246 return false;
1247 }
1248 }
1249 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1250 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001251 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1252 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001253 return false;
1254 }
1255 }
1256
1257 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001258 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001259 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001260 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1261 }
1262
1263 // Everything else is fine.
1264 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001265}
1266
Richard Smith83c68212011-10-31 05:11:32 +00001267const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001268 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001269}
1270
1271static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001272 if (Value.CallIndex)
1273 return false;
1274 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1275 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001276}
1277
Richard Smithcecf1842011-11-01 21:06:14 +00001278static bool IsWeakLValue(const LValue &Value) {
1279 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001280 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001281}
1282
Richard Smith2e312c82012-03-03 22:46:17 +00001283static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001284 // A null base expression indicates a null pointer. These are always
1285 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001286 if (!Value.getLValueBase()) {
1287 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001288 return true;
1289 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001290
Richard Smith027bf112011-11-17 22:56:20 +00001291 // We have a non-null base. These are generally known to be true, but if it's
1292 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001293 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001294 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001295 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001296}
1297
Richard Smith2e312c82012-03-03 22:46:17 +00001298static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001299 switch (Val.getKind()) {
1300 case APValue::Uninitialized:
1301 return false;
1302 case APValue::Int:
1303 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001304 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001305 case APValue::Float:
1306 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001307 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001308 case APValue::ComplexInt:
1309 Result = Val.getComplexIntReal().getBoolValue() ||
1310 Val.getComplexIntImag().getBoolValue();
1311 return true;
1312 case APValue::ComplexFloat:
1313 Result = !Val.getComplexFloatReal().isZero() ||
1314 !Val.getComplexFloatImag().isZero();
1315 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001316 case APValue::LValue:
1317 return EvalPointerValueAsBool(Val, Result);
1318 case APValue::MemberPointer:
1319 Result = Val.getMemberPointerDecl();
1320 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001321 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001322 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001323 case APValue::Struct:
1324 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001325 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001326 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001327 }
1328
Richard Smith11562c52011-10-28 17:51:58 +00001329 llvm_unreachable("unknown APValue kind");
1330}
1331
1332static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1333 EvalInfo &Info) {
1334 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001335 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001336 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001337 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001338 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001339}
1340
Richard Smith357362d2011-12-13 06:39:58 +00001341template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001342static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001343 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001344 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001345 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001346}
1347
1348static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1349 QualType SrcType, const APFloat &Value,
1350 QualType DestType, APSInt &Result) {
1351 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001352 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001353 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001354
Richard Smith357362d2011-12-13 06:39:58 +00001355 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001356 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001357 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1358 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001359 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001360 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001361}
1362
Richard Smith357362d2011-12-13 06:39:58 +00001363static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1364 QualType SrcType, QualType DestType,
1365 APFloat &Result) {
1366 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001367 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001368 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1369 APFloat::rmNearestTiesToEven, &ignored)
1370 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001371 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001372 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001373}
1374
Richard Smith911e1422012-01-30 22:27:01 +00001375static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1376 QualType DestType, QualType SrcType,
1377 APSInt &Value) {
1378 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001379 APSInt Result = Value;
1380 // Figure out if this is a truncate, extend or noop cast.
1381 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001382 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001383 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001384 return Result;
1385}
1386
Richard Smith357362d2011-12-13 06:39:58 +00001387static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1388 QualType SrcType, const APSInt &Value,
1389 QualType DestType, APFloat &Result) {
1390 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1391 if (Result.convertFromAPInt(Value, Value.isSigned(),
1392 APFloat::rmNearestTiesToEven)
1393 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001394 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001395 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001396}
1397
Richard Smith49ca8aa2013-08-06 07:09:20 +00001398static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1399 APValue &Value, const FieldDecl *FD) {
1400 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1401
1402 if (!Value.isInt()) {
1403 // Trying to store a pointer-cast-to-integer into a bitfield.
1404 // FIXME: In this case, we should provide the diagnostic for casting
1405 // a pointer to an integer.
1406 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1407 Info.Diag(E);
1408 return false;
1409 }
1410
1411 APSInt &Int = Value.getInt();
1412 unsigned OldBitWidth = Int.getBitWidth();
1413 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1414 if (NewBitWidth < OldBitWidth)
1415 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1416 return true;
1417}
1418
Eli Friedman803acb32011-12-22 03:51:45 +00001419static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1420 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001421 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001422 if (!Evaluate(SVal, Info, E))
1423 return false;
1424 if (SVal.isInt()) {
1425 Res = SVal.getInt();
1426 return true;
1427 }
1428 if (SVal.isFloat()) {
1429 Res = SVal.getFloat().bitcastToAPInt();
1430 return true;
1431 }
1432 if (SVal.isVector()) {
1433 QualType VecTy = E->getType();
1434 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1435 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1436 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1437 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1438 Res = llvm::APInt::getNullValue(VecSize);
1439 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1440 APValue &Elt = SVal.getVectorElt(i);
1441 llvm::APInt EltAsInt;
1442 if (Elt.isInt()) {
1443 EltAsInt = Elt.getInt();
1444 } else if (Elt.isFloat()) {
1445 EltAsInt = Elt.getFloat().bitcastToAPInt();
1446 } else {
1447 // Don't try to handle vectors of anything other than int or float
1448 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001449 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001450 return false;
1451 }
1452 unsigned BaseEltSize = EltAsInt.getBitWidth();
1453 if (BigEndian)
1454 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1455 else
1456 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1457 }
1458 return true;
1459 }
1460 // Give up if the input isn't an int, float, or vector. For example, we
1461 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001462 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001463 return false;
1464}
1465
Richard Smith43e77732013-05-07 04:50:00 +00001466/// Perform the given integer operation, which is known to need at most BitWidth
1467/// bits, and check for overflow in the original type (if that type was not an
1468/// unsigned type).
1469template<typename Operation>
1470static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1471 const APSInt &LHS, const APSInt &RHS,
1472 unsigned BitWidth, Operation Op) {
1473 if (LHS.isUnsigned())
1474 return Op(LHS, RHS);
1475
1476 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1477 APSInt Result = Value.trunc(LHS.getBitWidth());
1478 if (Result.extend(BitWidth) != Value) {
1479 if (Info.getIntOverflowCheckMode())
1480 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1481 diag::warn_integer_constant_overflow)
1482 << Result.toString(10) << E->getType();
1483 else
1484 HandleOverflow(Info, E, Value, E->getType());
1485 }
1486 return Result;
1487}
1488
1489/// Perform the given binary integer operation.
1490static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1491 BinaryOperatorKind Opcode, APSInt RHS,
1492 APSInt &Result) {
1493 switch (Opcode) {
1494 default:
1495 Info.Diag(E);
1496 return false;
1497 case BO_Mul:
1498 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1499 std::multiplies<APSInt>());
1500 return true;
1501 case BO_Add:
1502 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1503 std::plus<APSInt>());
1504 return true;
1505 case BO_Sub:
1506 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1507 std::minus<APSInt>());
1508 return true;
1509 case BO_And: Result = LHS & RHS; return true;
1510 case BO_Xor: Result = LHS ^ RHS; return true;
1511 case BO_Or: Result = LHS | RHS; return true;
1512 case BO_Div:
1513 case BO_Rem:
1514 if (RHS == 0) {
1515 Info.Diag(E, diag::note_expr_divide_by_zero);
1516 return false;
1517 }
1518 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1519 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1520 LHS.isSigned() && LHS.isMinSignedValue())
1521 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1522 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1523 return true;
1524 case BO_Shl: {
1525 if (Info.getLangOpts().OpenCL)
1526 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1527 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1528 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1529 RHS.isUnsigned());
1530 else if (RHS.isSigned() && RHS.isNegative()) {
1531 // During constant-folding, a negative shift is an opposite shift. Such
1532 // a shift is not a constant expression.
1533 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1534 RHS = -RHS;
1535 goto shift_right;
1536 }
1537 shift_left:
1538 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1539 // the shifted type.
1540 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1541 if (SA != RHS) {
1542 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1543 << RHS << E->getType() << LHS.getBitWidth();
1544 } else if (LHS.isSigned()) {
1545 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1546 // operand, and must not overflow the corresponding unsigned type.
1547 if (LHS.isNegative())
1548 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1549 else if (LHS.countLeadingZeros() < SA)
1550 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1551 }
1552 Result = LHS << SA;
1553 return true;
1554 }
1555 case BO_Shr: {
1556 if (Info.getLangOpts().OpenCL)
1557 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1558 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1559 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1560 RHS.isUnsigned());
1561 else if (RHS.isSigned() && RHS.isNegative()) {
1562 // During constant-folding, a negative shift is an opposite shift. Such a
1563 // shift is not a constant expression.
1564 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1565 RHS = -RHS;
1566 goto shift_left;
1567 }
1568 shift_right:
1569 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1570 // shifted type.
1571 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1572 if (SA != RHS)
1573 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1574 << RHS << E->getType() << LHS.getBitWidth();
1575 Result = LHS >> SA;
1576 return true;
1577 }
1578
1579 case BO_LT: Result = LHS < RHS; return true;
1580 case BO_GT: Result = LHS > RHS; return true;
1581 case BO_LE: Result = LHS <= RHS; return true;
1582 case BO_GE: Result = LHS >= RHS; return true;
1583 case BO_EQ: Result = LHS == RHS; return true;
1584 case BO_NE: Result = LHS != RHS; return true;
1585 }
1586}
1587
Richard Smith861b5b52013-05-07 23:34:45 +00001588/// Perform the given binary floating-point operation, in-place, on LHS.
1589static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1590 APFloat &LHS, BinaryOperatorKind Opcode,
1591 const APFloat &RHS) {
1592 switch (Opcode) {
1593 default:
1594 Info.Diag(E);
1595 return false;
1596 case BO_Mul:
1597 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1598 break;
1599 case BO_Add:
1600 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1601 break;
1602 case BO_Sub:
1603 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1604 break;
1605 case BO_Div:
1606 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1607 break;
1608 }
1609
1610 if (LHS.isInfinity() || LHS.isNaN())
1611 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1612 return true;
1613}
1614
Richard Smitha8105bc2012-01-06 16:39:00 +00001615/// Cast an lvalue referring to a base subobject to a derived class, by
1616/// truncating the lvalue's path to the given length.
1617static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1618 const RecordDecl *TruncatedType,
1619 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001620 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001621
1622 // Check we actually point to a derived class object.
1623 if (TruncatedElements == D.Entries.size())
1624 return true;
1625 assert(TruncatedElements >= D.MostDerivedPathLength &&
1626 "not casting to a derived class");
1627 if (!Result.checkSubobject(Info, E, CSK_Derived))
1628 return false;
1629
1630 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001631 const RecordDecl *RD = TruncatedType;
1632 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001633 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001634 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1635 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001636 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001637 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001638 else
Richard Smithd62306a2011-11-10 06:34:14 +00001639 Result.Offset -= Layout.getBaseClassOffset(Base);
1640 RD = Base;
1641 }
Richard Smith027bf112011-11-17 22:56:20 +00001642 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001643 return true;
1644}
1645
John McCalld7bca762012-05-01 00:38:49 +00001646static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001647 const CXXRecordDecl *Derived,
1648 const CXXRecordDecl *Base,
1649 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001650 if (!RL) {
1651 if (Derived->isInvalidDecl()) return false;
1652 RL = &Info.Ctx.getASTRecordLayout(Derived);
1653 }
1654
Richard Smithd62306a2011-11-10 06:34:14 +00001655 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001656 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001657 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001658}
1659
Richard Smitha8105bc2012-01-06 16:39:00 +00001660static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001661 const CXXRecordDecl *DerivedDecl,
1662 const CXXBaseSpecifier *Base) {
1663 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1664
John McCalld7bca762012-05-01 00:38:49 +00001665 if (!Base->isVirtual())
1666 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001667
Richard Smitha8105bc2012-01-06 16:39:00 +00001668 SubobjectDesignator &D = Obj.Designator;
1669 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001670 return false;
1671
Richard Smitha8105bc2012-01-06 16:39:00 +00001672 // Extract most-derived object and corresponding type.
1673 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1674 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1675 return false;
1676
1677 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001678 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001679 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1680 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001681 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001682 return true;
1683}
1684
Richard Smith84401042013-06-03 05:03:02 +00001685static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1686 QualType Type, LValue &Result) {
1687 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1688 PathE = E->path_end();
1689 PathI != PathE; ++PathI) {
1690 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1691 *PathI))
1692 return false;
1693 Type = (*PathI)->getType();
1694 }
1695 return true;
1696}
1697
Richard Smithd62306a2011-11-10 06:34:14 +00001698/// Update LVal to refer to the given field, which must be a member of the type
1699/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001700static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001701 const FieldDecl *FD,
1702 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001703 if (!RL) {
1704 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001705 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001706 }
Richard Smithd62306a2011-11-10 06:34:14 +00001707
1708 unsigned I = FD->getFieldIndex();
1709 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001710 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001711 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001712}
1713
Richard Smith1b78b3d2012-01-25 22:15:11 +00001714/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001715static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001716 LValue &LVal,
1717 const IndirectFieldDecl *IFD) {
1718 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1719 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001720 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1721 return false;
1722 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001723}
1724
Richard Smithd62306a2011-11-10 06:34:14 +00001725/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001726static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1727 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001728 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1729 // extension.
1730 if (Type->isVoidType() || Type->isFunctionType()) {
1731 Size = CharUnits::One();
1732 return true;
1733 }
1734
1735 if (!Type->isConstantSizeType()) {
1736 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001737 // FIXME: Better diagnostic.
1738 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001739 return false;
1740 }
1741
1742 Size = Info.Ctx.getTypeSizeInChars(Type);
1743 return true;
1744}
1745
1746/// Update a pointer value to model pointer arithmetic.
1747/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001748/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001749/// \param LVal - The pointer value to be updated.
1750/// \param EltTy - The pointee type represented by LVal.
1751/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001752static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1753 LValue &LVal, QualType EltTy,
1754 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001755 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001756 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001757 return false;
1758
1759 // Compute the new offset in the appropriate width.
1760 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001761 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001762 return true;
1763}
1764
Richard Smith66c96992012-02-18 22:04:06 +00001765/// Update an lvalue to refer to a component of a complex number.
1766/// \param Info - Information about the ongoing evaluation.
1767/// \param LVal - The lvalue to be updated.
1768/// \param EltTy - The complex number's component type.
1769/// \param Imag - False for the real component, true for the imaginary.
1770static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1771 LValue &LVal, QualType EltTy,
1772 bool Imag) {
1773 if (Imag) {
1774 CharUnits SizeOfComponent;
1775 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1776 return false;
1777 LVal.Offset += SizeOfComponent;
1778 }
1779 LVal.addComplex(Info, E, EltTy, Imag);
1780 return true;
1781}
1782
Richard Smith27908702011-10-24 17:54:18 +00001783/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001784///
1785/// \param Info Information about the ongoing evaluation.
1786/// \param E An expression to be used when printing diagnostics.
1787/// \param VD The variable whose initializer should be obtained.
1788/// \param Frame The frame in which the variable was created. Must be null
1789/// if this variable is not local to the evaluation.
1790/// \param Result Filled in with a pointer to the value of the variable.
1791static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1792 const VarDecl *VD, CallStackFrame *Frame,
1793 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001794 // If this is a parameter to an active constexpr function call, perform
1795 // argument substitution.
1796 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001797 // Assume arguments of a potential constant expression are unknown
1798 // constant expressions.
1799 if (Info.CheckingPotentialConstantExpression)
1800 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001801 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001802 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001803 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001804 }
Richard Smith3229b742013-05-05 21:17:10 +00001805 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001806 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001807 }
Richard Smith27908702011-10-24 17:54:18 +00001808
Richard Smithd9f663b2013-04-22 15:31:51 +00001809 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001810 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001811 Result = Frame->getTemporary(VD);
1812 assert(Result && "missing value for local variable");
1813 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001814 }
1815
Richard Smithd0b4dd62011-12-19 06:19:21 +00001816 // Dig out the initializer, and use the declaration which it's attached to.
1817 const Expr *Init = VD->getAnyInitializer(VD);
1818 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001819 // If we're checking a potential constant expression, the variable could be
1820 // initialized later.
1821 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001822 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001823 return false;
1824 }
1825
Richard Smithd62306a2011-11-10 06:34:14 +00001826 // If we're currently evaluating the initializer of this declaration, use that
1827 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001828 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001829 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001830 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001831 }
1832
Richard Smithcecf1842011-11-01 21:06:14 +00001833 // Never evaluate the initializer of a weak variable. We can't be sure that
1834 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001835 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001836 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001837 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001838 }
Richard Smithcecf1842011-11-01 21:06:14 +00001839
Richard Smithd0b4dd62011-12-19 06:19:21 +00001840 // Check that we can fold the initializer. In C++, we will have already done
1841 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001842 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001843 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001844 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001845 Notes.size() + 1) << VD;
1846 Info.Note(VD->getLocation(), diag::note_declared_at);
1847 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001848 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001849 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001850 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001851 Notes.size() + 1) << VD;
1852 Info.Note(VD->getLocation(), diag::note_declared_at);
1853 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001854 }
Richard Smith27908702011-10-24 17:54:18 +00001855
Richard Smith3229b742013-05-05 21:17:10 +00001856 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001857 return true;
Richard Smith27908702011-10-24 17:54:18 +00001858}
1859
Richard Smith11562c52011-10-28 17:51:58 +00001860static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001861 Qualifiers Quals = T.getQualifiers();
1862 return Quals.hasConst() && !Quals.hasVolatile();
1863}
1864
Richard Smithe97cbd72011-11-11 04:05:33 +00001865/// Get the base index of the given base class within an APValue representing
1866/// the given derived class.
1867static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1868 const CXXRecordDecl *Base) {
1869 Base = Base->getCanonicalDecl();
1870 unsigned Index = 0;
1871 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1872 E = Derived->bases_end(); I != E; ++I, ++Index) {
1873 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1874 return Index;
1875 }
1876
1877 llvm_unreachable("base class missing from derived class's bases list");
1878}
1879
Richard Smith3da88fa2013-04-26 14:36:30 +00001880/// Extract the value of a character from a string literal.
1881static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1882 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001883 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001884 const StringLiteral *S = cast<StringLiteral>(Lit);
1885 const ConstantArrayType *CAT =
1886 Info.Ctx.getAsConstantArrayType(S->getType());
1887 assert(CAT && "string literal isn't an array");
1888 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001889 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001890
1891 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001892 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001893 if (Index < S->getLength())
1894 Value = S->getCodeUnit(Index);
1895 return Value;
1896}
1897
Richard Smith3da88fa2013-04-26 14:36:30 +00001898// Expand a string literal into an array of characters.
1899static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1900 APValue &Result) {
1901 const StringLiteral *S = cast<StringLiteral>(Lit);
1902 const ConstantArrayType *CAT =
1903 Info.Ctx.getAsConstantArrayType(S->getType());
1904 assert(CAT && "string literal isn't an array");
1905 QualType CharType = CAT->getElementType();
1906 assert(CharType->isIntegerType() && "unexpected character type");
1907
1908 unsigned Elts = CAT->getSize().getZExtValue();
1909 Result = APValue(APValue::UninitArray(),
1910 std::min(S->getLength(), Elts), Elts);
1911 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1912 CharType->isUnsignedIntegerType());
1913 if (Result.hasArrayFiller())
1914 Result.getArrayFiller() = APValue(Value);
1915 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1916 Value = S->getCodeUnit(I);
1917 Result.getArrayInitializedElt(I) = APValue(Value);
1918 }
1919}
1920
1921// Expand an array so that it has more than Index filled elements.
1922static void expandArray(APValue &Array, unsigned Index) {
1923 unsigned Size = Array.getArraySize();
1924 assert(Index < Size);
1925
1926 // Always at least double the number of elements for which we store a value.
1927 unsigned OldElts = Array.getArrayInitializedElts();
1928 unsigned NewElts = std::max(Index+1, OldElts * 2);
1929 NewElts = std::min(Size, std::max(NewElts, 8u));
1930
1931 // Copy the data across.
1932 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1933 for (unsigned I = 0; I != OldElts; ++I)
1934 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1935 for (unsigned I = OldElts; I != NewElts; ++I)
1936 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1937 if (NewValue.hasArrayFiller())
1938 NewValue.getArrayFiller() = Array.getArrayFiller();
1939 Array.swap(NewValue);
1940}
1941
Richard Smith861b5b52013-05-07 23:34:45 +00001942/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001943enum AccessKinds {
1944 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001945 AK_Assign,
1946 AK_Increment,
1947 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001948};
1949
Richard Smith3229b742013-05-05 21:17:10 +00001950/// A handle to a complete object (an object that is not a subobject of
1951/// another object).
1952struct CompleteObject {
1953 /// The value of the complete object.
1954 APValue *Value;
1955 /// The type of the complete object.
1956 QualType Type;
1957
1958 CompleteObject() : Value(0) {}
1959 CompleteObject(APValue *Value, QualType Type)
1960 : Value(Value), Type(Type) {
1961 assert(Value && "missing value for complete object");
1962 }
1963
David Blaikie7d170102013-05-15 07:37:26 +00001964 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001965};
1966
Richard Smith3da88fa2013-04-26 14:36:30 +00001967/// Find the designated sub-object of an rvalue.
1968template<typename SubobjectHandler>
1969typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001970findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001971 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001972 if (Sub.Invalid)
1973 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001975 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001976 if (Info.getLangOpts().CPlusPlus11)
1977 Info.Diag(E, diag::note_constexpr_access_past_end)
1978 << handler.AccessKind;
1979 else
1980 Info.Diag(E);
1981 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001982 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001983
Richard Smith3229b742013-05-05 21:17:10 +00001984 APValue *O = Obj.Value;
1985 QualType ObjType = Obj.Type;
Richard Smith49ca8aa2013-08-06 07:09:20 +00001986 const FieldDecl *LastField = 0;
1987
Richard Smithd62306a2011-11-10 06:34:14 +00001988 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00001989 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
1990 if (O->isUninit()) {
1991 if (!Info.CheckingPotentialConstantExpression)
1992 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1993 return handler.failed();
1994 }
1995
Richard Smith49ca8aa2013-08-06 07:09:20 +00001996 if (I == N) {
1997 if (!handler.found(*O, ObjType))
1998 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001999
Richard Smith49ca8aa2013-08-06 07:09:20 +00002000 // If we modified a bit-field, truncate it to the right width.
2001 if (handler.AccessKind != AK_Read &&
2002 LastField && LastField->isBitField() &&
2003 !truncateBitfieldValue(Info, E, *O, LastField))
2004 return false;
2005
2006 return true;
2007 }
2008
2009 LastField = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002010 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002011 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002012 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002013 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002014 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002015 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002016 // Note, it should not be possible to form a pointer with a valid
2017 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002018 if (Info.getLangOpts().CPlusPlus11)
2019 Info.Diag(E, diag::note_constexpr_access_past_end)
2020 << handler.AccessKind;
2021 else
2022 Info.Diag(E);
2023 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002024 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002025
2026 ObjType = CAT->getElementType();
2027
Richard Smith14a94132012-02-17 03:35:37 +00002028 // An array object is represented as either an Array APValue or as an
2029 // LValue which refers to a string literal.
2030 if (O->isLValue()) {
2031 assert(I == N - 1 && "extracting subobject of character?");
2032 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002033 if (handler.AccessKind != AK_Read)
2034 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2035 *O);
2036 else
2037 return handler.foundString(*O, ObjType, Index);
2038 }
2039
2040 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002041 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002042 else if (handler.AccessKind != AK_Read) {
2043 expandArray(*O, Index);
2044 O = &O->getArrayInitializedElt(Index);
2045 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002046 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002047 } else if (ObjType->isAnyComplexType()) {
2048 // Next subobject is a complex number.
2049 uint64_t Index = Sub.Entries[I].ArrayIndex;
2050 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002051 if (Info.getLangOpts().CPlusPlus11)
2052 Info.Diag(E, diag::note_constexpr_access_past_end)
2053 << handler.AccessKind;
2054 else
2055 Info.Diag(E);
2056 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002057 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002058
2059 bool WasConstQualified = ObjType.isConstQualified();
2060 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2061 if (WasConstQualified)
2062 ObjType.addConst();
2063
Richard Smith66c96992012-02-18 22:04:06 +00002064 assert(I == N - 1 && "extracting subobject of scalar?");
2065 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002066 return handler.found(Index ? O->getComplexIntImag()
2067 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002068 } else {
2069 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002070 return handler.found(Index ? O->getComplexFloatImag()
2071 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002072 }
Richard Smithd62306a2011-11-10 06:34:14 +00002073 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002074 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002075 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002076 << Field;
2077 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002078 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002079 }
2080
Richard Smithd62306a2011-11-10 06:34:14 +00002081 // Next subobject is a class, struct or union field.
2082 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2083 if (RD->isUnion()) {
2084 const FieldDecl *UnionField = O->getUnionField();
2085 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002086 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002087 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2088 << handler.AccessKind << Field << !UnionField << UnionField;
2089 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 }
Richard Smithd62306a2011-11-10 06:34:14 +00002091 O = &O->getUnionValue();
2092 } else
2093 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002094
2095 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002096 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002097 if (WasConstQualified && !Field->isMutable())
2098 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002099
2100 if (ObjType.isVolatileQualified()) {
2101 if (Info.getLangOpts().CPlusPlus) {
2102 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002103 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2104 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002105 Info.Note(Field->getLocation(), diag::note_declared_at);
2106 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002107 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002108 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002109 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002110 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002111
2112 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002113 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002114 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002115 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2116 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2117 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002118
2119 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002120 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002121 if (WasConstQualified)
2122 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002123 }
2124 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002125}
2126
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002127namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002128struct ExtractSubobjectHandler {
2129 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002130 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002131
2132 static const AccessKinds AccessKind = AK_Read;
2133
2134 typedef bool result_type;
2135 bool failed() { return false; }
2136 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002137 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002138 return true;
2139 }
2140 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002141 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002142 return true;
2143 }
2144 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002145 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002146 return true;
2147 }
2148 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002149 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002150 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2151 return true;
2152 }
2153};
Richard Smith3229b742013-05-05 21:17:10 +00002154} // end anonymous namespace
2155
Richard Smith3da88fa2013-04-26 14:36:30 +00002156const AccessKinds ExtractSubobjectHandler::AccessKind;
2157
2158/// Extract the designated sub-object of an rvalue.
2159static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002160 const CompleteObject &Obj,
2161 const SubobjectDesignator &Sub,
2162 APValue &Result) {
2163 ExtractSubobjectHandler Handler = { Info, Result };
2164 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002165}
2166
Richard Smith3229b742013-05-05 21:17:10 +00002167namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002168struct ModifySubobjectHandler {
2169 EvalInfo &Info;
2170 APValue &NewVal;
2171 const Expr *E;
2172
2173 typedef bool result_type;
2174 static const AccessKinds AccessKind = AK_Assign;
2175
2176 bool checkConst(QualType QT) {
2177 // Assigning to a const object has undefined behavior.
2178 if (QT.isConstQualified()) {
2179 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2180 return false;
2181 }
2182 return true;
2183 }
2184
2185 bool failed() { return false; }
2186 bool found(APValue &Subobj, QualType SubobjType) {
2187 if (!checkConst(SubobjType))
2188 return false;
2189 // We've been given ownership of NewVal, so just swap it in.
2190 Subobj.swap(NewVal);
2191 return true;
2192 }
2193 bool found(APSInt &Value, QualType SubobjType) {
2194 if (!checkConst(SubobjType))
2195 return false;
2196 if (!NewVal.isInt()) {
2197 // Maybe trying to write a cast pointer value into a complex?
2198 Info.Diag(E);
2199 return false;
2200 }
2201 Value = NewVal.getInt();
2202 return true;
2203 }
2204 bool found(APFloat &Value, QualType SubobjType) {
2205 if (!checkConst(SubobjType))
2206 return false;
2207 Value = NewVal.getFloat();
2208 return true;
2209 }
2210 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2211 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2212 }
2213};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002214} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002215
Richard Smith3229b742013-05-05 21:17:10 +00002216const AccessKinds ModifySubobjectHandler::AccessKind;
2217
Richard Smith3da88fa2013-04-26 14:36:30 +00002218/// Update the designated sub-object of an rvalue to the given value.
2219static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002220 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002221 const SubobjectDesignator &Sub,
2222 APValue &NewVal) {
2223 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002224 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002225}
2226
Richard Smith84f6dcf2012-02-02 01:16:57 +00002227/// Find the position where two subobject designators diverge, or equivalently
2228/// the length of the common initial subsequence.
2229static unsigned FindDesignatorMismatch(QualType ObjType,
2230 const SubobjectDesignator &A,
2231 const SubobjectDesignator &B,
2232 bool &WasArrayIndex) {
2233 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2234 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002235 if (!ObjType.isNull() &&
2236 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002237 // Next subobject is an array element.
2238 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2239 WasArrayIndex = true;
2240 return I;
2241 }
Richard Smith66c96992012-02-18 22:04:06 +00002242 if (ObjType->isAnyComplexType())
2243 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2244 else
2245 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002246 } else {
2247 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2248 WasArrayIndex = false;
2249 return I;
2250 }
2251 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2252 // Next subobject is a field.
2253 ObjType = FD->getType();
2254 else
2255 // Next subobject is a base class.
2256 ObjType = QualType();
2257 }
2258 }
2259 WasArrayIndex = false;
2260 return I;
2261}
2262
2263/// Determine whether the given subobject designators refer to elements of the
2264/// same array object.
2265static bool AreElementsOfSameArray(QualType ObjType,
2266 const SubobjectDesignator &A,
2267 const SubobjectDesignator &B) {
2268 if (A.Entries.size() != B.Entries.size())
2269 return false;
2270
2271 bool IsArray = A.MostDerivedArraySize != 0;
2272 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2273 // A is a subobject of the array element.
2274 return false;
2275
2276 // If A (and B) designates an array element, the last entry will be the array
2277 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2278 // of length 1' case, and the entire path must match.
2279 bool WasArrayIndex;
2280 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2281 return CommonLength >= A.Entries.size() - IsArray;
2282}
2283
Richard Smith3229b742013-05-05 21:17:10 +00002284/// Find the complete object to which an LValue refers.
2285CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2286 const LValue &LVal, QualType LValType) {
2287 if (!LVal.Base) {
2288 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2289 return CompleteObject();
2290 }
2291
2292 CallStackFrame *Frame = 0;
2293 if (LVal.CallIndex) {
2294 Frame = Info.getCallFrame(LVal.CallIndex);
2295 if (!Frame) {
2296 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2297 << AK << LVal.Base.is<const ValueDecl*>();
2298 NoteLValueLocation(Info, LVal.Base);
2299 return CompleteObject();
2300 }
Richard Smith3229b742013-05-05 21:17:10 +00002301 }
2302
2303 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2304 // is not a constant expression (even if the object is non-volatile). We also
2305 // apply this rule to C++98, in order to conform to the expected 'volatile'
2306 // semantics.
2307 if (LValType.isVolatileQualified()) {
2308 if (Info.getLangOpts().CPlusPlus)
2309 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2310 << AK << LValType;
2311 else
2312 Info.Diag(E);
2313 return CompleteObject();
2314 }
2315
2316 // Compute value storage location and type of base object.
2317 APValue *BaseVal = 0;
Richard Smith84401042013-06-03 05:03:02 +00002318 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002319
2320 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2321 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2322 // In C++11, constexpr, non-volatile variables initialized with constant
2323 // expressions are constant expressions too. Inside constexpr functions,
2324 // parameters are constant expressions even if they're non-const.
2325 // In C++1y, objects local to a constant expression (those with a Frame) are
2326 // both readable and writable inside constant expressions.
2327 // In C, such things can also be folded, although they are not ICEs.
2328 const VarDecl *VD = dyn_cast<VarDecl>(D);
2329 if (VD) {
2330 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2331 VD = VDef;
2332 }
2333 if (!VD || VD->isInvalidDecl()) {
2334 Info.Diag(E);
2335 return CompleteObject();
2336 }
2337
2338 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002339 if (BaseType.isVolatileQualified()) {
2340 if (Info.getLangOpts().CPlusPlus) {
2341 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2342 << AK << 1 << VD;
2343 Info.Note(VD->getLocation(), diag::note_declared_at);
2344 } else {
2345 Info.Diag(E);
2346 }
2347 return CompleteObject();
2348 }
2349
2350 // Unless we're looking at a local variable or argument in a constexpr call,
2351 // the variable we're reading must be const.
2352 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002353 if (Info.getLangOpts().CPlusPlus1y &&
2354 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2355 // OK, we can read and modify an object if we're in the process of
2356 // evaluating its initializer, because its lifetime began in this
2357 // evaluation.
2358 } else if (AK != AK_Read) {
2359 // All the remaining cases only permit reading.
2360 Info.Diag(E, diag::note_constexpr_modify_global);
2361 return CompleteObject();
2362 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002363 // OK, we can read this variable.
2364 } else if (BaseType->isIntegralOrEnumerationType()) {
2365 if (!BaseType.isConstQualified()) {
2366 if (Info.getLangOpts().CPlusPlus) {
2367 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2368 Info.Note(VD->getLocation(), diag::note_declared_at);
2369 } else {
2370 Info.Diag(E);
2371 }
2372 return CompleteObject();
2373 }
2374 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2375 // We support folding of const floating-point types, in order to make
2376 // static const data members of such types (supported as an extension)
2377 // more useful.
2378 if (Info.getLangOpts().CPlusPlus11) {
2379 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2380 Info.Note(VD->getLocation(), diag::note_declared_at);
2381 } else {
2382 Info.CCEDiag(E);
2383 }
2384 } else {
2385 // FIXME: Allow folding of values of any literal type in all languages.
2386 if (Info.getLangOpts().CPlusPlus11) {
2387 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2388 Info.Note(VD->getLocation(), diag::note_declared_at);
2389 } else {
2390 Info.Diag(E);
2391 }
2392 return CompleteObject();
2393 }
2394 }
2395
2396 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2397 return CompleteObject();
2398 } else {
2399 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2400
2401 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002402 if (const MaterializeTemporaryExpr *MTE =
2403 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2404 assert(MTE->getStorageDuration() == SD_Static &&
2405 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002406
Richard Smithe6c01442013-06-05 00:46:14 +00002407 // Per C++1y [expr.const]p2:
2408 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2409 // - a [...] glvalue of integral or enumeration type that refers to
2410 // a non-volatile const object [...]
2411 // [...]
2412 // - a [...] glvalue of literal type that refers to a non-volatile
2413 // object whose lifetime began within the evaluation of e.
2414 //
2415 // C++11 misses the 'began within the evaluation of e' check and
2416 // instead allows all temporaries, including things like:
2417 // int &&r = 1;
2418 // int x = ++r;
2419 // constexpr int k = r;
2420 // Therefore we use the C++1y rules in C++11 too.
2421 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2422 const ValueDecl *ED = MTE->getExtendingDecl();
2423 if (!(BaseType.isConstQualified() &&
2424 BaseType->isIntegralOrEnumerationType()) &&
2425 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2426 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2427 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2428 return CompleteObject();
2429 }
2430
2431 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2432 assert(BaseVal && "got reference to unevaluated temporary");
2433 } else {
2434 Info.Diag(E);
2435 return CompleteObject();
2436 }
2437 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002438 BaseVal = Frame->getTemporary(Base);
2439 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002440 }
Richard Smith3229b742013-05-05 21:17:10 +00002441
2442 // Volatile temporary objects cannot be accessed in constant expressions.
2443 if (BaseType.isVolatileQualified()) {
2444 if (Info.getLangOpts().CPlusPlus) {
2445 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2446 << AK << 0;
2447 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2448 } else {
2449 Info.Diag(E);
2450 }
2451 return CompleteObject();
2452 }
2453 }
2454
Richard Smith7525ff62013-05-09 07:14:00 +00002455 // During the construction of an object, it is not yet 'const'.
2456 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2457 // and this doesn't do quite the right thing for const subobjects of the
2458 // object under construction.
2459 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2460 BaseType = Info.Ctx.getCanonicalType(BaseType);
2461 BaseType.removeLocalConst();
2462 }
2463
Richard Smith3229b742013-05-05 21:17:10 +00002464 // In C++1y, we can't safely access any mutable state when checking a
2465 // potential constant expression.
2466 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2467 Info.CheckingPotentialConstantExpression)
2468 return CompleteObject();
2469
2470 return CompleteObject(BaseVal, BaseType);
2471}
2472
Richard Smith243ef902013-05-05 23:31:59 +00002473/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2474/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2475/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002476///
2477/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002478/// \param Conv - The expression for which we are performing the conversion.
2479/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002480/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2481/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002482/// \param LVal - The glvalue on which we are attempting to perform this action.
2483/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002484static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002485 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002486 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002487 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002488 return false;
2489
Richard Smith3229b742013-05-05 21:17:10 +00002490 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002491 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002492 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2493 !Type.isVolatileQualified()) {
2494 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2495 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2496 // initializer until now for such expressions. Such an expression can't be
2497 // an ICE in C, so this only matters for fold.
2498 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2499 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002500 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002501 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002502 }
Richard Smith3229b742013-05-05 21:17:10 +00002503 APValue Lit;
2504 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2505 return false;
2506 CompleteObject LitObj(&Lit, Base->getType());
2507 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2508 } else if (isa<StringLiteral>(Base)) {
2509 // We represent a string literal array as an lvalue pointing at the
2510 // corresponding expression, rather than building an array of chars.
2511 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2512 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2513 CompleteObject StrObj(&Str, Base->getType());
2514 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002515 }
Richard Smith11562c52011-10-28 17:51:58 +00002516 }
2517
Richard Smith3229b742013-05-05 21:17:10 +00002518 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2519 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002520}
2521
2522/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002523static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002524 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002525 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002526 return false;
2527
Richard Smith3229b742013-05-05 21:17:10 +00002528 if (!Info.getLangOpts().CPlusPlus1y) {
2529 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002530 return false;
2531 }
2532
Richard Smith3229b742013-05-05 21:17:10 +00002533 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2534 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002535}
2536
Richard Smith243ef902013-05-05 23:31:59 +00002537static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2538 return T->isSignedIntegerType() &&
2539 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2540}
2541
2542namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002543struct CompoundAssignSubobjectHandler {
2544 EvalInfo &Info;
2545 const Expr *E;
2546 QualType PromotedLHSType;
2547 BinaryOperatorKind Opcode;
2548 const APValue &RHS;
2549
2550 static const AccessKinds AccessKind = AK_Assign;
2551
2552 typedef bool result_type;
2553
2554 bool checkConst(QualType QT) {
2555 // Assigning to a const object has undefined behavior.
2556 if (QT.isConstQualified()) {
2557 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2558 return false;
2559 }
2560 return true;
2561 }
2562
2563 bool failed() { return false; }
2564 bool found(APValue &Subobj, QualType SubobjType) {
2565 switch (Subobj.getKind()) {
2566 case APValue::Int:
2567 return found(Subobj.getInt(), SubobjType);
2568 case APValue::Float:
2569 return found(Subobj.getFloat(), SubobjType);
2570 case APValue::ComplexInt:
2571 case APValue::ComplexFloat:
2572 // FIXME: Implement complex compound assignment.
2573 Info.Diag(E);
2574 return false;
2575 case APValue::LValue:
2576 return foundPointer(Subobj, SubobjType);
2577 default:
2578 // FIXME: can this happen?
2579 Info.Diag(E);
2580 return false;
2581 }
2582 }
2583 bool found(APSInt &Value, QualType SubobjType) {
2584 if (!checkConst(SubobjType))
2585 return false;
2586
2587 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2588 // We don't support compound assignment on integer-cast-to-pointer
2589 // values.
2590 Info.Diag(E);
2591 return false;
2592 }
2593
2594 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2595 SubobjType, Value);
2596 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2597 return false;
2598 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2599 return true;
2600 }
2601 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002602 return checkConst(SubobjType) &&
2603 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2604 Value) &&
2605 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2606 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002607 }
2608 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2609 if (!checkConst(SubobjType))
2610 return false;
2611
2612 QualType PointeeType;
2613 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2614 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002615
2616 if (PointeeType.isNull() || !RHS.isInt() ||
2617 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002618 Info.Diag(E);
2619 return false;
2620 }
2621
Richard Smith861b5b52013-05-07 23:34:45 +00002622 int64_t Offset = getExtValue(RHS.getInt());
2623 if (Opcode == BO_Sub)
2624 Offset = -Offset;
2625
2626 LValue LVal;
2627 LVal.setFrom(Info.Ctx, Subobj);
2628 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2629 return false;
2630 LVal.moveInto(Subobj);
2631 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002632 }
2633 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2634 llvm_unreachable("shouldn't encounter string elements here");
2635 }
2636};
2637} // end anonymous namespace
2638
2639const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2640
2641/// Perform a compound assignment of LVal <op>= RVal.
2642static bool handleCompoundAssignment(
2643 EvalInfo &Info, const Expr *E,
2644 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2645 BinaryOperatorKind Opcode, const APValue &RVal) {
2646 if (LVal.Designator.Invalid)
2647 return false;
2648
2649 if (!Info.getLangOpts().CPlusPlus1y) {
2650 Info.Diag(E);
2651 return false;
2652 }
2653
2654 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2655 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2656 RVal };
2657 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2658}
2659
2660namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002661struct IncDecSubobjectHandler {
2662 EvalInfo &Info;
2663 const Expr *E;
2664 AccessKinds AccessKind;
2665 APValue *Old;
2666
2667 typedef bool result_type;
2668
2669 bool checkConst(QualType QT) {
2670 // Assigning to a const object has undefined behavior.
2671 if (QT.isConstQualified()) {
2672 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2673 return false;
2674 }
2675 return true;
2676 }
2677
2678 bool failed() { return false; }
2679 bool found(APValue &Subobj, QualType SubobjType) {
2680 // Stash the old value. Also clear Old, so we don't clobber it later
2681 // if we're post-incrementing a complex.
2682 if (Old) {
2683 *Old = Subobj;
2684 Old = 0;
2685 }
2686
2687 switch (Subobj.getKind()) {
2688 case APValue::Int:
2689 return found(Subobj.getInt(), SubobjType);
2690 case APValue::Float:
2691 return found(Subobj.getFloat(), SubobjType);
2692 case APValue::ComplexInt:
2693 return found(Subobj.getComplexIntReal(),
2694 SubobjType->castAs<ComplexType>()->getElementType()
2695 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2696 case APValue::ComplexFloat:
2697 return found(Subobj.getComplexFloatReal(),
2698 SubobjType->castAs<ComplexType>()->getElementType()
2699 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2700 case APValue::LValue:
2701 return foundPointer(Subobj, SubobjType);
2702 default:
2703 // FIXME: can this happen?
2704 Info.Diag(E);
2705 return false;
2706 }
2707 }
2708 bool found(APSInt &Value, QualType SubobjType) {
2709 if (!checkConst(SubobjType))
2710 return false;
2711
2712 if (!SubobjType->isIntegerType()) {
2713 // We don't support increment / decrement on integer-cast-to-pointer
2714 // values.
2715 Info.Diag(E);
2716 return false;
2717 }
2718
2719 if (Old) *Old = APValue(Value);
2720
2721 // bool arithmetic promotes to int, and the conversion back to bool
2722 // doesn't reduce mod 2^n, so special-case it.
2723 if (SubobjType->isBooleanType()) {
2724 if (AccessKind == AK_Increment)
2725 Value = 1;
2726 else
2727 Value = !Value;
2728 return true;
2729 }
2730
2731 bool WasNegative = Value.isNegative();
2732 if (AccessKind == AK_Increment) {
2733 ++Value;
2734
2735 if (!WasNegative && Value.isNegative() &&
2736 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2737 APSInt ActualValue(Value, /*IsUnsigned*/true);
2738 HandleOverflow(Info, E, ActualValue, SubobjType);
2739 }
2740 } else {
2741 --Value;
2742
2743 if (WasNegative && !Value.isNegative() &&
2744 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2745 unsigned BitWidth = Value.getBitWidth();
2746 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2747 ActualValue.setBit(BitWidth);
2748 HandleOverflow(Info, E, ActualValue, SubobjType);
2749 }
2750 }
2751 return true;
2752 }
2753 bool found(APFloat &Value, QualType SubobjType) {
2754 if (!checkConst(SubobjType))
2755 return false;
2756
2757 if (Old) *Old = APValue(Value);
2758
2759 APFloat One(Value.getSemantics(), 1);
2760 if (AccessKind == AK_Increment)
2761 Value.add(One, APFloat::rmNearestTiesToEven);
2762 else
2763 Value.subtract(One, APFloat::rmNearestTiesToEven);
2764 return true;
2765 }
2766 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2767 if (!checkConst(SubobjType))
2768 return false;
2769
2770 QualType PointeeType;
2771 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2772 PointeeType = PT->getPointeeType();
2773 else {
2774 Info.Diag(E);
2775 return false;
2776 }
2777
2778 LValue LVal;
2779 LVal.setFrom(Info.Ctx, Subobj);
2780 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2781 AccessKind == AK_Increment ? 1 : -1))
2782 return false;
2783 LVal.moveInto(Subobj);
2784 return true;
2785 }
2786 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2787 llvm_unreachable("shouldn't encounter string elements here");
2788 }
2789};
2790} // end anonymous namespace
2791
2792/// Perform an increment or decrement on LVal.
2793static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2794 QualType LValType, bool IsIncrement, APValue *Old) {
2795 if (LVal.Designator.Invalid)
2796 return false;
2797
2798 if (!Info.getLangOpts().CPlusPlus1y) {
2799 Info.Diag(E);
2800 return false;
2801 }
2802
2803 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2804 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2805 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2806 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2807}
2808
Richard Smithe97cbd72011-11-11 04:05:33 +00002809/// Build an lvalue for the object argument of a member function call.
2810static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2811 LValue &This) {
2812 if (Object->getType()->isPointerType())
2813 return EvaluatePointer(Object, This, Info);
2814
2815 if (Object->isGLValue())
2816 return EvaluateLValue(Object, This, Info);
2817
Richard Smithd9f663b2013-04-22 15:31:51 +00002818 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002819 return EvaluateTemporary(Object, This, Info);
2820
2821 return false;
2822}
2823
2824/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2825/// lvalue referring to the result.
2826///
2827/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00002828/// \param LV - An lvalue referring to the base of the member pointer.
2829/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00002830/// \param IncludeMember - Specifies whether the member itself is included in
2831/// the resulting LValue subobject designator. This is not possible when
2832/// creating a bound member function.
2833/// \return The field or method declaration to which the member pointer refers,
2834/// or 0 if evaluation fails.
2835static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00002836 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00002837 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00002838 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00002839 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00002840 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00002841 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Richard Smith027bf112011-11-17 22:56:20 +00002842 return 0;
2843
2844 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2845 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00002846 if (!MemPtr.getDecl()) {
2847 // FIXME: Specific diagnostic.
2848 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002849 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002850 }
Richard Smith253c2a32012-01-27 01:14:48 +00002851
Richard Smith027bf112011-11-17 22:56:20 +00002852 if (MemPtr.isDerivedMember()) {
2853 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002854 // The end of the derived-to-base path for the base object must match the
2855 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002856 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00002857 LV.Designator.Entries.size()) {
2858 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002859 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002860 }
Richard Smith027bf112011-11-17 22:56:20 +00002861 unsigned PathLengthToMember =
2862 LV.Designator.Entries.size() - MemPtr.Path.size();
2863 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2864 const CXXRecordDecl *LVDecl = getAsBaseClass(
2865 LV.Designator.Entries[PathLengthToMember + I]);
2866 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00002867 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2868 Info.Diag(RHS);
Richard Smith027bf112011-11-17 22:56:20 +00002869 return 0;
Richard Smith84401042013-06-03 05:03:02 +00002870 }
Richard Smith027bf112011-11-17 22:56:20 +00002871 }
2872
2873 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00002874 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00002875 PathLengthToMember))
2876 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002877 } else if (!MemPtr.Path.empty()) {
2878 // Extend the LValue path with the member pointer's path.
2879 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2880 MemPtr.Path.size() + IncludeMember);
2881
2882 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00002883 if (const PointerType *PT = LVType->getAs<PointerType>())
2884 LVType = PT->getPointeeType();
2885 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2886 assert(RD && "member pointer access on non-class-type expression");
2887 // The first class in the path is that of the lvalue.
2888 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2889 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00002890 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
John McCalld7bca762012-05-01 00:38:49 +00002891 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002892 RD = Base;
2893 }
2894 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00002895 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2896 MemPtr.getContainingRecord()))
John McCalld7bca762012-05-01 00:38:49 +00002897 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002898 }
2899
2900 // Add the member. Note that we cannot build bound member functions here.
2901 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002902 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002903 if (!HandleLValueMember(Info, RHS, LV, FD))
John McCalld7bca762012-05-01 00:38:49 +00002904 return 0;
2905 } else if (const IndirectFieldDecl *IFD =
2906 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00002907 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
John McCalld7bca762012-05-01 00:38:49 +00002908 return 0;
2909 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002910 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002911 }
Richard Smith027bf112011-11-17 22:56:20 +00002912 }
2913
2914 return MemPtr.getDecl();
2915}
2916
Richard Smith84401042013-06-03 05:03:02 +00002917static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2918 const BinaryOperator *BO,
2919 LValue &LV,
2920 bool IncludeMember = true) {
2921 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2922
2923 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
2924 if (Info.keepEvaluatingAfterFailure()) {
2925 MemberPtr MemPtr;
2926 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
2927 }
2928 return 0;
2929 }
2930
2931 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
2932 BO->getRHS(), IncludeMember);
2933}
2934
Richard Smith027bf112011-11-17 22:56:20 +00002935/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2936/// the provided lvalue, which currently refers to the base object.
2937static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2938 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002939 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002940 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002941 return false;
2942
Richard Smitha8105bc2012-01-06 16:39:00 +00002943 QualType TargetQT = E->getType();
2944 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2945 TargetQT = PT->getPointeeType();
2946
2947 // Check this cast lands within the final derived-to-base subobject path.
2948 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002949 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002950 << D.MostDerivedType << TargetQT;
2951 return false;
2952 }
2953
Richard Smith027bf112011-11-17 22:56:20 +00002954 // Check the type of the final cast. We don't need to check the path,
2955 // since a cast can only be formed if the path is unique.
2956 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002957 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2958 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002959 if (NewEntriesSize == D.MostDerivedPathLength)
2960 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2961 else
Richard Smith027bf112011-11-17 22:56:20 +00002962 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002963 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002964 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002965 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002966 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002967 }
Richard Smith027bf112011-11-17 22:56:20 +00002968
2969 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002970 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002971}
2972
Mike Stump876387b2009-10-27 22:09:17 +00002973namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002974enum EvalStmtResult {
2975 /// Evaluation failed.
2976 ESR_Failed,
2977 /// Hit a 'return' statement.
2978 ESR_Returned,
2979 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002980 ESR_Succeeded,
2981 /// Hit a 'continue' statement.
2982 ESR_Continue,
2983 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002984 ESR_Break,
2985 /// Still scanning for 'case' or 'default' statement.
2986 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002987};
2988}
2989
Richard Smithd9f663b2013-04-22 15:31:51 +00002990static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2992 // We don't need to evaluate the initializer for a static local.
2993 if (!VD->hasLocalStorage())
2994 return true;
2995
2996 LValue Result;
2997 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00002998 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00002999
Richard Smith51f03172013-06-20 03:00:05 +00003000 if (!VD->getInit()) {
3001 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3002 << false << VD->getType();
3003 Val = APValue();
3004 return false;
3005 }
3006
Richard Smithd9f663b2013-04-22 15:31:51 +00003007 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3008 // Wipe out any partially-computed value, to allow tracking that this
3009 // evaluation failed.
3010 Val = APValue();
3011 return false;
3012 }
3013 }
3014
3015 return true;
3016}
3017
Richard Smith4e18ca52013-05-06 05:56:11 +00003018/// Evaluate a condition (either a variable declaration or an expression).
3019static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3020 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003021 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003022 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3023 return false;
3024 return EvaluateAsBooleanCondition(Cond, Result, Info);
3025}
3026
3027static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003028 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00003029
3030/// Evaluate the body of a loop, and translate the result as appropriate.
3031static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003032 const Stmt *Body,
3033 const SwitchCase *Case = 0) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003034 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003035 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003036 case ESR_Break:
3037 return ESR_Succeeded;
3038 case ESR_Succeeded:
3039 case ESR_Continue:
3040 return ESR_Continue;
3041 case ESR_Failed:
3042 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003043 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003044 return ESR;
3045 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003046 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003047}
3048
Richard Smith496ddcf2013-05-12 17:32:42 +00003049/// Evaluate a switch statement.
3050static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3051 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003052 BlockScopeRAII Scope(Info);
3053
Richard Smith496ddcf2013-05-12 17:32:42 +00003054 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003055 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003056 {
3057 FullExpressionRAII Scope(Info);
3058 if (SS->getConditionVariable() &&
3059 !EvaluateDecl(Info, SS->getConditionVariable()))
3060 return ESR_Failed;
3061 if (!EvaluateInteger(SS->getCond(), Value, Info))
3062 return ESR_Failed;
3063 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003064
3065 // Find the switch case corresponding to the value of the condition.
3066 // FIXME: Cache this lookup.
3067 const SwitchCase *Found = 0;
3068 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3069 SC = SC->getNextSwitchCase()) {
3070 if (isa<DefaultStmt>(SC)) {
3071 Found = SC;
3072 continue;
3073 }
3074
3075 const CaseStmt *CS = cast<CaseStmt>(SC);
3076 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3077 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3078 : LHS;
3079 if (LHS <= Value && Value <= RHS) {
3080 Found = SC;
3081 break;
3082 }
3083 }
3084
3085 if (!Found)
3086 return ESR_Succeeded;
3087
3088 // Search the switch body for the switch case and evaluate it from there.
3089 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3090 case ESR_Break:
3091 return ESR_Succeeded;
3092 case ESR_Succeeded:
3093 case ESR_Continue:
3094 case ESR_Failed:
3095 case ESR_Returned:
3096 return ESR;
3097 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003098 // This can only happen if the switch case is nested within a statement
3099 // expression. We have no intention of supporting that.
3100 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3101 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003102 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003103 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003104}
3105
Richard Smith254a73d2011-10-28 22:34:42 +00003106// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003107static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003108 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003109 if (!Info.nextStep(S))
3110 return ESR_Failed;
3111
Richard Smith496ddcf2013-05-12 17:32:42 +00003112 // If we're hunting down a 'case' or 'default' label, recurse through
3113 // substatements until we hit the label.
3114 if (Case) {
3115 // FIXME: We don't start the lifetime of objects whose initialization we
3116 // jump over. However, such objects must be of class type with a trivial
3117 // default constructor that initialize all subobjects, so must be empty,
3118 // so this almost never matters.
3119 switch (S->getStmtClass()) {
3120 case Stmt::CompoundStmtClass:
3121 // FIXME: Precompute which substatement of a compound statement we
3122 // would jump to, and go straight there rather than performing a
3123 // linear scan each time.
3124 case Stmt::LabelStmtClass:
3125 case Stmt::AttributedStmtClass:
3126 case Stmt::DoStmtClass:
3127 break;
3128
3129 case Stmt::CaseStmtClass:
3130 case Stmt::DefaultStmtClass:
3131 if (Case == S)
3132 Case = 0;
3133 break;
3134
3135 case Stmt::IfStmtClass: {
3136 // FIXME: Precompute which side of an 'if' we would jump to, and go
3137 // straight there rather than scanning both sides.
3138 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003139
3140 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3141 // preceded by our switch label.
3142 BlockScopeRAII Scope(Info);
3143
Richard Smith496ddcf2013-05-12 17:32:42 +00003144 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3145 if (ESR != ESR_CaseNotFound || !IS->getElse())
3146 return ESR;
3147 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3148 }
3149
3150 case Stmt::WhileStmtClass: {
3151 EvalStmtResult ESR =
3152 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3153 if (ESR != ESR_Continue)
3154 return ESR;
3155 break;
3156 }
3157
3158 case Stmt::ForStmtClass: {
3159 const ForStmt *FS = cast<ForStmt>(S);
3160 EvalStmtResult ESR =
3161 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3162 if (ESR != ESR_Continue)
3163 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003164 if (FS->getInc()) {
3165 FullExpressionRAII IncScope(Info);
3166 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3167 return ESR_Failed;
3168 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003169 break;
3170 }
3171
3172 case Stmt::DeclStmtClass:
3173 // FIXME: If the variable has initialization that can't be jumped over,
3174 // bail out of any immediately-surrounding compound-statement too.
3175 default:
3176 return ESR_CaseNotFound;
3177 }
3178 }
3179
Richard Smith254a73d2011-10-28 22:34:42 +00003180 switch (S->getStmtClass()) {
3181 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003182 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003183 // Don't bother evaluating beyond an expression-statement which couldn't
3184 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003185 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003186 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003187 return ESR_Failed;
3188 return ESR_Succeeded;
3189 }
3190
3191 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003192 return ESR_Failed;
3193
3194 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003195 return ESR_Succeeded;
3196
Richard Smithd9f663b2013-04-22 15:31:51 +00003197 case Stmt::DeclStmtClass: {
3198 const DeclStmt *DS = cast<DeclStmt>(S);
3199 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
Richard Smith08d6a2c2013-07-24 07:11:57 +00003200 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3201 // Each declaration initialization is its own full-expression.
3202 // FIXME: This isn't quite right; if we're performing aggregate
3203 // initialization, each braced subexpression is its own full-expression.
3204 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003205 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3206 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003207 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003208 return ESR_Succeeded;
3209 }
3210
Richard Smith357362d2011-12-13 06:39:58 +00003211 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003212 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003213 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003214 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003215 return ESR_Failed;
3216 return ESR_Returned;
3217 }
Richard Smith254a73d2011-10-28 22:34:42 +00003218
3219 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003220 BlockScopeRAII Scope(Info);
3221
Richard Smith254a73d2011-10-28 22:34:42 +00003222 const CompoundStmt *CS = cast<CompoundStmt>(S);
3223 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3224 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00003225 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3226 if (ESR == ESR_Succeeded)
3227 Case = 0;
3228 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003229 return ESR;
3230 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003231 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003232 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003233
3234 case Stmt::IfStmtClass: {
3235 const IfStmt *IS = cast<IfStmt>(S);
3236
3237 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003238 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003239 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003240 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003241 return ESR_Failed;
3242
3243 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3244 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3245 if (ESR != ESR_Succeeded)
3246 return ESR;
3247 }
3248 return ESR_Succeeded;
3249 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003250
3251 case Stmt::WhileStmtClass: {
3252 const WhileStmt *WS = cast<WhileStmt>(S);
3253 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003254 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003255 bool Continue;
3256 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3257 Continue))
3258 return ESR_Failed;
3259 if (!Continue)
3260 break;
3261
3262 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3263 if (ESR != ESR_Continue)
3264 return ESR;
3265 }
3266 return ESR_Succeeded;
3267 }
3268
3269 case Stmt::DoStmtClass: {
3270 const DoStmt *DS = cast<DoStmt>(S);
3271 bool Continue;
3272 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003273 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003274 if (ESR != ESR_Continue)
3275 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003276 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003277
Richard Smith08d6a2c2013-07-24 07:11:57 +00003278 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003279 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3280 return ESR_Failed;
3281 } while (Continue);
3282 return ESR_Succeeded;
3283 }
3284
3285 case Stmt::ForStmtClass: {
3286 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003287 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003288 if (FS->getInit()) {
3289 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3290 if (ESR != ESR_Succeeded)
3291 return ESR;
3292 }
3293 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003294 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003295 bool Continue = true;
3296 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3297 FS->getCond(), Continue))
3298 return ESR_Failed;
3299 if (!Continue)
3300 break;
3301
3302 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3303 if (ESR != ESR_Continue)
3304 return ESR;
3305
Richard Smith08d6a2c2013-07-24 07:11:57 +00003306 if (FS->getInc()) {
3307 FullExpressionRAII IncScope(Info);
3308 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3309 return ESR_Failed;
3310 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003311 }
3312 return ESR_Succeeded;
3313 }
3314
Richard Smith896e0d72013-05-06 06:51:17 +00003315 case Stmt::CXXForRangeStmtClass: {
3316 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003317 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003318
3319 // Initialize the __range variable.
3320 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3321 if (ESR != ESR_Succeeded)
3322 return ESR;
3323
3324 // Create the __begin and __end iterators.
3325 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3326 if (ESR != ESR_Succeeded)
3327 return ESR;
3328
3329 while (true) {
3330 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003331 {
3332 bool Continue = true;
3333 FullExpressionRAII CondExpr(Info);
3334 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3335 return ESR_Failed;
3336 if (!Continue)
3337 break;
3338 }
Richard Smith896e0d72013-05-06 06:51:17 +00003339
3340 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003341 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003342 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3343 if (ESR != ESR_Succeeded)
3344 return ESR;
3345
3346 // Loop body.
3347 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3348 if (ESR != ESR_Continue)
3349 return ESR;
3350
3351 // Increment: ++__begin
3352 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3353 return ESR_Failed;
3354 }
3355
3356 return ESR_Succeeded;
3357 }
3358
Richard Smith496ddcf2013-05-12 17:32:42 +00003359 case Stmt::SwitchStmtClass:
3360 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3361
Richard Smith4e18ca52013-05-06 05:56:11 +00003362 case Stmt::ContinueStmtClass:
3363 return ESR_Continue;
3364
3365 case Stmt::BreakStmtClass:
3366 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003367
3368 case Stmt::LabelStmtClass:
3369 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3370
3371 case Stmt::AttributedStmtClass:
3372 // As a general principle, C++11 attributes can be ignored without
3373 // any semantic impact.
3374 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3375 Case);
3376
3377 case Stmt::CaseStmtClass:
3378 case Stmt::DefaultStmtClass:
3379 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003380 }
3381}
3382
Richard Smithcc36f692011-12-22 02:22:31 +00003383/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3384/// default constructor. If so, we'll fold it whether or not it's marked as
3385/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3386/// so we need special handling.
3387static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003388 const CXXConstructorDecl *CD,
3389 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003390 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3391 return false;
3392
Richard Smith66e05fe2012-01-18 05:21:49 +00003393 // Value-initialization does not call a trivial default constructor, so such a
3394 // call is a core constant expression whether or not the constructor is
3395 // constexpr.
3396 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003397 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003398 // FIXME: If DiagDecl is an implicitly-declared special member function,
3399 // we should be much more explicit about why it's not constexpr.
3400 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3401 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3402 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003403 } else {
3404 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3405 }
3406 }
3407 return true;
3408}
3409
Richard Smith357362d2011-12-13 06:39:58 +00003410/// CheckConstexprFunction - Check that a function can be called in a constant
3411/// expression.
3412static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3413 const FunctionDecl *Declaration,
3414 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003415 // Potential constant expressions can contain calls to declared, but not yet
3416 // defined, constexpr functions.
3417 if (Info.CheckingPotentialConstantExpression && !Definition &&
3418 Declaration->isConstexpr())
3419 return false;
3420
Richard Smith0838f3a2013-05-14 05:18:44 +00003421 // Bail out with no diagnostic if the function declaration itself is invalid.
3422 // We will have produced a relevant diagnostic while parsing it.
3423 if (Declaration->isInvalidDecl())
3424 return false;
3425
Richard Smith357362d2011-12-13 06:39:58 +00003426 // Can we evaluate this function call?
3427 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3428 return true;
3429
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003430 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003431 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003432 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3433 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003434 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3435 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3436 << DiagDecl;
3437 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3438 } else {
3439 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3440 }
3441 return false;
3442}
3443
Richard Smithd62306a2011-11-10 06:34:14 +00003444namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003445typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003446}
3447
3448/// EvaluateArgs - Evaluate the arguments to a function call.
3449static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3450 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003451 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003452 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003453 I != E; ++I) {
3454 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3455 // If we're checking for a potential constant expression, evaluate all
3456 // initializers even if some of them fail.
3457 if (!Info.keepEvaluatingAfterFailure())
3458 return false;
3459 Success = false;
3460 }
3461 }
3462 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003463}
3464
Richard Smith254a73d2011-10-28 22:34:42 +00003465/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003466static bool HandleFunctionCall(SourceLocation CallLoc,
3467 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003468 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003469 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003470 ArgVector ArgValues(Args.size());
3471 if (!EvaluateArgs(Args, ArgValues, Info))
3472 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003473
Richard Smith253c2a32012-01-27 01:14:48 +00003474 if (!Info.CheckCallLimit(CallLoc))
3475 return false;
3476
3477 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003478
3479 // For a trivial copy or move assignment, perform an APValue copy. This is
3480 // essential for unions, where the operations performed by the assignment
3481 // operator cannot be represented as statements.
3482 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3483 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3484 assert(This &&
3485 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3486 LValue RHS;
3487 RHS.setFrom(Info.Ctx, ArgValues[0]);
3488 APValue RHSValue;
3489 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3490 RHS, RHSValue))
3491 return false;
3492 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3493 RHSValue))
3494 return false;
3495 This->moveInto(Result);
3496 return true;
3497 }
3498
Richard Smithd9f663b2013-04-22 15:31:51 +00003499 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003500 if (ESR == ESR_Succeeded) {
3501 if (Callee->getResultType()->isVoidType())
3502 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003503 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003504 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003505 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003506}
3507
Richard Smithd62306a2011-11-10 06:34:14 +00003508/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003509static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003510 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003511 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003512 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003513 ArgVector ArgValues(Args.size());
3514 if (!EvaluateArgs(Args, ArgValues, Info))
3515 return false;
3516
Richard Smith253c2a32012-01-27 01:14:48 +00003517 if (!Info.CheckCallLimit(CallLoc))
3518 return false;
3519
Richard Smith3607ffe2012-02-13 03:54:03 +00003520 const CXXRecordDecl *RD = Definition->getParent();
3521 if (RD->getNumVBases()) {
3522 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3523 return false;
3524 }
3525
Richard Smith253c2a32012-01-27 01:14:48 +00003526 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003527
3528 // If it's a delegating constructor, just delegate.
3529 if (Definition->isDelegatingConstructor()) {
3530 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003531 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3532 return false;
3533 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003534 }
3535
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003536 // For a trivial copy or move constructor, perform an APValue copy. This is
3537 // essential for unions, where the operations performed by the constructor
3538 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003539 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003540 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3541 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003542 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003543 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003544 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003545 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003546 }
3547
3548 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003549 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003550 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3551 std::distance(RD->field_begin(), RD->field_end()));
3552
John McCalld7bca762012-05-01 00:38:49 +00003553 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003554 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3555
Richard Smith08d6a2c2013-07-24 07:11:57 +00003556 // A scope for temporaries lifetime-extended by reference members.
3557 BlockScopeRAII LifetimeExtendedScope(Info);
3558
Richard Smith253c2a32012-01-27 01:14:48 +00003559 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003560 unsigned BasesSeen = 0;
3561#ifndef NDEBUG
3562 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3563#endif
3564 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3565 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003566 LValue Subobject = This;
3567 APValue *Value = &Result;
3568
3569 // Determine the subobject to initialize.
Richard Smith49ca8aa2013-08-06 07:09:20 +00003570 FieldDecl *FD = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00003571 if ((*I)->isBaseInitializer()) {
3572 QualType BaseType((*I)->getBaseClass(), 0);
3573#ifndef NDEBUG
3574 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003575 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003576 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3577 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3578 "base class initializers not in expected order");
3579 ++BaseIt;
3580#endif
John McCalld7bca762012-05-01 00:38:49 +00003581 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3582 BaseType->getAsCXXRecordDecl(), &Layout))
3583 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003584 Value = &Result.getStructBase(BasesSeen++);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003585 } else if ((FD = (*I)->getMember())) {
John McCalld7bca762012-05-01 00:38:49 +00003586 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3587 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003588 if (RD->isUnion()) {
3589 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003590 Value = &Result.getUnionValue();
3591 } else {
3592 Value = &Result.getStructField(FD->getFieldIndex());
3593 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003594 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003595 // Walk the indirect field decl's chain to find the object to initialize,
3596 // and make sure we've initialized every step along it.
3597 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3598 CE = IFD->chain_end();
3599 C != CE; ++C) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003600 FD = cast<FieldDecl>(*C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003601 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3602 // Switch the union field if it differs. This happens if we had
3603 // preceding zero-initialization, and we're now initializing a union
3604 // subobject other than the first.
3605 // FIXME: In this case, the values of the other subobjects are
3606 // specified, since zero-initialization sets all padding bits to zero.
3607 if (Value->isUninit() ||
3608 (Value->isUnion() && Value->getUnionField() != FD)) {
3609 if (CD->isUnion())
3610 *Value = APValue(FD);
3611 else
3612 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3613 std::distance(CD->field_begin(), CD->field_end()));
3614 }
John McCalld7bca762012-05-01 00:38:49 +00003615 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3616 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003617 if (CD->isUnion())
3618 Value = &Value->getUnionValue();
3619 else
3620 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003621 }
Richard Smithd62306a2011-11-10 06:34:14 +00003622 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003623 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003624 }
Richard Smith253c2a32012-01-27 01:14:48 +00003625
Richard Smith08d6a2c2013-07-24 07:11:57 +00003626 FullExpressionRAII InitScope(Info);
Richard Smith49ca8aa2013-08-06 07:09:20 +00003627 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3628 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3629 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003630 // If we're checking for a potential constant expression, evaluate all
3631 // initializers even if some of them fail.
3632 if (!Info.keepEvaluatingAfterFailure())
3633 return false;
3634 Success = false;
3635 }
Richard Smithd62306a2011-11-10 06:34:14 +00003636 }
3637
Richard Smithd9f663b2013-04-22 15:31:51 +00003638 return Success &&
3639 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003640}
3641
Eli Friedman9a156e52008-11-12 09:44:48 +00003642//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003643// Generic Evaluation
3644//===----------------------------------------------------------------------===//
3645namespace {
3646
Richard Smithf57d8cb2011-12-09 22:58:01 +00003647// FIXME: RetTy is always bool. Remove it.
3648template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003649class ExprEvaluatorBase
3650 : public ConstStmtVisitor<Derived, RetTy> {
3651private:
Richard Smith2e312c82012-03-03 22:46:17 +00003652 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003653 return static_cast<Derived*>(this)->Success(V, E);
3654 }
Richard Smithfddd3842011-12-30 21:15:51 +00003655 RetTy DerivedZeroInitialization(const Expr *E) {
3656 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003657 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003658
Richard Smith17100ba2012-02-16 02:46:34 +00003659 // Check whether a conditional operator with a non-constant condition is a
3660 // potential constant expression. If neither arm is a potential constant
3661 // expression, then the conditional operator is not either.
3662 template<typename ConditionalOperator>
3663 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3664 assert(Info.CheckingPotentialConstantExpression);
3665
3666 // Speculatively evaluate both arms.
3667 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003668 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003669 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3670
3671 StmtVisitorTy::Visit(E->getFalseExpr());
3672 if (Diag.empty())
3673 return;
3674
3675 Diag.clear();
3676 StmtVisitorTy::Visit(E->getTrueExpr());
3677 if (Diag.empty())
3678 return;
3679 }
3680
3681 Error(E, diag::note_constexpr_conditional_never_const);
3682 }
3683
3684
3685 template<typename ConditionalOperator>
3686 bool HandleConditionalOperator(const ConditionalOperator *E) {
3687 bool BoolResult;
3688 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3689 if (Info.CheckingPotentialConstantExpression)
3690 CheckPotentialConstantConditional(E);
3691 return false;
3692 }
3693
3694 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3695 return StmtVisitorTy::Visit(EvalExpr);
3696 }
3697
Peter Collingbournee9200682011-05-13 03:29:01 +00003698protected:
3699 EvalInfo &Info;
3700 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3701 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3702
Richard Smith92b1ce02011-12-12 09:28:41 +00003703 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003704 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003705 }
3706
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003707 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3708
3709public:
3710 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3711
3712 EvalInfo &getEvalInfo() { return Info; }
3713
Richard Smithf57d8cb2011-12-09 22:58:01 +00003714 /// Report an evaluation error. This should only be called when an error is
3715 /// first discovered. When propagating an error, just return false.
3716 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003717 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003718 return false;
3719 }
3720 bool Error(const Expr *E) {
3721 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3722 }
3723
Peter Collingbournee9200682011-05-13 03:29:01 +00003724 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003725 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003726 }
3727 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003728 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003729 }
3730
3731 RetTy VisitParenExpr(const ParenExpr *E)
3732 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3733 RetTy VisitUnaryExtension(const UnaryOperator *E)
3734 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3735 RetTy VisitUnaryPlus(const UnaryOperator *E)
3736 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3737 RetTy VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003738 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003739 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3740 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003741 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3742 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003743 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3744 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003745 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3746 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003747 // We cannot create any objects for which cleanups are required, so there is
3748 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3749 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3750 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003751
Richard Smith6d6ecc32011-12-12 12:46:16 +00003752 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3753 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3754 return static_cast<Derived*>(this)->VisitCastExpr(E);
3755 }
3756 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3757 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3758 return static_cast<Derived*>(this)->VisitCastExpr(E);
3759 }
3760
Richard Smith027bf112011-11-17 22:56:20 +00003761 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3762 switch (E->getOpcode()) {
3763 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003764 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003765
3766 case BO_Comma:
3767 VisitIgnoredValue(E->getLHS());
3768 return StmtVisitorTy::Visit(E->getRHS());
3769
3770 case BO_PtrMemD:
3771 case BO_PtrMemI: {
3772 LValue Obj;
3773 if (!HandleMemberPointerAccess(Info, E, Obj))
3774 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003775 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003776 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003777 return false;
3778 return DerivedSuccess(Result, E);
3779 }
3780 }
3781 }
3782
Peter Collingbournee9200682011-05-13 03:29:01 +00003783 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003784 // Evaluate and cache the common expression. We treat it as a temporary,
3785 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003786 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00003787 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003788 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003789
Richard Smith17100ba2012-02-16 02:46:34 +00003790 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003791 }
3792
3793 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003794 bool IsBcpCall = false;
3795 // If the condition (ignoring parens) is a __builtin_constant_p call,
3796 // the result is a constant expression if it can be folded without
3797 // side-effects. This is an important GNU extension. See GCC PR38377
3798 // for discussion.
3799 if (const CallExpr *CallCE =
3800 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3801 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3802 IsBcpCall = true;
3803
3804 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3805 // constant expression; we can't check whether it's potentially foldable.
3806 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3807 return false;
3808
3809 FoldConstant Fold(Info);
3810
Richard Smith17100ba2012-02-16 02:46:34 +00003811 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003812 return false;
3813
3814 if (IsBcpCall)
3815 Fold.Fold(Info);
3816
3817 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003818 }
3819
3820 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003821 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3822 return DerivedSuccess(*Value, E);
3823
3824 const Expr *Source = E->getSourceExpr();
3825 if (!Source)
3826 return Error(E);
3827 if (Source == E) { // sanity checking.
3828 assert(0 && "OpaqueValueExpr recursively refers to itself");
3829 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003830 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003831 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00003832 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003833
Richard Smith254a73d2011-10-28 22:34:42 +00003834 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003835 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003836 QualType CalleeType = Callee->getType();
3837
Richard Smith254a73d2011-10-28 22:34:42 +00003838 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003839 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003840 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003841 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003842
Richard Smithe97cbd72011-11-11 04:05:33 +00003843 // Extract function decl and 'this' pointer from the callee.
3844 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003845 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003846 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3847 // Explicit bound member calls, such as x.f() or p->g();
3848 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003849 return false;
3850 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003851 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003852 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003853 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3854 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003855 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3856 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003857 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003858 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003859 return Error(Callee);
3860
3861 FD = dyn_cast<FunctionDecl>(Member);
3862 if (!FD)
3863 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003864 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003865 LValue Call;
3866 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003867 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003868
Richard Smitha8105bc2012-01-06 16:39:00 +00003869 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003870 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003871 FD = dyn_cast_or_null<FunctionDecl>(
3872 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003873 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003874 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003875
3876 // Overloaded operator calls to member functions are represented as normal
3877 // calls with '*this' as the first argument.
3878 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3879 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003880 // FIXME: When selecting an implicit conversion for an overloaded
3881 // operator delete, we sometimes try to evaluate calls to conversion
3882 // operators without a 'this' parameter!
3883 if (Args.empty())
3884 return Error(E);
3885
Richard Smithe97cbd72011-11-11 04:05:33 +00003886 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3887 return false;
3888 This = &ThisVal;
3889 Args = Args.slice(1);
3890 }
3891
3892 // Don't call function pointers which have been cast to some other type.
3893 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003894 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003895 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003896 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003897
Richard Smith47b34932012-02-01 02:39:43 +00003898 if (This && !This->checkSubobject(Info, E, CSK_This))
3899 return false;
3900
Richard Smith3607ffe2012-02-13 03:54:03 +00003901 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3902 // calls to such functions in constant expressions.
3903 if (This && !HasQualifier &&
3904 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3905 return Error(E, diag::note_constexpr_virtual_call);
3906
Richard Smith357362d2011-12-13 06:39:58 +00003907 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003908 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003909 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003910
Richard Smith357362d2011-12-13 06:39:58 +00003911 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003912 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3913 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003914 return false;
3915
Richard Smithb228a862012-02-15 02:18:13 +00003916 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003917 }
3918
Richard Smith11562c52011-10-28 17:51:58 +00003919 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3920 return StmtVisitorTy::Visit(E->getInitializer());
3921 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003922 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003923 if (E->getNumInits() == 0)
3924 return DerivedZeroInitialization(E);
3925 if (E->getNumInits() == 1)
3926 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003927 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003928 }
3929 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003930 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003931 }
3932 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003933 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003934 }
Richard Smith027bf112011-11-17 22:56:20 +00003935 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003936 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003937 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003938
Richard Smithd62306a2011-11-10 06:34:14 +00003939 /// A member expression where the object is a prvalue is itself a prvalue.
3940 RetTy VisitMemberExpr(const MemberExpr *E) {
3941 assert(!E->isArrow() && "missing call to bound member function?");
3942
Richard Smith2e312c82012-03-03 22:46:17 +00003943 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003944 if (!Evaluate(Val, Info, E->getBase()))
3945 return false;
3946
3947 QualType BaseTy = E->getBase()->getType();
3948
3949 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003950 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003951 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003952 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003953 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3954
Richard Smith3229b742013-05-05 21:17:10 +00003955 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003956 SubobjectDesignator Designator(BaseTy);
3957 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003958
Richard Smith3229b742013-05-05 21:17:10 +00003959 APValue Result;
3960 return extractSubobject(Info, E, Obj, Designator, Result) &&
3961 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003962 }
3963
Richard Smith11562c52011-10-28 17:51:58 +00003964 RetTy VisitCastExpr(const CastExpr *E) {
3965 switch (E->getCastKind()) {
3966 default:
3967 break;
3968
Richard Smitha23ab512013-05-23 00:30:41 +00003969 case CK_AtomicToNonAtomic: {
3970 APValue AtomicVal;
3971 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
3972 return false;
3973 return DerivedSuccess(AtomicVal, E);
3974 }
3975
Richard Smith11562c52011-10-28 17:51:58 +00003976 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003977 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003978 return StmtVisitorTy::Visit(E->getSubExpr());
3979
3980 case CK_LValueToRValue: {
3981 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003982 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3983 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003984 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003985 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003986 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003987 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003988 return false;
3989 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003990 }
3991 }
3992
Richard Smithf57d8cb2011-12-09 22:58:01 +00003993 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003994 }
3995
Richard Smith243ef902013-05-05 23:31:59 +00003996 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3997 return VisitUnaryPostIncDec(UO);
3998 }
3999 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4000 return VisitUnaryPostIncDec(UO);
4001 }
4002 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4003 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4004 return Error(UO);
4005
4006 LValue LVal;
4007 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4008 return false;
4009 APValue RVal;
4010 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4011 UO->isIncrementOp(), &RVal))
4012 return false;
4013 return DerivedSuccess(RVal, UO);
4014 }
4015
Richard Smith51f03172013-06-20 03:00:05 +00004016 RetTy VisitStmtExpr(const StmtExpr *E) {
4017 // We will have checked the full-expressions inside the statement expression
4018 // when they were completed, and don't need to check them again now.
4019 if (Info.getIntOverflowCheckMode())
4020 return Error(E);
4021
Richard Smith08d6a2c2013-07-24 07:11:57 +00004022 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004023 const CompoundStmt *CS = E->getSubStmt();
4024 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4025 BE = CS->body_end();
4026 /**/; ++BI) {
4027 if (BI + 1 == BE) {
4028 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4029 if (!FinalExpr) {
4030 Info.Diag((*BI)->getLocStart(),
4031 diag::note_constexpr_stmt_expr_unsupported);
4032 return false;
4033 }
4034 return this->Visit(FinalExpr);
4035 }
4036
4037 APValue ReturnValue;
4038 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4039 if (ESR != ESR_Succeeded) {
4040 // FIXME: If the statement-expression terminated due to 'return',
4041 // 'break', or 'continue', it would be nice to propagate that to
4042 // the outer statement evaluation rather than bailing out.
4043 if (ESR != ESR_Failed)
4044 Info.Diag((*BI)->getLocStart(),
4045 diag::note_constexpr_stmt_expr_unsupported);
4046 return false;
4047 }
4048 }
4049 }
4050
Richard Smith4a678122011-10-24 18:44:57 +00004051 /// Visit a value which is evaluated, but whose value is ignored.
4052 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004053 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004054 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004055};
4056
4057}
4058
4059//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004060// Common base class for lvalue and temporary evaluation.
4061//===----------------------------------------------------------------------===//
4062namespace {
4063template<class Derived>
4064class LValueExprEvaluatorBase
4065 : public ExprEvaluatorBase<Derived, bool> {
4066protected:
4067 LValue &Result;
4068 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4069 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4070
4071 bool Success(APValue::LValueBase B) {
4072 Result.set(B);
4073 return true;
4074 }
4075
4076public:
4077 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4078 ExprEvaluatorBaseTy(Info), Result(Result) {}
4079
Richard Smith2e312c82012-03-03 22:46:17 +00004080 bool Success(const APValue &V, const Expr *E) {
4081 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004082 return true;
4083 }
Richard Smith027bf112011-11-17 22:56:20 +00004084
Richard Smith027bf112011-11-17 22:56:20 +00004085 bool VisitMemberExpr(const MemberExpr *E) {
4086 // Handle non-static data members.
4087 QualType BaseTy;
4088 if (E->isArrow()) {
4089 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4090 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004091 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004092 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004093 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004094 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4095 return false;
4096 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004097 } else {
4098 if (!this->Visit(E->getBase()))
4099 return false;
4100 BaseTy = E->getBase()->getType();
4101 }
Richard Smith027bf112011-11-17 22:56:20 +00004102
Richard Smith1b78b3d2012-01-25 22:15:11 +00004103 const ValueDecl *MD = E->getMemberDecl();
4104 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4105 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4106 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4107 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004108 if (!HandleLValueMember(this->Info, E, Result, FD))
4109 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004110 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004111 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4112 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004113 } else
4114 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004115
Richard Smith1b78b3d2012-01-25 22:15:11 +00004116 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004117 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004118 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004119 RefValue))
4120 return false;
4121 return Success(RefValue, E);
4122 }
4123 return true;
4124 }
4125
4126 bool VisitBinaryOperator(const BinaryOperator *E) {
4127 switch (E->getOpcode()) {
4128 default:
4129 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4130
4131 case BO_PtrMemD:
4132 case BO_PtrMemI:
4133 return HandleMemberPointerAccess(this->Info, E, Result);
4134 }
4135 }
4136
4137 bool VisitCastExpr(const CastExpr *E) {
4138 switch (E->getCastKind()) {
4139 default:
4140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4141
4142 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004143 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004144 if (!this->Visit(E->getSubExpr()))
4145 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004146
4147 // Now figure out the necessary offset to add to the base LV to get from
4148 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004149 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4150 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004151 }
4152 }
4153};
4154}
4155
4156//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004157// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004158//
4159// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4160// function designators (in C), decl references to void objects (in C), and
4161// temporaries (if building with -Wno-address-of-temporary).
4162//
4163// LValue evaluation produces values comprising a base expression of one of the
4164// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004165// - Declarations
4166// * VarDecl
4167// * FunctionDecl
4168// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004169// * CompoundLiteralExpr in C
4170// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004171// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004172// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004173// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004174// * ObjCEncodeExpr
4175// * AddrLabelExpr
4176// * BlockExpr
4177// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004178// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004179// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004180// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004181// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4182// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004183// * A MaterializeTemporaryExpr that has static storage duration, with no
4184// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004185// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004186//===----------------------------------------------------------------------===//
4187namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004188class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004189 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004190public:
Richard Smith027bf112011-11-17 22:56:20 +00004191 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4192 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004193
Richard Smith11562c52011-10-28 17:51:58 +00004194 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004195 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004196
Peter Collingbournee9200682011-05-13 03:29:01 +00004197 bool VisitDeclRefExpr(const DeclRefExpr *E);
4198 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004199 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004200 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4201 bool VisitMemberExpr(const MemberExpr *E);
4202 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4203 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004204 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004205 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004206 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4207 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004208 bool VisitUnaryReal(const UnaryOperator *E);
4209 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004210 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4211 return VisitUnaryPreIncDec(UO);
4212 }
4213 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4214 return VisitUnaryPreIncDec(UO);
4215 }
Richard Smith3229b742013-05-05 21:17:10 +00004216 bool VisitBinAssign(const BinaryOperator *BO);
4217 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004218
Peter Collingbournee9200682011-05-13 03:29:01 +00004219 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004220 switch (E->getCastKind()) {
4221 default:
Richard Smith027bf112011-11-17 22:56:20 +00004222 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004223
Eli Friedmance3e02a2011-10-11 00:13:24 +00004224 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004225 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004226 if (!Visit(E->getSubExpr()))
4227 return false;
4228 Result.Designator.setInvalid();
4229 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004230
Richard Smith027bf112011-11-17 22:56:20 +00004231 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004232 if (!Visit(E->getSubExpr()))
4233 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004234 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004235 }
4236 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004237};
4238} // end anonymous namespace
4239
Richard Smith11562c52011-10-28 17:51:58 +00004240/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004241/// expressions which are not glvalues, in two cases:
4242/// * function designators in C, and
4243/// * "extern void" objects
4244static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4245 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4246 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004247 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004248}
4249
Peter Collingbournee9200682011-05-13 03:29:01 +00004250bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4252 return Success(FD);
4253 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004254 return VisitVarDecl(E, VD);
4255 return Error(E);
4256}
Richard Smith733237d2011-10-24 23:14:33 +00004257
Richard Smith11562c52011-10-28 17:51:58 +00004258bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00004259 CallStackFrame *Frame = 0;
4260 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4261 Frame = Info.CurrentCall;
4262
Richard Smithfec09922011-11-01 16:57:24 +00004263 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004264 if (Frame) {
4265 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004266 return true;
4267 }
Richard Smithce40ad62011-11-12 22:28:03 +00004268 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004269 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004270
Richard Smith3229b742013-05-05 21:17:10 +00004271 APValue *V;
4272 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004273 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004274 if (V->isUninit()) {
4275 if (!Info.CheckingPotentialConstantExpression)
4276 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4277 return false;
4278 }
Richard Smith3229b742013-05-05 21:17:10 +00004279 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004280}
4281
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004282bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4283 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004284 // Walk through the expression to find the materialized temporary itself.
4285 SmallVector<const Expr *, 2> CommaLHSs;
4286 SmallVector<SubobjectAdjustment, 2> Adjustments;
4287 const Expr *Inner = E->GetTemporaryExpr()->
4288 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004289
Richard Smith84401042013-06-03 05:03:02 +00004290 // If we passed any comma operators, evaluate their LHSs.
4291 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4292 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4293 return false;
4294
Richard Smithe6c01442013-06-05 00:46:14 +00004295 // A materialized temporary with static storage duration can appear within the
4296 // result of a constant expression evaluation, so we need to preserve its
4297 // value for use outside this evaluation.
4298 APValue *Value;
4299 if (E->getStorageDuration() == SD_Static) {
4300 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004301 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004302 Result.set(E);
4303 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004304 Value = &Info.CurrentCall->
4305 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004306 Result.set(E, Info.CurrentCall->Index);
4307 }
4308
Richard Smithea4ad5d2013-06-06 08:19:16 +00004309 QualType Type = Inner->getType();
4310
Richard Smith84401042013-06-03 05:03:02 +00004311 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004312 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4313 (E->getStorageDuration() == SD_Static &&
4314 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4315 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004316 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004317 }
Richard Smith84401042013-06-03 05:03:02 +00004318
4319 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004320 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4321 --I;
4322 switch (Adjustments[I].Kind) {
4323 case SubobjectAdjustment::DerivedToBaseAdjustment:
4324 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4325 Type, Result))
4326 return false;
4327 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4328 break;
4329
4330 case SubobjectAdjustment::FieldAdjustment:
4331 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4332 return false;
4333 Type = Adjustments[I].Field->getType();
4334 break;
4335
4336 case SubobjectAdjustment::MemberPointerAdjustment:
4337 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4338 Adjustments[I].Ptr.RHS))
4339 return false;
4340 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4341 break;
4342 }
4343 }
4344
4345 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004346}
4347
Peter Collingbournee9200682011-05-13 03:29:01 +00004348bool
4349LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004350 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4351 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4352 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004353 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004354}
4355
Richard Smith6e525142011-12-27 12:18:28 +00004356bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004357 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004358 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004359
4360 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4361 << E->getExprOperand()->getType()
4362 << E->getExprOperand()->getSourceRange();
4363 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004364}
4365
Francois Pichet0066db92012-04-16 04:08:35 +00004366bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4367 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004368}
Francois Pichet0066db92012-04-16 04:08:35 +00004369
Peter Collingbournee9200682011-05-13 03:29:01 +00004370bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004371 // Handle static data members.
4372 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4373 VisitIgnoredValue(E->getBase());
4374 return VisitVarDecl(E, VD);
4375 }
4376
Richard Smith254a73d2011-10-28 22:34:42 +00004377 // Handle static member functions.
4378 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4379 if (MD->isStatic()) {
4380 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004381 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004382 }
4383 }
4384
Richard Smithd62306a2011-11-10 06:34:14 +00004385 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004386 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004387}
4388
Peter Collingbournee9200682011-05-13 03:29:01 +00004389bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004390 // FIXME: Deal with vectors as array subscript bases.
4391 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004392 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004393
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004394 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004395 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004396
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004397 APSInt Index;
4398 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004399 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004400
Richard Smith861b5b52013-05-07 23:34:45 +00004401 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4402 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004403}
Eli Friedman9a156e52008-11-12 09:44:48 +00004404
Peter Collingbournee9200682011-05-13 03:29:01 +00004405bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004406 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004407}
4408
Richard Smith66c96992012-02-18 22:04:06 +00004409bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4410 if (!Visit(E->getSubExpr()))
4411 return false;
4412 // __real is a no-op on scalar lvalues.
4413 if (E->getSubExpr()->getType()->isAnyComplexType())
4414 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4415 return true;
4416}
4417
4418bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4419 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4420 "lvalue __imag__ on scalar?");
4421 if (!Visit(E->getSubExpr()))
4422 return false;
4423 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4424 return true;
4425}
4426
Richard Smith243ef902013-05-05 23:31:59 +00004427bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4428 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004429 return Error(UO);
4430
4431 if (!this->Visit(UO->getSubExpr()))
4432 return false;
4433
Richard Smith243ef902013-05-05 23:31:59 +00004434 return handleIncDec(
4435 this->Info, UO, Result, UO->getSubExpr()->getType(),
4436 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004437}
4438
4439bool LValueExprEvaluator::VisitCompoundAssignOperator(
4440 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004441 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004442 return Error(CAO);
4443
Richard Smith3229b742013-05-05 21:17:10 +00004444 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004445
4446 // The overall lvalue result is the result of evaluating the LHS.
4447 if (!this->Visit(CAO->getLHS())) {
4448 if (Info.keepEvaluatingAfterFailure())
4449 Evaluate(RHS, this->Info, CAO->getRHS());
4450 return false;
4451 }
4452
Richard Smith3229b742013-05-05 21:17:10 +00004453 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4454 return false;
4455
Richard Smith43e77732013-05-07 04:50:00 +00004456 return handleCompoundAssignment(
4457 this->Info, CAO,
4458 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4459 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004460}
4461
4462bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004463 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4464 return Error(E);
4465
Richard Smith3229b742013-05-05 21:17:10 +00004466 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004467
4468 if (!this->Visit(E->getLHS())) {
4469 if (Info.keepEvaluatingAfterFailure())
4470 Evaluate(NewVal, this->Info, E->getRHS());
4471 return false;
4472 }
4473
Richard Smith3229b742013-05-05 21:17:10 +00004474 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4475 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004476
4477 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004478 NewVal);
4479}
4480
Eli Friedman9a156e52008-11-12 09:44:48 +00004481//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004482// Pointer Evaluation
4483//===----------------------------------------------------------------------===//
4484
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004485namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004486class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004487 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004488 LValue &Result;
4489
Peter Collingbournee9200682011-05-13 03:29:01 +00004490 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004491 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004492 return true;
4493 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004494public:
Mike Stump11289f42009-09-09 15:08:12 +00004495
John McCall45d55e42010-05-07 21:00:08 +00004496 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004497 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004498
Richard Smith2e312c82012-03-03 22:46:17 +00004499 bool Success(const APValue &V, const Expr *E) {
4500 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004501 return true;
4502 }
Richard Smithfddd3842011-12-30 21:15:51 +00004503 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004504 return Success((Expr*)0);
4505 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004506
John McCall45d55e42010-05-07 21:00:08 +00004507 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004508 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004509 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004510 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004511 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004512 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004513 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004514 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004515 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004516 bool VisitCallExpr(const CallExpr *E);
4517 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004518 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004519 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004520 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004521 }
Richard Smithd62306a2011-11-10 06:34:14 +00004522 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004523 // Can't look at 'this' when checking a potential constant expression.
4524 if (Info.CheckingPotentialConstantExpression)
4525 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004526 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004527 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004528 Result = *Info.CurrentCall->This;
4529 return true;
4530 }
John McCallc07a0c72011-02-17 10:25:35 +00004531
Eli Friedman449fe542009-03-23 04:56:01 +00004532 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004533};
Chris Lattner05706e882008-07-11 18:11:29 +00004534} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004535
John McCall45d55e42010-05-07 21:00:08 +00004536static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004537 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004538 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004539}
4540
John McCall45d55e42010-05-07 21:00:08 +00004541bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004542 if (E->getOpcode() != BO_Add &&
4543 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004544 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004545
Chris Lattner05706e882008-07-11 18:11:29 +00004546 const Expr *PExp = E->getLHS();
4547 const Expr *IExp = E->getRHS();
4548 if (IExp->getType()->isPointerType())
4549 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004550
Richard Smith253c2a32012-01-27 01:14:48 +00004551 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4552 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004553 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004554
John McCall45d55e42010-05-07 21:00:08 +00004555 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004556 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004557 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004558
4559 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004560 if (E->getOpcode() == BO_Sub)
4561 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004562
Ted Kremenek28831752012-08-23 20:46:57 +00004563 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004564 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4565 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004566}
Eli Friedman9a156e52008-11-12 09:44:48 +00004567
John McCall45d55e42010-05-07 21:00:08 +00004568bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4569 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004570}
Mike Stump11289f42009-09-09 15:08:12 +00004571
Peter Collingbournee9200682011-05-13 03:29:01 +00004572bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4573 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004574
Eli Friedman847a2bc2009-12-27 05:43:15 +00004575 switch (E->getCastKind()) {
4576 default:
4577 break;
4578
John McCalle3027922010-08-25 11:45:40 +00004579 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004580 case CK_CPointerToObjCPointerCast:
4581 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004582 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004583 if (!Visit(SubExpr))
4584 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004585 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4586 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4587 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004588 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004589 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004590 if (SubExpr->getType()->isVoidPointerType())
4591 CCEDiag(E, diag::note_constexpr_invalid_cast)
4592 << 3 << SubExpr->getType();
4593 else
4594 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4595 }
Richard Smith96e0c102011-11-04 02:25:55 +00004596 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004597
Anders Carlsson18275092010-10-31 20:41:46 +00004598 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004599 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004600 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004601 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004602 if (!Result.Base && Result.Offset.isZero())
4603 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004604
Richard Smithd62306a2011-11-10 06:34:14 +00004605 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004606 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004607 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4608 castAs<PointerType>()->getPointeeType(),
4609 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004610
Richard Smith027bf112011-11-17 22:56:20 +00004611 case CK_BaseToDerived:
4612 if (!Visit(E->getSubExpr()))
4613 return false;
4614 if (!Result.Base && Result.Offset.isZero())
4615 return true;
4616 return HandleBaseToDerivedCast(Info, E, Result);
4617
Richard Smith0b0a0b62011-10-29 20:57:55 +00004618 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004619 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004620 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004621
John McCalle3027922010-08-25 11:45:40 +00004622 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004623 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4624
Richard Smith2e312c82012-03-03 22:46:17 +00004625 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004626 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004627 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004628
John McCall45d55e42010-05-07 21:00:08 +00004629 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004630 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4631 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004632 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004633 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004634 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004635 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004636 return true;
4637 } else {
4638 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004639 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004640 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004641 }
4642 }
John McCalle3027922010-08-25 11:45:40 +00004643 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004644 if (SubExpr->isGLValue()) {
4645 if (!EvaluateLValue(SubExpr, Result, Info))
4646 return false;
4647 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004648 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004649 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004650 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004651 return false;
4652 }
Richard Smith96e0c102011-11-04 02:25:55 +00004653 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004654 if (const ConstantArrayType *CAT
4655 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4656 Result.addArray(Info, E, CAT);
4657 else
4658 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004659 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004660
John McCalle3027922010-08-25 11:45:40 +00004661 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004662 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004663 }
4664
Richard Smith11562c52011-10-28 17:51:58 +00004665 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004666}
Chris Lattner05706e882008-07-11 18:11:29 +00004667
Peter Collingbournee9200682011-05-13 03:29:01 +00004668bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004669 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004670 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004671
Richard Smith6cbd65d2013-07-11 02:27:57 +00004672 switch (E->isBuiltinCall()) {
4673 case Builtin::BI__builtin_addressof:
4674 return EvaluateLValue(E->getArg(0), Result, Info);
4675
4676 default:
4677 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4678 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004679}
Chris Lattner05706e882008-07-11 18:11:29 +00004680
4681//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004682// Member Pointer Evaluation
4683//===----------------------------------------------------------------------===//
4684
4685namespace {
4686class MemberPointerExprEvaluator
4687 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4688 MemberPtr &Result;
4689
4690 bool Success(const ValueDecl *D) {
4691 Result = MemberPtr(D);
4692 return true;
4693 }
4694public:
4695
4696 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4697 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4698
Richard Smith2e312c82012-03-03 22:46:17 +00004699 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004700 Result.setFrom(V);
4701 return true;
4702 }
Richard Smithfddd3842011-12-30 21:15:51 +00004703 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004704 return Success((const ValueDecl*)0);
4705 }
4706
4707 bool VisitCastExpr(const CastExpr *E);
4708 bool VisitUnaryAddrOf(const UnaryOperator *E);
4709};
4710} // end anonymous namespace
4711
4712static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4713 EvalInfo &Info) {
4714 assert(E->isRValue() && E->getType()->isMemberPointerType());
4715 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4716}
4717
4718bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4719 switch (E->getCastKind()) {
4720 default:
4721 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4722
4723 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004724 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004725 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004726
4727 case CK_BaseToDerivedMemberPointer: {
4728 if (!Visit(E->getSubExpr()))
4729 return false;
4730 if (E->path_empty())
4731 return true;
4732 // Base-to-derived member pointer casts store the path in derived-to-base
4733 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4734 // the wrong end of the derived->base arc, so stagger the path by one class.
4735 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4736 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4737 PathI != PathE; ++PathI) {
4738 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4739 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4740 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004741 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004742 }
4743 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4744 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004746 return true;
4747 }
4748
4749 case CK_DerivedToBaseMemberPointer:
4750 if (!Visit(E->getSubExpr()))
4751 return false;
4752 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4753 PathE = E->path_end(); PathI != PathE; ++PathI) {
4754 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4755 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4756 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004757 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004758 }
4759 return true;
4760 }
4761}
4762
4763bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4764 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4765 // member can be formed.
4766 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4767}
4768
4769//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004770// Record Evaluation
4771//===----------------------------------------------------------------------===//
4772
4773namespace {
4774 class RecordExprEvaluator
4775 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4776 const LValue &This;
4777 APValue &Result;
4778 public:
4779
4780 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4781 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4782
Richard Smith2e312c82012-03-03 22:46:17 +00004783 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004784 Result = V;
4785 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004786 }
Richard Smithfddd3842011-12-30 21:15:51 +00004787 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004788
Richard Smithe97cbd72011-11-11 04:05:33 +00004789 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004790 bool VisitInitListExpr(const InitListExpr *E);
4791 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00004792 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004793 };
4794}
4795
Richard Smithfddd3842011-12-30 21:15:51 +00004796/// Perform zero-initialization on an object of non-union class type.
4797/// C++11 [dcl.init]p5:
4798/// To zero-initialize an object or reference of type T means:
4799/// [...]
4800/// -- if T is a (possibly cv-qualified) non-union class type,
4801/// each non-static data member and each base-class subobject is
4802/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004803static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4804 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004805 const LValue &This, APValue &Result) {
4806 assert(!RD->isUnion() && "Expected non-union class type");
4807 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4808 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4809 std::distance(RD->field_begin(), RD->field_end()));
4810
John McCalld7bca762012-05-01 00:38:49 +00004811 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004812 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4813
4814 if (CD) {
4815 unsigned Index = 0;
4816 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004817 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004818 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4819 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004820 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4821 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004822 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004823 Result.getStructBase(Index)))
4824 return false;
4825 }
4826 }
4827
Richard Smitha8105bc2012-01-06 16:39:00 +00004828 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4829 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004830 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004831 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004832 continue;
4833
4834 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004835 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004836 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004837
David Blaikie2d7c57e2012-04-30 02:36:29 +00004838 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004839 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004840 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004841 return false;
4842 }
4843
4844 return true;
4845}
4846
4847bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4848 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004849 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004850 if (RD->isUnion()) {
4851 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4852 // object's first non-static named data member is zero-initialized
4853 RecordDecl::field_iterator I = RD->field_begin();
4854 if (I == RD->field_end()) {
4855 Result = APValue((const FieldDecl*)0);
4856 return true;
4857 }
4858
4859 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004860 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004861 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004862 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004863 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004864 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004865 }
4866
Richard Smith5d108602012-02-17 00:44:16 +00004867 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004868 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004869 return false;
4870 }
4871
Richard Smitha8105bc2012-01-06 16:39:00 +00004872 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004873}
4874
Richard Smithe97cbd72011-11-11 04:05:33 +00004875bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4876 switch (E->getCastKind()) {
4877 default:
4878 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4879
4880 case CK_ConstructorConversion:
4881 return Visit(E->getSubExpr());
4882
4883 case CK_DerivedToBase:
4884 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004885 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004886 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004887 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004888 if (!DerivedObject.isStruct())
4889 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004890
4891 // Derived-to-base rvalue conversion: just slice off the derived part.
4892 APValue *Value = &DerivedObject;
4893 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4894 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4895 PathE = E->path_end(); PathI != PathE; ++PathI) {
4896 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4897 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4898 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4899 RD = Base;
4900 }
4901 Result = *Value;
4902 return true;
4903 }
4904 }
4905}
4906
Richard Smithd62306a2011-11-10 06:34:14 +00004907bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4908 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004909 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004910 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4911
4912 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004913 const FieldDecl *Field = E->getInitializedFieldInUnion();
4914 Result = APValue(Field);
4915 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004916 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004917
4918 // If the initializer list for a union does not contain any elements, the
4919 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004920 // FIXME: The element should be initialized from an initializer list.
4921 // Is this difference ever observable for initializer lists which
4922 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004923 ImplicitValueInitExpr VIE(Field->getType());
4924 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4925
Richard Smithd62306a2011-11-10 06:34:14 +00004926 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004927 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4928 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004929
4930 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4931 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4932 isa<CXXDefaultInitExpr>(InitExpr));
4933
Richard Smithb228a862012-02-15 02:18:13 +00004934 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004935 }
4936
4937 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4938 "initializer list for class with base classes");
4939 Result = APValue(APValue::UninitStruct(), 0,
4940 std::distance(RD->field_begin(), RD->field_end()));
4941 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004942 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004943 for (RecordDecl::field_iterator Field = RD->field_begin(),
4944 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4945 // Anonymous bit-fields are not considered members of the class for
4946 // purposes of aggregate initialization.
4947 if (Field->isUnnamedBitfield())
4948 continue;
4949
4950 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004951
Richard Smith253c2a32012-01-27 01:14:48 +00004952 bool HaveInit = ElementNo < E->getNumInits();
4953
4954 // FIXME: Diagnostics here should point to the end of the initializer
4955 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004956 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004957 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004958 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004959
4960 // Perform an implicit value-initialization for members beyond the end of
4961 // the initializer list.
4962 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004963 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004964
Richard Smith852c9db2013-04-20 22:23:05 +00004965 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4966 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4967 isa<CXXDefaultInitExpr>(Init));
4968
Richard Smith49ca8aa2013-08-06 07:09:20 +00004969 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
4970 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
4971 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
4972 FieldVal, *Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004973 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004974 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004975 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004976 }
4977 }
4978
Richard Smith253c2a32012-01-27 01:14:48 +00004979 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004980}
4981
4982bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4983 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004984 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4985
Richard Smithfddd3842011-12-30 21:15:51 +00004986 bool ZeroInit = E->requiresZeroInitialization();
4987 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004988 // If we've already performed zero-initialization, we're already done.
4989 if (!Result.isUninit())
4990 return true;
4991
Richard Smithfddd3842011-12-30 21:15:51 +00004992 if (ZeroInit)
4993 return ZeroInitialization(E);
4994
Richard Smithcc36f692011-12-22 02:22:31 +00004995 const CXXRecordDecl *RD = FD->getParent();
4996 if (RD->isUnion())
4997 Result = APValue((FieldDecl*)0);
4998 else
4999 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5000 std::distance(RD->field_begin(), RD->field_end()));
5001 return true;
5002 }
5003
Richard Smithd62306a2011-11-10 06:34:14 +00005004 const FunctionDecl *Definition = 0;
5005 FD->getBody(Definition);
5006
Richard Smith357362d2011-12-13 06:39:58 +00005007 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5008 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005009
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005010 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005011 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005012 if (const MaterializeTemporaryExpr *ME
5013 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5014 return Visit(ME->GetTemporaryExpr());
5015
Richard Smithfddd3842011-12-30 21:15:51 +00005016 if (ZeroInit && !ZeroInitialization(E))
5017 return false;
5018
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005019 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005020 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005021 cast<CXXConstructorDecl>(Definition), Info,
5022 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005023}
5024
Richard Smithcc1b96d2013-06-12 22:31:48 +00005025bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5026 const CXXStdInitializerListExpr *E) {
5027 const ConstantArrayType *ArrayType =
5028 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5029
5030 LValue Array;
5031 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5032 return false;
5033
5034 // Get a pointer to the first element of the array.
5035 Array.addArray(Info, E, ArrayType);
5036
5037 // FIXME: Perform the checks on the field types in SemaInit.
5038 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5039 RecordDecl::field_iterator Field = Record->field_begin();
5040 if (Field == Record->field_end())
5041 return Error(E);
5042
5043 // Start pointer.
5044 if (!Field->getType()->isPointerType() ||
5045 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5046 ArrayType->getElementType()))
5047 return Error(E);
5048
5049 // FIXME: What if the initializer_list type has base classes, etc?
5050 Result = APValue(APValue::UninitStruct(), 0, 2);
5051 Array.moveInto(Result.getStructField(0));
5052
5053 if (++Field == Record->field_end())
5054 return Error(E);
5055
5056 if (Field->getType()->isPointerType() &&
5057 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5058 ArrayType->getElementType())) {
5059 // End pointer.
5060 if (!HandleLValueArrayAdjustment(Info, E, Array,
5061 ArrayType->getElementType(),
5062 ArrayType->getSize().getZExtValue()))
5063 return false;
5064 Array.moveInto(Result.getStructField(1));
5065 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5066 // Length.
5067 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5068 else
5069 return Error(E);
5070
5071 if (++Field != Record->field_end())
5072 return Error(E);
5073
5074 return true;
5075}
5076
Richard Smithd62306a2011-11-10 06:34:14 +00005077static bool EvaluateRecord(const Expr *E, const LValue &This,
5078 APValue &Result, EvalInfo &Info) {
5079 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005080 "can't evaluate expression as a record rvalue");
5081 return RecordExprEvaluator(Info, This, Result).Visit(E);
5082}
5083
5084//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005085// Temporary Evaluation
5086//
5087// Temporaries are represented in the AST as rvalues, but generally behave like
5088// lvalues. The full-object of which the temporary is a subobject is implicitly
5089// materialized so that a reference can bind to it.
5090//===----------------------------------------------------------------------===//
5091namespace {
5092class TemporaryExprEvaluator
5093 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5094public:
5095 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5096 LValueExprEvaluatorBaseTy(Info, Result) {}
5097
5098 /// Visit an expression which constructs the value of this temporary.
5099 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005100 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005101 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5102 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005103 }
5104
5105 bool VisitCastExpr(const CastExpr *E) {
5106 switch (E->getCastKind()) {
5107 default:
5108 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5109
5110 case CK_ConstructorConversion:
5111 return VisitConstructExpr(E->getSubExpr());
5112 }
5113 }
5114 bool VisitInitListExpr(const InitListExpr *E) {
5115 return VisitConstructExpr(E);
5116 }
5117 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5118 return VisitConstructExpr(E);
5119 }
5120 bool VisitCallExpr(const CallExpr *E) {
5121 return VisitConstructExpr(E);
5122 }
5123};
5124} // end anonymous namespace
5125
5126/// Evaluate an expression of record type as a temporary.
5127static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005128 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005129 return TemporaryExprEvaluator(Info, Result).Visit(E);
5130}
5131
5132//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005133// Vector Evaluation
5134//===----------------------------------------------------------------------===//
5135
5136namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005137 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00005138 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5139 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005140 public:
Mike Stump11289f42009-09-09 15:08:12 +00005141
Richard Smith2d406342011-10-22 21:10:00 +00005142 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5143 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005144
Richard Smith2d406342011-10-22 21:10:00 +00005145 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5146 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5147 // FIXME: remove this APValue copy.
5148 Result = APValue(V.data(), V.size());
5149 return true;
5150 }
Richard Smith2e312c82012-03-03 22:46:17 +00005151 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005152 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005153 Result = V;
5154 return true;
5155 }
Richard Smithfddd3842011-12-30 21:15:51 +00005156 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005157
Richard Smith2d406342011-10-22 21:10:00 +00005158 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005159 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005160 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005161 bool VisitInitListExpr(const InitListExpr *E);
5162 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005163 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005164 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005165 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005166 };
5167} // end anonymous namespace
5168
5169static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005170 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005171 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005172}
5173
Richard Smith2d406342011-10-22 21:10:00 +00005174bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5175 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005176 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005177
Richard Smith161f09a2011-12-06 22:44:34 +00005178 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005179 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005180
Eli Friedmanc757de22011-03-25 00:43:55 +00005181 switch (E->getCastKind()) {
5182 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005183 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005184 if (SETy->isIntegerType()) {
5185 APSInt IntResult;
5186 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005187 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005188 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005189 } else if (SETy->isRealFloatingType()) {
5190 APFloat F(0.0);
5191 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005192 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005193 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005194 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005195 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005196 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005197
5198 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005199 SmallVector<APValue, 4> Elts(NElts, Val);
5200 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005201 }
Eli Friedman803acb32011-12-22 03:51:45 +00005202 case CK_BitCast: {
5203 // Evaluate the operand into an APInt we can extract from.
5204 llvm::APInt SValInt;
5205 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5206 return false;
5207 // Extract the elements
5208 QualType EltTy = VTy->getElementType();
5209 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5210 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5211 SmallVector<APValue, 4> Elts;
5212 if (EltTy->isRealFloatingType()) {
5213 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005214 unsigned FloatEltSize = EltSize;
5215 if (&Sem == &APFloat::x87DoubleExtended)
5216 FloatEltSize = 80;
5217 for (unsigned i = 0; i < NElts; i++) {
5218 llvm::APInt Elt;
5219 if (BigEndian)
5220 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5221 else
5222 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005223 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005224 }
5225 } else if (EltTy->isIntegerType()) {
5226 for (unsigned i = 0; i < NElts; i++) {
5227 llvm::APInt Elt;
5228 if (BigEndian)
5229 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5230 else
5231 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5232 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5233 }
5234 } else {
5235 return Error(E);
5236 }
5237 return Success(Elts, E);
5238 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005239 default:
Richard Smith11562c52011-10-28 17:51:58 +00005240 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005241 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005242}
5243
Richard Smith2d406342011-10-22 21:10:00 +00005244bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005245VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005246 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005247 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005248 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005249
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005250 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005251 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005252
Eli Friedmanb9c71292012-01-03 23:24:20 +00005253 // The number of initializers can be less than the number of
5254 // vector elements. For OpenCL, this can be due to nested vector
5255 // initialization. For GCC compatibility, missing trailing elements
5256 // should be initialized with zeroes.
5257 unsigned CountInits = 0, CountElts = 0;
5258 while (CountElts < NumElements) {
5259 // Handle nested vector initialization.
5260 if (CountInits < NumInits
5261 && E->getInit(CountInits)->getType()->isExtVectorType()) {
5262 APValue v;
5263 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5264 return Error(E);
5265 unsigned vlen = v.getVectorLength();
5266 for (unsigned j = 0; j < vlen; j++)
5267 Elements.push_back(v.getVectorElt(j));
5268 CountElts += vlen;
5269 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005270 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005271 if (CountInits < NumInits) {
5272 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005273 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005274 } else // trailing integer zero.
5275 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5276 Elements.push_back(APValue(sInt));
5277 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005278 } else {
5279 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005280 if (CountInits < NumInits) {
5281 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005282 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005283 } else // trailing float zero.
5284 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5285 Elements.push_back(APValue(f));
5286 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005287 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005288 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005289 }
Richard Smith2d406342011-10-22 21:10:00 +00005290 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005291}
5292
Richard Smith2d406342011-10-22 21:10:00 +00005293bool
Richard Smithfddd3842011-12-30 21:15:51 +00005294VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005295 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005296 QualType EltTy = VT->getElementType();
5297 APValue ZeroElement;
5298 if (EltTy->isIntegerType())
5299 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5300 else
5301 ZeroElement =
5302 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5303
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005304 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005305 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005306}
5307
Richard Smith2d406342011-10-22 21:10:00 +00005308bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005309 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005310 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005311}
5312
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005313//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005314// Array Evaluation
5315//===----------------------------------------------------------------------===//
5316
5317namespace {
5318 class ArrayExprEvaluator
5319 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00005320 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005321 APValue &Result;
5322 public:
5323
Richard Smithd62306a2011-11-10 06:34:14 +00005324 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5325 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005326
5327 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005328 assert((V.isArray() || V.isLValue()) &&
5329 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005330 Result = V;
5331 return true;
5332 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005333
Richard Smithfddd3842011-12-30 21:15:51 +00005334 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005335 const ConstantArrayType *CAT =
5336 Info.Ctx.getAsConstantArrayType(E->getType());
5337 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005338 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005339
5340 Result = APValue(APValue::UninitArray(), 0,
5341 CAT->getSize().getZExtValue());
5342 if (!Result.hasArrayFiller()) return true;
5343
Richard Smithfddd3842011-12-30 21:15:51 +00005344 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005345 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005346 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005347 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005348 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005349 }
5350
Richard Smithf3e9e432011-11-07 09:22:26 +00005351 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005352 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005353 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5354 const LValue &Subobject,
5355 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005356 };
5357} // end anonymous namespace
5358
Richard Smithd62306a2011-11-10 06:34:14 +00005359static bool EvaluateArray(const Expr *E, const LValue &This,
5360 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005361 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005362 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005363}
5364
5365bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5366 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5367 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005368 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005369
Richard Smithca2cfbf2011-12-22 01:07:19 +00005370 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5371 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005372 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005373 LValue LV;
5374 if (!EvaluateLValue(E->getInit(0), LV, Info))
5375 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005376 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005377 LV.moveInto(Val);
5378 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005379 }
5380
Richard Smith253c2a32012-01-27 01:14:48 +00005381 bool Success = true;
5382
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005383 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5384 "zero-initialized array shouldn't have any initialized elts");
5385 APValue Filler;
5386 if (Result.isArray() && Result.hasArrayFiller())
5387 Filler = Result.getArrayFiller();
5388
Richard Smith9543c5e2013-04-22 14:44:29 +00005389 unsigned NumEltsToInit = E->getNumInits();
5390 unsigned NumElts = CAT->getSize().getZExtValue();
5391 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5392
5393 // If the initializer might depend on the array index, run it for each
5394 // array element. For now, just whitelist non-class value-initialization.
5395 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5396 NumEltsToInit = NumElts;
5397
5398 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005399
5400 // If the array was previously zero-initialized, preserve the
5401 // zero-initialized values.
5402 if (!Filler.isUninit()) {
5403 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5404 Result.getArrayInitializedElt(I) = Filler;
5405 if (Result.hasArrayFiller())
5406 Result.getArrayFiller() = Filler;
5407 }
5408
Richard Smithd62306a2011-11-10 06:34:14 +00005409 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005410 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005411 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5412 const Expr *Init =
5413 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005414 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005415 Info, Subobject, Init) ||
5416 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005417 CAT->getElementType(), 1)) {
5418 if (!Info.keepEvaluatingAfterFailure())
5419 return false;
5420 Success = false;
5421 }
Richard Smithd62306a2011-11-10 06:34:14 +00005422 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005423
Richard Smith9543c5e2013-04-22 14:44:29 +00005424 if (!Result.hasArrayFiller())
5425 return Success;
5426
5427 // If we get here, we have a trivial filler, which we can just evaluate
5428 // once and splat over the rest of the array elements.
5429 assert(FillerExpr && "no array filler for incomplete init list");
5430 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5431 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005432}
5433
Richard Smith027bf112011-11-17 22:56:20 +00005434bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005435 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5436}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005437
Richard Smith9543c5e2013-04-22 14:44:29 +00005438bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5439 const LValue &Subobject,
5440 APValue *Value,
5441 QualType Type) {
5442 bool HadZeroInit = !Value->isUninit();
5443
5444 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5445 unsigned N = CAT->getSize().getZExtValue();
5446
5447 // Preserve the array filler if we had prior zero-initialization.
5448 APValue Filler =
5449 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5450 : APValue();
5451
5452 *Value = APValue(APValue::UninitArray(), N, N);
5453
5454 if (HadZeroInit)
5455 for (unsigned I = 0; I != N; ++I)
5456 Value->getArrayInitializedElt(I) = Filler;
5457
5458 // Initialize the elements.
5459 LValue ArrayElt = Subobject;
5460 ArrayElt.addArray(Info, E, CAT);
5461 for (unsigned I = 0; I != N; ++I)
5462 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5463 CAT->getElementType()) ||
5464 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5465 CAT->getElementType(), 1))
5466 return false;
5467
5468 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005469 }
Richard Smith027bf112011-11-17 22:56:20 +00005470
Richard Smith9543c5e2013-04-22 14:44:29 +00005471 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005472 return Error(E);
5473
Richard Smith027bf112011-11-17 22:56:20 +00005474 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005475
Richard Smithfddd3842011-12-30 21:15:51 +00005476 bool ZeroInit = E->requiresZeroInitialization();
5477 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005478 if (HadZeroInit)
5479 return true;
5480
Richard Smithfddd3842011-12-30 21:15:51 +00005481 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005482 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005483 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005484 }
5485
Richard Smithcc36f692011-12-22 02:22:31 +00005486 const CXXRecordDecl *RD = FD->getParent();
5487 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005488 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005489 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005490 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005491 APValue(APValue::UninitStruct(), RD->getNumBases(),
5492 std::distance(RD->field_begin(), RD->field_end()));
5493 return true;
5494 }
5495
Richard Smith027bf112011-11-17 22:56:20 +00005496 const FunctionDecl *Definition = 0;
5497 FD->getBody(Definition);
5498
Richard Smith357362d2011-12-13 06:39:58 +00005499 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5500 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005501
Richard Smith9eae7232012-01-12 18:54:33 +00005502 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005503 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005504 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005505 return false;
5506 }
5507
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005508 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005509 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005510 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005511 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005512}
5513
Richard Smithf3e9e432011-11-07 09:22:26 +00005514//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005515// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005516//
5517// As a GNU extension, we support casting pointers to sufficiently-wide integer
5518// types and back in constant folding. Integer values are thus represented
5519// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005520//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005521
5522namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005523class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005524 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005525 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005526public:
Richard Smith2e312c82012-03-03 22:46:17 +00005527 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005528 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005529
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005530 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005531 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005532 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005533 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005534 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005535 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005536 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005537 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005538 return true;
5539 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005540 bool Success(const llvm::APSInt &SI, const Expr *E) {
5541 return Success(SI, E, Result);
5542 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005543
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005544 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005545 assert(E->getType()->isIntegralOrEnumerationType() &&
5546 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005547 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005548 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005549 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005550 Result.getInt().setIsUnsigned(
5551 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005552 return true;
5553 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005554 bool Success(const llvm::APInt &I, const Expr *E) {
5555 return Success(I, E, Result);
5556 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005557
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005558 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005559 assert(E->getType()->isIntegralOrEnumerationType() &&
5560 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005561 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005562 return true;
5563 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005564 bool Success(uint64_t Value, const Expr *E) {
5565 return Success(Value, E, Result);
5566 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005567
Ken Dyckdbc01912011-03-11 02:13:43 +00005568 bool Success(CharUnits Size, const Expr *E) {
5569 return Success(Size.getQuantity(), E);
5570 }
5571
Richard Smith2e312c82012-03-03 22:46:17 +00005572 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005573 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005574 Result = V;
5575 return true;
5576 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005577 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005578 }
Mike Stump11289f42009-09-09 15:08:12 +00005579
Richard Smithfddd3842011-12-30 21:15:51 +00005580 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005581
Peter Collingbournee9200682011-05-13 03:29:01 +00005582 //===--------------------------------------------------------------------===//
5583 // Visitor Methods
5584 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005585
Chris Lattner7174bf32008-07-12 00:38:25 +00005586 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005587 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005588 }
5589 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005590 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005591 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005592
5593 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5594 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005595 if (CheckReferencedDecl(E, E->getDecl()))
5596 return true;
5597
5598 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005599 }
5600 bool VisitMemberExpr(const MemberExpr *E) {
5601 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005602 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005603 return true;
5604 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005605
5606 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005607 }
5608
Peter Collingbournee9200682011-05-13 03:29:01 +00005609 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005610 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005611 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005612 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005613
Peter Collingbournee9200682011-05-13 03:29:01 +00005614 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005615 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005616
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005617 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005618 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
Ted Kremeneke65b0862012-03-06 20:05:56 +00005621 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5622 return Success(E->getValue(), E);
5623 }
5624
Richard Smith4ce706a2011-10-11 21:43:33 +00005625 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005626 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005627 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005628 }
5629
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005630 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005631 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005632 }
5633
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005634 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5635 return Success(E->getValue(), E);
5636 }
5637
Douglas Gregor29c42f22012-02-24 07:38:34 +00005638 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5639 return Success(E->getValue(), E);
5640 }
5641
John Wiegley6242b6a2011-04-28 00:16:57 +00005642 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5643 return Success(E->getValue(), E);
5644 }
5645
John Wiegleyf9f65842011-04-25 06:54:41 +00005646 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5647 return Success(E->getValue(), E);
5648 }
5649
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005650 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005651 bool VisitUnaryImag(const UnaryOperator *E);
5652
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005653 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005654 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005655
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005656private:
Ken Dyck160146e2010-01-27 17:10:57 +00005657 CharUnits GetAlignOfExpr(const Expr *E);
5658 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005659 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005660 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005661 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005662};
Chris Lattner05706e882008-07-11 18:11:29 +00005663} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005664
Richard Smith11562c52011-10-28 17:51:58 +00005665/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5666/// produce either the integer value or a pointer.
5667///
5668/// GCC has a heinous extension which folds casts between pointer types and
5669/// pointer-sized integral types. We support this by allowing the evaluation of
5670/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5671/// Some simple arithmetic on such values is supported (they are treated much
5672/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005673static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005674 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005675 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005676 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005677}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005678
Richard Smithf57d8cb2011-12-09 22:58:01 +00005679static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005680 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005681 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005682 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005683 if (!Val.isInt()) {
5684 // FIXME: It would be better to produce the diagnostic for casting
5685 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005686 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005687 return false;
5688 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005689 Result = Val.getInt();
5690 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005691}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005692
Richard Smithf57d8cb2011-12-09 22:58:01 +00005693/// Check whether the given declaration can be directly converted to an integral
5694/// rvalue. If not, no diagnostic is produced; there are other things we can
5695/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005696bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005697 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005698 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005699 // Check for signedness/width mismatches between E type and ECD value.
5700 bool SameSign = (ECD->getInitVal().isSigned()
5701 == E->getType()->isSignedIntegerOrEnumerationType());
5702 bool SameWidth = (ECD->getInitVal().getBitWidth()
5703 == Info.Ctx.getIntWidth(E->getType()));
5704 if (SameSign && SameWidth)
5705 return Success(ECD->getInitVal(), E);
5706 else {
5707 // Get rid of mismatch (otherwise Success assertions will fail)
5708 // by computing a new value matching the type of E.
5709 llvm::APSInt Val = ECD->getInitVal();
5710 if (!SameSign)
5711 Val.setIsSigned(!ECD->getInitVal().isSigned());
5712 if (!SameWidth)
5713 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5714 return Success(Val, E);
5715 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005716 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005717 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005718}
5719
Chris Lattner86ee2862008-10-06 06:40:35 +00005720/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5721/// as GCC.
5722static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5723 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005724 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005725 enum gcc_type_class {
5726 no_type_class = -1,
5727 void_type_class, integer_type_class, char_type_class,
5728 enumeral_type_class, boolean_type_class,
5729 pointer_type_class, reference_type_class, offset_type_class,
5730 real_type_class, complex_type_class,
5731 function_type_class, method_type_class,
5732 record_type_class, union_type_class,
5733 array_type_class, string_type_class,
5734 lang_type_class
5735 };
Mike Stump11289f42009-09-09 15:08:12 +00005736
5737 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005738 // ideal, however it is what gcc does.
5739 if (E->getNumArgs() == 0)
5740 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005741
Chris Lattner86ee2862008-10-06 06:40:35 +00005742 QualType ArgTy = E->getArg(0)->getType();
5743 if (ArgTy->isVoidType())
5744 return void_type_class;
5745 else if (ArgTy->isEnumeralType())
5746 return enumeral_type_class;
5747 else if (ArgTy->isBooleanType())
5748 return boolean_type_class;
5749 else if (ArgTy->isCharType())
5750 return string_type_class; // gcc doesn't appear to use char_type_class
5751 else if (ArgTy->isIntegerType())
5752 return integer_type_class;
5753 else if (ArgTy->isPointerType())
5754 return pointer_type_class;
5755 else if (ArgTy->isReferenceType())
5756 return reference_type_class;
5757 else if (ArgTy->isRealType())
5758 return real_type_class;
5759 else if (ArgTy->isComplexType())
5760 return complex_type_class;
5761 else if (ArgTy->isFunctionType())
5762 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005763 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005764 return record_type_class;
5765 else if (ArgTy->isUnionType())
5766 return union_type_class;
5767 else if (ArgTy->isArrayType())
5768 return array_type_class;
5769 else if (ArgTy->isUnionType())
5770 return union_type_class;
5771 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005772 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005773}
5774
Richard Smith5fab0c92011-12-28 19:48:30 +00005775/// EvaluateBuiltinConstantPForLValue - Determine the result of
5776/// __builtin_constant_p when applied to the given lvalue.
5777///
5778/// An lvalue is only "constant" if it is a pointer or reference to the first
5779/// character of a string literal.
5780template<typename LValue>
5781static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005782 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005783 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5784}
5785
5786/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5787/// GCC as we can manage.
5788static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5789 QualType ArgType = Arg->getType();
5790
5791 // __builtin_constant_p always has one operand. The rules which gcc follows
5792 // are not precisely documented, but are as follows:
5793 //
5794 // - If the operand is of integral, floating, complex or enumeration type,
5795 // and can be folded to a known value of that type, it returns 1.
5796 // - If the operand and can be folded to a pointer to the first character
5797 // of a string literal (or such a pointer cast to an integral type), it
5798 // returns 1.
5799 //
5800 // Otherwise, it returns 0.
5801 //
5802 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5803 // its support for this does not currently work.
5804 if (ArgType->isIntegralOrEnumerationType()) {
5805 Expr::EvalResult Result;
5806 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5807 return false;
5808
5809 APValue &V = Result.Val;
5810 if (V.getKind() == APValue::Int)
5811 return true;
5812
5813 return EvaluateBuiltinConstantPForLValue(V);
5814 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5815 return Arg->isEvaluatable(Ctx);
5816 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5817 LValue LV;
5818 Expr::EvalStatus Status;
5819 EvalInfo Info(Ctx, Status);
5820 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5821 : EvaluatePointer(Arg, LV, Info)) &&
5822 !Status.HasSideEffects)
5823 return EvaluateBuiltinConstantPForLValue(LV);
5824 }
5825
5826 // Anything else isn't considered to be sufficiently constant.
5827 return false;
5828}
5829
John McCall95007602010-05-10 23:27:23 +00005830/// Retrieves the "underlying object type" of the given expression,
5831/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005832QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5833 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5834 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005835 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005836 } else if (const Expr *E = B.get<const Expr*>()) {
5837 if (isa<CompoundLiteralExpr>(E))
5838 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005839 }
5840
5841 return QualType();
5842}
5843
Peter Collingbournee9200682011-05-13 03:29:01 +00005844bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005845 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005846
5847 {
5848 // The operand of __builtin_object_size is never evaluated for side-effects.
5849 // If there are any, but we can determine the pointed-to object anyway, then
5850 // ignore the side-effects.
5851 SpeculativeEvaluationRAII SpeculativeEval(Info);
5852 if (!EvaluatePointer(E->getArg(0), Base, Info))
5853 return false;
5854 }
John McCall95007602010-05-10 23:27:23 +00005855
5856 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005857 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005858
Richard Smithce40ad62011-11-12 22:28:03 +00005859 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005860 if (T.isNull() ||
5861 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005862 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005863 T->isVariablyModifiedType() ||
5864 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005865 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005866
5867 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5868 CharUnits Offset = Base.getLValueOffset();
5869
5870 if (!Offset.isNegative() && Offset <= Size)
5871 Size -= Offset;
5872 else
5873 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005874 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005875}
5876
Peter Collingbournee9200682011-05-13 03:29:01 +00005877bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005878 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005879 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005880 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005881
5882 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005883 if (TryEvaluateBuiltinObjectSize(E))
5884 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005885
Richard Smith0421ce72012-08-07 04:16:51 +00005886 // If evaluating the argument has side-effects, we can't determine the size
5887 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5888 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005889 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005890 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005891 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005892 return Success(0, E);
5893 }
Mike Stump876387b2009-10-27 22:09:17 +00005894
Richard Smith01ade172012-05-23 04:13:20 +00005895 // Expression had no side effects, but we couldn't statically determine the
5896 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005897 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005898 }
5899
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005900 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005901 case Builtin::BI__builtin_bswap32:
5902 case Builtin::BI__builtin_bswap64: {
5903 APSInt Val;
5904 if (!EvaluateInteger(E->getArg(0), Val, Info))
5905 return false;
5906
5907 return Success(Val.byteSwap(), E);
5908 }
5909
Richard Smith8889a3d2013-06-13 06:26:32 +00005910 case Builtin::BI__builtin_classify_type:
5911 return Success(EvaluateBuiltinClassifyType(E), E);
5912
5913 // FIXME: BI__builtin_clrsb
5914 // FIXME: BI__builtin_clrsbl
5915 // FIXME: BI__builtin_clrsbll
5916
Richard Smith80b3c8e2013-06-13 05:04:16 +00005917 case Builtin::BI__builtin_clz:
5918 case Builtin::BI__builtin_clzl:
5919 case Builtin::BI__builtin_clzll: {
5920 APSInt Val;
5921 if (!EvaluateInteger(E->getArg(0), Val, Info))
5922 return false;
5923 if (!Val)
5924 return Error(E);
5925
5926 return Success(Val.countLeadingZeros(), E);
5927 }
5928
Richard Smith8889a3d2013-06-13 06:26:32 +00005929 case Builtin::BI__builtin_constant_p:
5930 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5931
Richard Smith80b3c8e2013-06-13 05:04:16 +00005932 case Builtin::BI__builtin_ctz:
5933 case Builtin::BI__builtin_ctzl:
5934 case Builtin::BI__builtin_ctzll: {
5935 APSInt Val;
5936 if (!EvaluateInteger(E->getArg(0), Val, Info))
5937 return false;
5938 if (!Val)
5939 return Error(E);
5940
5941 return Success(Val.countTrailingZeros(), E);
5942 }
5943
Richard Smith8889a3d2013-06-13 06:26:32 +00005944 case Builtin::BI__builtin_eh_return_data_regno: {
5945 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5946 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5947 return Success(Operand, E);
5948 }
5949
5950 case Builtin::BI__builtin_expect:
5951 return Visit(E->getArg(0));
5952
5953 case Builtin::BI__builtin_ffs:
5954 case Builtin::BI__builtin_ffsl:
5955 case Builtin::BI__builtin_ffsll: {
5956 APSInt Val;
5957 if (!EvaluateInteger(E->getArg(0), Val, Info))
5958 return false;
5959
5960 unsigned N = Val.countTrailingZeros();
5961 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
5962 }
5963
5964 case Builtin::BI__builtin_fpclassify: {
5965 APFloat Val(0.0);
5966 if (!EvaluateFloat(E->getArg(5), Val, Info))
5967 return false;
5968 unsigned Arg;
5969 switch (Val.getCategory()) {
5970 case APFloat::fcNaN: Arg = 0; break;
5971 case APFloat::fcInfinity: Arg = 1; break;
5972 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
5973 case APFloat::fcZero: Arg = 4; break;
5974 }
5975 return Visit(E->getArg(Arg));
5976 }
5977
5978 case Builtin::BI__builtin_isinf_sign: {
5979 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00005980 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00005981 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
5982 }
5983
5984 case Builtin::BI__builtin_parity:
5985 case Builtin::BI__builtin_parityl:
5986 case Builtin::BI__builtin_parityll: {
5987 APSInt Val;
5988 if (!EvaluateInteger(E->getArg(0), Val, Info))
5989 return false;
5990
5991 return Success(Val.countPopulation() % 2, E);
5992 }
5993
Richard Smith80b3c8e2013-06-13 05:04:16 +00005994 case Builtin::BI__builtin_popcount:
5995 case Builtin::BI__builtin_popcountl:
5996 case Builtin::BI__builtin_popcountll: {
5997 APSInt Val;
5998 if (!EvaluateInteger(E->getArg(0), Val, Info))
5999 return false;
6000
6001 return Success(Val.countPopulation(), E);
6002 }
6003
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006004 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006005 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006006 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006007 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006008 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6009 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006010 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006011 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006012 case Builtin::BI__builtin_strlen:
6013 // As an extension, we support strlen() and __builtin_strlen() as constant
6014 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00006015 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006016 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
6017 // The string literal may have embedded null characters. Find the first
6018 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006019 StringRef Str = S->getString();
6020 StringRef::size_type Pos = Str.find(0);
6021 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006022 Str = Str.substr(0, Pos);
6023
6024 return Success(Str.size(), E);
6025 }
6026
Richard Smithf57d8cb2011-12-09 22:58:01 +00006027 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006028
Richard Smith01ba47d2012-04-13 00:45:38 +00006029 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006030 case Builtin::BI__atomic_is_lock_free:
6031 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006032 APSInt SizeVal;
6033 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6034 return false;
6035
6036 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6037 // of two less than the maximum inline atomic width, we know it is
6038 // lock-free. If the size isn't a power of two, or greater than the
6039 // maximum alignment where we promote atomics, we know it is not lock-free
6040 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6041 // the answer can only be determined at runtime; for example, 16-byte
6042 // atomics have lock-free implementations on some, but not all,
6043 // x86-64 processors.
6044
6045 // Check power-of-two.
6046 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006047 if (Size.isPowerOfTwo()) {
6048 // Check against inlining width.
6049 unsigned InlineWidthBits =
6050 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6051 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6052 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6053 Size == CharUnits::One() ||
6054 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6055 Expr::NPC_NeverValueDependent))
6056 // OK, we will inline appropriately-aligned operations of this size,
6057 // and _Atomic(T) is appropriately-aligned.
6058 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006059
Richard Smith01ba47d2012-04-13 00:45:38 +00006060 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6061 castAs<PointerType>()->getPointeeType();
6062 if (!PointeeType->isIncompleteType() &&
6063 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6064 // OK, we will inline operations on this object.
6065 return Success(1, E);
6066 }
6067 }
6068 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006069
Richard Smith01ba47d2012-04-13 00:45:38 +00006070 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6071 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006072 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006073 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006074}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006075
Richard Smith8b3497e2011-10-31 01:37:14 +00006076static bool HasSameBase(const LValue &A, const LValue &B) {
6077 if (!A.getLValueBase())
6078 return !B.getLValueBase();
6079 if (!B.getLValueBase())
6080 return false;
6081
Richard Smithce40ad62011-11-12 22:28:03 +00006082 if (A.getLValueBase().getOpaqueValue() !=
6083 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006084 const Decl *ADecl = GetLValueBaseDecl(A);
6085 if (!ADecl)
6086 return false;
6087 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006088 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006089 return false;
6090 }
6091
6092 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006093 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006094}
6095
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006096namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006097
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006098/// \brief Data recursive integer evaluator of certain binary operators.
6099///
6100/// We use a data recursive algorithm for binary operators so that we are able
6101/// to handle extreme cases of chained binary operators without causing stack
6102/// overflow.
6103class DataRecursiveIntBinOpEvaluator {
6104 struct EvalResult {
6105 APValue Val;
6106 bool Failed;
6107
6108 EvalResult() : Failed(false) { }
6109
6110 void swap(EvalResult &RHS) {
6111 Val.swap(RHS.Val);
6112 Failed = RHS.Failed;
6113 RHS.Failed = false;
6114 }
6115 };
6116
6117 struct Job {
6118 const Expr *E;
6119 EvalResult LHSResult; // meaningful only for binary operator expression.
6120 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6121
6122 Job() : StoredInfo(0) { }
6123 void startSpeculativeEval(EvalInfo &Info) {
6124 OldEvalStatus = Info.EvalStatus;
6125 Info.EvalStatus.Diag = 0;
6126 StoredInfo = &Info;
6127 }
6128 ~Job() {
6129 if (StoredInfo) {
6130 StoredInfo->EvalStatus = OldEvalStatus;
6131 }
6132 }
6133 private:
6134 EvalInfo *StoredInfo; // non-null if status changed.
6135 Expr::EvalStatus OldEvalStatus;
6136 };
6137
6138 SmallVector<Job, 16> Queue;
6139
6140 IntExprEvaluator &IntEval;
6141 EvalInfo &Info;
6142 APValue &FinalResult;
6143
6144public:
6145 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6146 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6147
6148 /// \brief True if \param E is a binary operator that we are going to handle
6149 /// data recursively.
6150 /// We handle binary operators that are comma, logical, or that have operands
6151 /// with integral or enumeration type.
6152 static bool shouldEnqueue(const BinaryOperator *E) {
6153 return E->getOpcode() == BO_Comma ||
6154 E->isLogicalOp() ||
6155 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6156 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006157 }
6158
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006159 bool Traverse(const BinaryOperator *E) {
6160 enqueue(E);
6161 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006162 while (!Queue.empty())
6163 process(PrevResult);
6164
6165 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006166
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006167 FinalResult.swap(PrevResult.Val);
6168 return true;
6169 }
6170
6171private:
6172 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6173 return IntEval.Success(Value, E, Result);
6174 }
6175 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6176 return IntEval.Success(Value, E, Result);
6177 }
6178 bool Error(const Expr *E) {
6179 return IntEval.Error(E);
6180 }
6181 bool Error(const Expr *E, diag::kind D) {
6182 return IntEval.Error(E, D);
6183 }
6184
6185 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6186 return Info.CCEDiag(E, D);
6187 }
6188
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006189 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6190 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006191 bool &SuppressRHSDiags);
6192
6193 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6194 const BinaryOperator *E, APValue &Result);
6195
6196 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6197 Result.Failed = !Evaluate(Result.Val, Info, E);
6198 if (Result.Failed)
6199 Result.Val = APValue();
6200 }
6201
Richard Trieuba4d0872012-03-21 23:30:30 +00006202 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006203
6204 void enqueue(const Expr *E) {
6205 E = E->IgnoreParens();
6206 Queue.resize(Queue.size()+1);
6207 Queue.back().E = E;
6208 Queue.back().Kind = Job::AnyExprKind;
6209 }
6210};
6211
6212}
6213
6214bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006215 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006216 bool &SuppressRHSDiags) {
6217 if (E->getOpcode() == BO_Comma) {
6218 // Ignore LHS but note if we could not evaluate it.
6219 if (LHSResult.Failed)
6220 Info.EvalStatus.HasSideEffects = true;
6221 return true;
6222 }
6223
6224 if (E->isLogicalOp()) {
6225 bool lhsResult;
6226 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006227 // We were able to evaluate the LHS, see if we can get away with not
6228 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006229 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006230 Success(lhsResult, E, LHSResult.Val);
6231 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006232 }
6233 } else {
6234 // Since we weren't able to evaluate the left hand side, it
6235 // must have had side effects.
6236 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006237
6238 // We can't evaluate the LHS; however, sometimes the result
6239 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6240 // Don't ignore RHS and suppress diagnostics from this arm.
6241 SuppressRHSDiags = true;
6242 }
6243
6244 return true;
6245 }
6246
6247 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6248 E->getRHS()->getType()->isIntegralOrEnumerationType());
6249
6250 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006251 return false; // Ignore RHS;
6252
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006253 return true;
6254}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006255
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006256bool DataRecursiveIntBinOpEvaluator::
6257 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6258 const BinaryOperator *E, APValue &Result) {
6259 if (E->getOpcode() == BO_Comma) {
6260 if (RHSResult.Failed)
6261 return false;
6262 Result = RHSResult.Val;
6263 return true;
6264 }
6265
6266 if (E->isLogicalOp()) {
6267 bool lhsResult, rhsResult;
6268 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6269 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6270
6271 if (LHSIsOK) {
6272 if (RHSIsOK) {
6273 if (E->getOpcode() == BO_LOr)
6274 return Success(lhsResult || rhsResult, E, Result);
6275 else
6276 return Success(lhsResult && rhsResult, E, Result);
6277 }
6278 } else {
6279 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006280 // We can't evaluate the LHS; however, sometimes the result
6281 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6282 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006283 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006284 }
6285 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006286
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006287 return false;
6288 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006289
6290 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6291 E->getRHS()->getType()->isIntegralOrEnumerationType());
6292
6293 if (LHSResult.Failed || RHSResult.Failed)
6294 return false;
6295
6296 const APValue &LHSVal = LHSResult.Val;
6297 const APValue &RHSVal = RHSResult.Val;
6298
6299 // Handle cases like (unsigned long)&a + 4.
6300 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6301 Result = LHSVal;
6302 CharUnits AdditionalOffset = CharUnits::fromQuantity(
6303 RHSVal.getInt().getZExtValue());
6304 if (E->getOpcode() == BO_Add)
6305 Result.getLValueOffset() += AdditionalOffset;
6306 else
6307 Result.getLValueOffset() -= AdditionalOffset;
6308 return true;
6309 }
6310
6311 // Handle cases like 4 + (unsigned long)&a
6312 if (E->getOpcode() == BO_Add &&
6313 RHSVal.isLValue() && LHSVal.isInt()) {
6314 Result = RHSVal;
6315 Result.getLValueOffset() += CharUnits::fromQuantity(
6316 LHSVal.getInt().getZExtValue());
6317 return true;
6318 }
6319
6320 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6321 // Handle (intptr_t)&&A - (intptr_t)&&B.
6322 if (!LHSVal.getLValueOffset().isZero() ||
6323 !RHSVal.getLValueOffset().isZero())
6324 return false;
6325 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6326 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6327 if (!LHSExpr || !RHSExpr)
6328 return false;
6329 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6330 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6331 if (!LHSAddrExpr || !RHSAddrExpr)
6332 return false;
6333 // Make sure both labels come from the same function.
6334 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6335 RHSAddrExpr->getLabel()->getDeclContext())
6336 return false;
6337 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6338 return true;
6339 }
Richard Smith43e77732013-05-07 04:50:00 +00006340
6341 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006342 if (!LHSVal.isInt() || !RHSVal.isInt())
6343 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006344
6345 // Set up the width and signedness manually, in case it can't be deduced
6346 // from the operation we're performing.
6347 // FIXME: Don't do this in the cases where we can deduce it.
6348 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6349 E->getType()->isUnsignedIntegerOrEnumerationType());
6350 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6351 RHSVal.getInt(), Value))
6352 return false;
6353 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006354}
6355
Richard Trieuba4d0872012-03-21 23:30:30 +00006356void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006357 Job &job = Queue.back();
6358
6359 switch (job.Kind) {
6360 case Job::AnyExprKind: {
6361 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6362 if (shouldEnqueue(Bop)) {
6363 job.Kind = Job::BinOpKind;
6364 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006365 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006366 }
6367 }
6368
6369 EvaluateExpr(job.E, Result);
6370 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006371 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006372 }
6373
6374 case Job::BinOpKind: {
6375 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006376 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006377 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006378 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006379 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006380 }
6381 if (SuppressRHSDiags)
6382 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006383 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006384 job.Kind = Job::BinOpVisitedLHSKind;
6385 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006386 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006387 }
6388
6389 case Job::BinOpVisitedLHSKind: {
6390 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6391 EvalResult RHS;
6392 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006393 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006394 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006395 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006396 }
6397 }
6398
6399 llvm_unreachable("Invalid Job::Kind!");
6400}
6401
6402bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6403 if (E->isAssignmentOp())
6404 return Error(E);
6405
6406 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6407 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006408
Anders Carlssonacc79812008-11-16 07:17:21 +00006409 QualType LHSTy = E->getLHS()->getType();
6410 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006411
6412 if (LHSTy->isAnyComplexType()) {
6413 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006414 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006415
Richard Smith253c2a32012-01-27 01:14:48 +00006416 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6417 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006418 return false;
6419
Richard Smith253c2a32012-01-27 01:14:48 +00006420 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006421 return false;
6422
6423 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006424 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006425 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006426 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006427 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6428
John McCalle3027922010-08-25 11:45:40 +00006429 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006430 return Success((CR_r == APFloat::cmpEqual &&
6431 CR_i == APFloat::cmpEqual), E);
6432 else {
John McCalle3027922010-08-25 11:45:40 +00006433 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006434 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006435 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006436 CR_r == APFloat::cmpLessThan ||
6437 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006438 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006439 CR_i == APFloat::cmpLessThan ||
6440 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006441 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006442 } else {
John McCalle3027922010-08-25 11:45:40 +00006443 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006444 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6445 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6446 else {
John McCalle3027922010-08-25 11:45:40 +00006447 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006448 "Invalid compex comparison.");
6449 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6450 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6451 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006452 }
6453 }
Mike Stump11289f42009-09-09 15:08:12 +00006454
Anders Carlssonacc79812008-11-16 07:17:21 +00006455 if (LHSTy->isRealFloatingType() &&
6456 RHSTy->isRealFloatingType()) {
6457 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006458
Richard Smith253c2a32012-01-27 01:14:48 +00006459 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6460 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006461 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006462
Richard Smith253c2a32012-01-27 01:14:48 +00006463 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006464 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006465
Anders Carlssonacc79812008-11-16 07:17:21 +00006466 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006467
Anders Carlssonacc79812008-11-16 07:17:21 +00006468 switch (E->getOpcode()) {
6469 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006470 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006471 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006472 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006473 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006474 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006475 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006476 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006477 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006478 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006479 E);
John McCalle3027922010-08-25 11:45:40 +00006480 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006481 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006482 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006483 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006484 || CR == APFloat::cmpLessThan
6485 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006486 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006487 }
Mike Stump11289f42009-09-09 15:08:12 +00006488
Eli Friedmana38da572009-04-28 19:17:36 +00006489 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006490 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006491 LValue LHSValue, RHSValue;
6492
6493 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6494 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006495 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006496
Richard Smith253c2a32012-01-27 01:14:48 +00006497 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006498 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006499
Richard Smith8b3497e2011-10-31 01:37:14 +00006500 // Reject differing bases from the normal codepath; we special-case
6501 // comparisons to null.
6502 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006503 if (E->getOpcode() == BO_Sub) {
6504 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006505 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6506 return false;
6507 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006508 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006509 if (!LHSExpr || !RHSExpr)
6510 return false;
6511 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6512 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6513 if (!LHSAddrExpr || !RHSAddrExpr)
6514 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006515 // Make sure both labels come from the same function.
6516 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6517 RHSAddrExpr->getLabel()->getDeclContext())
6518 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006519 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006520 return true;
6521 }
Richard Smith83c68212011-10-31 05:11:32 +00006522 // Inequalities and subtractions between unrelated pointers have
6523 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006524 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006525 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006526 // A constant address may compare equal to the address of a symbol.
6527 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006528 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006529 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6530 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006531 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006532 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006533 // distinct addresses. In clang, the result of such a comparison is
6534 // unspecified, so it is not a constant expression. However, we do know
6535 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006536 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6537 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006538 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006539 // We can't tell whether weak symbols will end up pointing to the same
6540 // object.
6541 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006542 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006543 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006544 // (Note that clang defaults to -fmerge-all-constants, which can
6545 // lead to inconsistent results for comparisons involving the address
6546 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006547 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006548 }
Eli Friedman64004332009-03-23 04:38:34 +00006549
Richard Smith1b470412012-02-01 08:10:20 +00006550 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6551 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6552
Richard Smith84f6dcf2012-02-02 01:16:57 +00006553 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6554 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6555
John McCalle3027922010-08-25 11:45:40 +00006556 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006557 // C++11 [expr.add]p6:
6558 // Unless both pointers point to elements of the same array object, or
6559 // one past the last element of the array object, the behavior is
6560 // undefined.
6561 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6562 !AreElementsOfSameArray(getType(LHSValue.Base),
6563 LHSDesignator, RHSDesignator))
6564 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6565
Chris Lattner882bdf22010-04-20 17:13:14 +00006566 QualType Type = E->getLHS()->getType();
6567 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006568
Richard Smithd62306a2011-11-10 06:34:14 +00006569 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006570 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006571 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006572
Richard Smith1b470412012-02-01 08:10:20 +00006573 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6574 // and produce incorrect results when it overflows. Such behavior
6575 // appears to be non-conforming, but is common, so perhaps we should
6576 // assume the standard intended for such cases to be undefined behavior
6577 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006578
Richard Smith1b470412012-02-01 08:10:20 +00006579 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6580 // overflow in the final conversion to ptrdiff_t.
6581 APSInt LHS(
6582 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6583 APSInt RHS(
6584 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6585 APSInt ElemSize(
6586 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6587 APSInt TrueResult = (LHS - RHS) / ElemSize;
6588 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6589
6590 if (Result.extend(65) != TrueResult)
6591 HandleOverflow(Info, E, TrueResult, E->getType());
6592 return Success(Result, E);
6593 }
Richard Smithde21b242012-01-31 06:41:30 +00006594
6595 // C++11 [expr.rel]p3:
6596 // Pointers to void (after pointer conversions) can be compared, with a
6597 // result defined as follows: If both pointers represent the same
6598 // address or are both the null pointer value, the result is true if the
6599 // operator is <= or >= and false otherwise; otherwise the result is
6600 // unspecified.
6601 // We interpret this as applying to pointers to *cv* void.
6602 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006603 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006604 CCEDiag(E, diag::note_constexpr_void_comparison);
6605
Richard Smith84f6dcf2012-02-02 01:16:57 +00006606 // C++11 [expr.rel]p2:
6607 // - If two pointers point to non-static data members of the same object,
6608 // or to subobjects or array elements fo such members, recursively, the
6609 // pointer to the later declared member compares greater provided the
6610 // two members have the same access control and provided their class is
6611 // not a union.
6612 // [...]
6613 // - Otherwise pointer comparisons are unspecified.
6614 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6615 E->isRelationalOp()) {
6616 bool WasArrayIndex;
6617 unsigned Mismatch =
6618 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6619 RHSDesignator, WasArrayIndex);
6620 // At the point where the designators diverge, the comparison has a
6621 // specified value if:
6622 // - we are comparing array indices
6623 // - we are comparing fields of a union, or fields with the same access
6624 // Otherwise, the result is unspecified and thus the comparison is not a
6625 // constant expression.
6626 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6627 Mismatch < RHSDesignator.Entries.size()) {
6628 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6629 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6630 if (!LF && !RF)
6631 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6632 else if (!LF)
6633 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6634 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6635 << RF->getParent() << RF;
6636 else if (!RF)
6637 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6638 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6639 << LF->getParent() << LF;
6640 else if (!LF->getParent()->isUnion() &&
6641 LF->getAccess() != RF->getAccess())
6642 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6643 << LF << LF->getAccess() << RF << RF->getAccess()
6644 << LF->getParent();
6645 }
6646 }
6647
Eli Friedman6c31cb42012-04-16 04:30:08 +00006648 // The comparison here must be unsigned, and performed with the same
6649 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006650 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6651 uint64_t CompareLHS = LHSOffset.getQuantity();
6652 uint64_t CompareRHS = RHSOffset.getQuantity();
6653 assert(PtrSize <= 64 && "Unexpected pointer width");
6654 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6655 CompareLHS &= Mask;
6656 CompareRHS &= Mask;
6657
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006658 // If there is a base and this is a relational operator, we can only
6659 // compare pointers within the object in question; otherwise, the result
6660 // depends on where the object is located in memory.
6661 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6662 QualType BaseTy = getType(LHSValue.Base);
6663 if (BaseTy->isIncompleteType())
6664 return Error(E);
6665 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6666 uint64_t OffsetLimit = Size.getQuantity();
6667 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6668 return Error(E);
6669 }
6670
Richard Smith8b3497e2011-10-31 01:37:14 +00006671 switch (E->getOpcode()) {
6672 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006673 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6674 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6675 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6676 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6677 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6678 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006679 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006680 }
6681 }
Richard Smith7bb00672012-02-01 01:42:44 +00006682
6683 if (LHSTy->isMemberPointerType()) {
6684 assert(E->isEqualityOp() && "unexpected member pointer operation");
6685 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6686
6687 MemberPtr LHSValue, RHSValue;
6688
6689 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6690 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6691 return false;
6692
6693 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6694 return false;
6695
6696 // C++11 [expr.eq]p2:
6697 // If both operands are null, they compare equal. Otherwise if only one is
6698 // null, they compare unequal.
6699 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6700 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6701 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6702 }
6703
6704 // Otherwise if either is a pointer to a virtual member function, the
6705 // result is unspecified.
6706 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6707 if (MD->isVirtual())
6708 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6710 if (MD->isVirtual())
6711 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6712
6713 // Otherwise they compare equal if and only if they would refer to the
6714 // same member of the same most derived object or the same subobject if
6715 // they were dereferenced with a hypothetical object of the associated
6716 // class type.
6717 bool Equal = LHSValue == RHSValue;
6718 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6719 }
6720
Richard Smithab44d9b2012-02-14 22:35:28 +00006721 if (LHSTy->isNullPtrType()) {
6722 assert(E->isComparisonOp() && "unexpected nullptr operation");
6723 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6724 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6725 // are compared, the result is true of the operator is <=, >= or ==, and
6726 // false otherwise.
6727 BinaryOperator::Opcode Opcode = E->getOpcode();
6728 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6729 }
6730
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006731 assert((!LHSTy->isIntegralOrEnumerationType() ||
6732 !RHSTy->isIntegralOrEnumerationType()) &&
6733 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6734 // We can't continue from here for non-integral types.
6735 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006736}
6737
Ken Dyck160146e2010-01-27 17:10:57 +00006738CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006739 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6740 // result shall be the alignment of the referenced type."
6741 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6742 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006743
6744 // __alignof is defined to return the preferred alignment.
6745 return Info.Ctx.toCharUnitsFromBits(
6746 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006747}
6748
Ken Dyck160146e2010-01-27 17:10:57 +00006749CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006750 E = E->IgnoreParens();
6751
John McCall768439e2013-05-06 07:40:34 +00006752 // The kinds of expressions that we have special-case logic here for
6753 // should be kept up to date with the special checks for those
6754 // expressions in Sema.
6755
Chris Lattner68061312009-01-24 21:53:27 +00006756 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006757 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006758 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006759 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6760 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006761
Chris Lattner68061312009-01-24 21:53:27 +00006762 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006763 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6764 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006765
Chris Lattner24aeeab2009-01-24 21:09:06 +00006766 return GetAlignOfType(E->getType());
6767}
6768
6769
Peter Collingbournee190dee2011-03-11 19:24:49 +00006770/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6771/// a result as the expression's type.
6772bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6773 const UnaryExprOrTypeTraitExpr *E) {
6774 switch(E->getKind()) {
6775 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006776 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006777 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006778 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006779 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006780 }
Eli Friedman64004332009-03-23 04:38:34 +00006781
Peter Collingbournee190dee2011-03-11 19:24:49 +00006782 case UETT_VecStep: {
6783 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006784
Peter Collingbournee190dee2011-03-11 19:24:49 +00006785 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006786 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006787
Peter Collingbournee190dee2011-03-11 19:24:49 +00006788 // The vec_step built-in functions that take a 3-component
6789 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6790 if (n == 3)
6791 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006792
Peter Collingbournee190dee2011-03-11 19:24:49 +00006793 return Success(n, E);
6794 } else
6795 return Success(1, E);
6796 }
6797
6798 case UETT_SizeOf: {
6799 QualType SrcTy = E->getTypeOfArgument();
6800 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6801 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006802 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6803 SrcTy = Ref->getPointeeType();
6804
Richard Smithd62306a2011-11-10 06:34:14 +00006805 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006806 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006807 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006808 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006809 }
6810 }
6811
6812 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006813}
6814
Peter Collingbournee9200682011-05-13 03:29:01 +00006815bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006816 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006817 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006818 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006819 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006820 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006821 for (unsigned i = 0; i != n; ++i) {
6822 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6823 switch (ON.getKind()) {
6824 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006825 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006826 APSInt IdxResult;
6827 if (!EvaluateInteger(Idx, IdxResult, Info))
6828 return false;
6829 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6830 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006831 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006832 CurrentType = AT->getElementType();
6833 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6834 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006835 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006836 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006837
Douglas Gregor882211c2010-04-28 22:16:22 +00006838 case OffsetOfExpr::OffsetOfNode::Field: {
6839 FieldDecl *MemberDecl = ON.getField();
6840 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006841 if (!RT)
6842 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006843 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006844 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006845 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006846 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006847 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006848 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006849 CurrentType = MemberDecl->getType().getNonReferenceType();
6850 break;
6851 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006852
Douglas Gregor882211c2010-04-28 22:16:22 +00006853 case OffsetOfExpr::OffsetOfNode::Identifier:
6854 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006855
Douglas Gregord1702062010-04-29 00:18:15 +00006856 case OffsetOfExpr::OffsetOfNode::Base: {
6857 CXXBaseSpecifier *BaseSpec = ON.getBase();
6858 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006859 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006860
6861 // Find the layout of the class whose base we are looking into.
6862 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006863 if (!RT)
6864 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006865 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006866 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006867 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6868
6869 // Find the base class itself.
6870 CurrentType = BaseSpec->getType();
6871 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6872 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006873 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006874
6875 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006876 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006877 break;
6878 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006879 }
6880 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006881 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006882}
6883
Chris Lattnere13042c2008-07-11 19:10:17 +00006884bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006885 switch (E->getOpcode()) {
6886 default:
6887 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6888 // See C99 6.6p3.
6889 return Error(E);
6890 case UO_Extension:
6891 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6892 // If so, we could clear the diagnostic ID.
6893 return Visit(E->getSubExpr());
6894 case UO_Plus:
6895 // The result is just the value.
6896 return Visit(E->getSubExpr());
6897 case UO_Minus: {
6898 if (!Visit(E->getSubExpr()))
6899 return false;
6900 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006901 const APSInt &Value = Result.getInt();
6902 if (Value.isSigned() && Value.isMinSignedValue())
6903 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6904 E->getType());
6905 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006906 }
6907 case UO_Not: {
6908 if (!Visit(E->getSubExpr()))
6909 return false;
6910 if (!Result.isInt()) return Error(E);
6911 return Success(~Result.getInt(), E);
6912 }
6913 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006914 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006915 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006916 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006917 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006918 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006919 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006920}
Mike Stump11289f42009-09-09 15:08:12 +00006921
Chris Lattner477c4be2008-07-12 01:15:53 +00006922/// HandleCast - This is used to evaluate implicit or explicit casts where the
6923/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006924bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6925 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006926 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006927 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006928
Eli Friedmanc757de22011-03-25 00:43:55 +00006929 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006930 case CK_BaseToDerived:
6931 case CK_DerivedToBase:
6932 case CK_UncheckedDerivedToBase:
6933 case CK_Dynamic:
6934 case CK_ToUnion:
6935 case CK_ArrayToPointerDecay:
6936 case CK_FunctionToPointerDecay:
6937 case CK_NullToPointer:
6938 case CK_NullToMemberPointer:
6939 case CK_BaseToDerivedMemberPointer:
6940 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006941 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006942 case CK_ConstructorConversion:
6943 case CK_IntegralToPointer:
6944 case CK_ToVoid:
6945 case CK_VectorSplat:
6946 case CK_IntegralToFloating:
6947 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006948 case CK_CPointerToObjCPointerCast:
6949 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006950 case CK_AnyPointerToBlockPointerCast:
6951 case CK_ObjCObjectLValueCast:
6952 case CK_FloatingRealToComplex:
6953 case CK_FloatingComplexToReal:
6954 case CK_FloatingComplexCast:
6955 case CK_FloatingComplexToIntegralComplex:
6956 case CK_IntegralRealToComplex:
6957 case CK_IntegralComplexCast:
6958 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006959 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006960 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00006961 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006962 llvm_unreachable("invalid cast kind for integral value");
6963
Eli Friedman9faf2f92011-03-25 19:07:11 +00006964 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006965 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006966 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006967 case CK_ARCProduceObject:
6968 case CK_ARCConsumeObject:
6969 case CK_ARCReclaimReturnedObject:
6970 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006971 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006972 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006973
Richard Smith4ef685b2012-01-17 21:17:26 +00006974 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006975 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006976 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006977 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006978 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006979
6980 case CK_MemberPointerToBoolean:
6981 case CK_PointerToBoolean:
6982 case CK_IntegralToBoolean:
6983 case CK_FloatingToBoolean:
6984 case CK_FloatingComplexToBoolean:
6985 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006986 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006987 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006988 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006989 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006990 }
6991
Eli Friedmanc757de22011-03-25 00:43:55 +00006992 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006993 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006994 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006995
Eli Friedman742421e2009-02-20 01:15:07 +00006996 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006997 // Allow casts of address-of-label differences if they are no-ops
6998 // or narrowing. (The narrowing case isn't actually guaranteed to
6999 // be constant-evaluatable except in some narrow cases which are hard
7000 // to detect here. We let it through on the assumption the user knows
7001 // what they are doing.)
7002 if (Result.isAddrLabelDiff())
7003 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007004 // Only allow casts of lvalues if they are lossless.
7005 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7006 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007007
Richard Smith911e1422012-01-30 22:27:01 +00007008 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7009 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007010 }
Mike Stump11289f42009-09-09 15:08:12 +00007011
Eli Friedmanc757de22011-03-25 00:43:55 +00007012 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007013 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7014
John McCall45d55e42010-05-07 21:00:08 +00007015 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007016 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007017 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007018
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007019 if (LV.getLValueBase()) {
7020 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007021 // FIXME: Allow a larger integer size than the pointer size, and allow
7022 // narrowing back down to pointer width in subsequent integral casts.
7023 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007024 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007026
Richard Smithcf74da72011-11-16 07:18:12 +00007027 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007028 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007029 return true;
7030 }
7031
Ken Dyck02990832010-01-15 12:37:54 +00007032 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7033 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007034 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007035 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007036
Eli Friedmanc757de22011-03-25 00:43:55 +00007037 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007038 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007039 if (!EvaluateComplex(SubExpr, C, Info))
7040 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007041 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007042 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007043
Eli Friedmanc757de22011-03-25 00:43:55 +00007044 case CK_FloatingToIntegral: {
7045 APFloat F(0.0);
7046 if (!EvaluateFloat(SubExpr, F, Info))
7047 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007048
Richard Smith357362d2011-12-13 06:39:58 +00007049 APSInt Value;
7050 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7051 return false;
7052 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007053 }
7054 }
Mike Stump11289f42009-09-09 15:08:12 +00007055
Eli Friedmanc757de22011-03-25 00:43:55 +00007056 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007057}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007058
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007059bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7060 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007061 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007062 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7063 return false;
7064 if (!LV.isComplexInt())
7065 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007066 return Success(LV.getComplexIntReal(), E);
7067 }
7068
7069 return Visit(E->getSubExpr());
7070}
7071
Eli Friedman4e7a2412009-02-27 04:45:43 +00007072bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007073 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007074 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007075 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7076 return false;
7077 if (!LV.isComplexInt())
7078 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007079 return Success(LV.getComplexIntImag(), E);
7080 }
7081
Richard Smith4a678122011-10-24 18:44:57 +00007082 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007083 return Success(0, E);
7084}
7085
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007086bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7087 return Success(E->getPackLength(), E);
7088}
7089
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007090bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7091 return Success(E->getValue(), E);
7092}
7093
Chris Lattner05706e882008-07-11 18:11:29 +00007094//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007095// Float Evaluation
7096//===----------------------------------------------------------------------===//
7097
7098namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007099class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007100 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00007101 APFloat &Result;
7102public:
7103 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007104 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007105
Richard Smith2e312c82012-03-03 22:46:17 +00007106 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007107 Result = V.getFloat();
7108 return true;
7109 }
Eli Friedman24c01542008-08-22 00:06:13 +00007110
Richard Smithfddd3842011-12-30 21:15:51 +00007111 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007112 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7113 return true;
7114 }
7115
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007116 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007117
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007118 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007119 bool VisitBinaryOperator(const BinaryOperator *E);
7120 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007121 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007122
John McCallb1fb0d32010-05-07 22:08:54 +00007123 bool VisitUnaryReal(const UnaryOperator *E);
7124 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007125
Richard Smithfddd3842011-12-30 21:15:51 +00007126 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007127};
7128} // end anonymous namespace
7129
7130static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007131 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007132 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007133}
7134
Jay Foad39c79802011-01-12 09:06:06 +00007135static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007136 QualType ResultTy,
7137 const Expr *Arg,
7138 bool SNaN,
7139 llvm::APFloat &Result) {
7140 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7141 if (!S) return false;
7142
7143 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7144
7145 llvm::APInt fill;
7146
7147 // Treat empty strings as if they were zero.
7148 if (S->getString().empty())
7149 fill = llvm::APInt(32, 0);
7150 else if (S->getString().getAsInteger(0, fill))
7151 return false;
7152
7153 if (SNaN)
7154 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7155 else
7156 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7157 return true;
7158}
7159
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007160bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007161 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007162 default:
7163 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7164
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007165 case Builtin::BI__builtin_huge_val:
7166 case Builtin::BI__builtin_huge_valf:
7167 case Builtin::BI__builtin_huge_vall:
7168 case Builtin::BI__builtin_inf:
7169 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007170 case Builtin::BI__builtin_infl: {
7171 const llvm::fltSemantics &Sem =
7172 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007173 Result = llvm::APFloat::getInf(Sem);
7174 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007175 }
Mike Stump11289f42009-09-09 15:08:12 +00007176
John McCall16291492010-02-28 13:00:19 +00007177 case Builtin::BI__builtin_nans:
7178 case Builtin::BI__builtin_nansf:
7179 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007180 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7181 true, Result))
7182 return Error(E);
7183 return true;
John McCall16291492010-02-28 13:00:19 +00007184
Chris Lattner0b7282e2008-10-06 06:31:58 +00007185 case Builtin::BI__builtin_nan:
7186 case Builtin::BI__builtin_nanf:
7187 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007188 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007189 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007190 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7191 false, Result))
7192 return Error(E);
7193 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007194
7195 case Builtin::BI__builtin_fabs:
7196 case Builtin::BI__builtin_fabsf:
7197 case Builtin::BI__builtin_fabsl:
7198 if (!EvaluateFloat(E->getArg(0), Result, Info))
7199 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007200
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007201 if (Result.isNegative())
7202 Result.changeSign();
7203 return true;
7204
Richard Smith8889a3d2013-06-13 06:26:32 +00007205 // FIXME: Builtin::BI__builtin_powi
7206 // FIXME: Builtin::BI__builtin_powif
7207 // FIXME: Builtin::BI__builtin_powil
7208
Mike Stump11289f42009-09-09 15:08:12 +00007209 case Builtin::BI__builtin_copysign:
7210 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007211 case Builtin::BI__builtin_copysignl: {
7212 APFloat RHS(0.);
7213 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7214 !EvaluateFloat(E->getArg(1), RHS, Info))
7215 return false;
7216 Result.copySign(RHS);
7217 return true;
7218 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007219 }
7220}
7221
John McCallb1fb0d32010-05-07 22:08:54 +00007222bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007223 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7224 ComplexValue CV;
7225 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7226 return false;
7227 Result = CV.FloatReal;
7228 return true;
7229 }
7230
7231 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007232}
7233
7234bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007235 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7236 ComplexValue CV;
7237 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7238 return false;
7239 Result = CV.FloatImag;
7240 return true;
7241 }
7242
Richard Smith4a678122011-10-24 18:44:57 +00007243 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007244 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7245 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007246 return true;
7247}
7248
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007249bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007250 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007251 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007252 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007253 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007254 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007255 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7256 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007257 Result.changeSign();
7258 return true;
7259 }
7260}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007261
Eli Friedman24c01542008-08-22 00:06:13 +00007262bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007263 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7264 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007265
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007266 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007267 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7268 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007269 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007270 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7271 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007272}
7273
7274bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7275 Result = E->getValue();
7276 return true;
7277}
7278
Peter Collingbournee9200682011-05-13 03:29:01 +00007279bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7280 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007281
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007282 switch (E->getCastKind()) {
7283 default:
Richard Smith11562c52011-10-28 17:51:58 +00007284 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007285
7286 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007287 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007288 return EvaluateInteger(SubExpr, IntResult, Info) &&
7289 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7290 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007291 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007292
7293 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007294 if (!Visit(SubExpr))
7295 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007296 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7297 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007298 }
John McCalld7646252010-11-14 08:17:51 +00007299
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007300 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007301 ComplexValue V;
7302 if (!EvaluateComplex(SubExpr, V, Info))
7303 return false;
7304 Result = V.getComplexFloatReal();
7305 return true;
7306 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007307 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007308}
7309
Eli Friedman24c01542008-08-22 00:06:13 +00007310//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007311// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007312//===----------------------------------------------------------------------===//
7313
7314namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007315class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00007316 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00007317 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007318
Anders Carlsson537969c2008-11-16 20:27:53 +00007319public:
John McCall93d91dc2010-05-07 17:22:02 +00007320 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007321 : ExprEvaluatorBaseTy(info), Result(Result) {}
7322
Richard Smith2e312c82012-03-03 22:46:17 +00007323 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007324 Result.setFrom(V);
7325 return true;
7326 }
Mike Stump11289f42009-09-09 15:08:12 +00007327
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007328 bool ZeroInitialization(const Expr *E);
7329
Anders Carlsson537969c2008-11-16 20:27:53 +00007330 //===--------------------------------------------------------------------===//
7331 // Visitor Methods
7332 //===--------------------------------------------------------------------===//
7333
Peter Collingbournee9200682011-05-13 03:29:01 +00007334 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007335 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007336 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007337 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007338 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007339};
7340} // end anonymous namespace
7341
John McCall93d91dc2010-05-07 17:22:02 +00007342static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7343 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007344 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007345 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007346}
7347
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007348bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007349 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007350 if (ElemTy->isRealFloatingType()) {
7351 Result.makeComplexFloat();
7352 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7353 Result.FloatReal = Zero;
7354 Result.FloatImag = Zero;
7355 } else {
7356 Result.makeComplexInt();
7357 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7358 Result.IntReal = Zero;
7359 Result.IntImag = Zero;
7360 }
7361 return true;
7362}
7363
Peter Collingbournee9200682011-05-13 03:29:01 +00007364bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7365 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007366
7367 if (SubExpr->getType()->isRealFloatingType()) {
7368 Result.makeComplexFloat();
7369 APFloat &Imag = Result.FloatImag;
7370 if (!EvaluateFloat(SubExpr, Imag, Info))
7371 return false;
7372
7373 Result.FloatReal = APFloat(Imag.getSemantics());
7374 return true;
7375 } else {
7376 assert(SubExpr->getType()->isIntegerType() &&
7377 "Unexpected imaginary literal.");
7378
7379 Result.makeComplexInt();
7380 APSInt &Imag = Result.IntImag;
7381 if (!EvaluateInteger(SubExpr, Imag, Info))
7382 return false;
7383
7384 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7385 return true;
7386 }
7387}
7388
Peter Collingbournee9200682011-05-13 03:29:01 +00007389bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007390
John McCallfcef3cf2010-12-14 17:51:41 +00007391 switch (E->getCastKind()) {
7392 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007393 case CK_BaseToDerived:
7394 case CK_DerivedToBase:
7395 case CK_UncheckedDerivedToBase:
7396 case CK_Dynamic:
7397 case CK_ToUnion:
7398 case CK_ArrayToPointerDecay:
7399 case CK_FunctionToPointerDecay:
7400 case CK_NullToPointer:
7401 case CK_NullToMemberPointer:
7402 case CK_BaseToDerivedMemberPointer:
7403 case CK_DerivedToBaseMemberPointer:
7404 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007405 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007406 case CK_ConstructorConversion:
7407 case CK_IntegralToPointer:
7408 case CK_PointerToIntegral:
7409 case CK_PointerToBoolean:
7410 case CK_ToVoid:
7411 case CK_VectorSplat:
7412 case CK_IntegralCast:
7413 case CK_IntegralToBoolean:
7414 case CK_IntegralToFloating:
7415 case CK_FloatingToIntegral:
7416 case CK_FloatingToBoolean:
7417 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007418 case CK_CPointerToObjCPointerCast:
7419 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007420 case CK_AnyPointerToBlockPointerCast:
7421 case CK_ObjCObjectLValueCast:
7422 case CK_FloatingComplexToReal:
7423 case CK_FloatingComplexToBoolean:
7424 case CK_IntegralComplexToReal:
7425 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007426 case CK_ARCProduceObject:
7427 case CK_ARCConsumeObject:
7428 case CK_ARCReclaimReturnedObject:
7429 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007430 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007431 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007432 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007433 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007434 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007435
John McCallfcef3cf2010-12-14 17:51:41 +00007436 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007437 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007438 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007439 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007440
7441 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007442 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007443 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007444 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007445
7446 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007447 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007448 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007449 return false;
7450
John McCallfcef3cf2010-12-14 17:51:41 +00007451 Result.makeComplexFloat();
7452 Result.FloatImag = APFloat(Real.getSemantics());
7453 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007454 }
7455
John McCallfcef3cf2010-12-14 17:51:41 +00007456 case CK_FloatingComplexCast: {
7457 if (!Visit(E->getSubExpr()))
7458 return false;
7459
7460 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7461 QualType From
7462 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7463
Richard Smith357362d2011-12-13 06:39:58 +00007464 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7465 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007466 }
7467
7468 case CK_FloatingComplexToIntegralComplex: {
7469 if (!Visit(E->getSubExpr()))
7470 return false;
7471
7472 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7473 QualType From
7474 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7475 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007476 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7477 To, Result.IntReal) &&
7478 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7479 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007480 }
7481
7482 case CK_IntegralRealToComplex: {
7483 APSInt &Real = Result.IntReal;
7484 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7485 return false;
7486
7487 Result.makeComplexInt();
7488 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7489 return true;
7490 }
7491
7492 case CK_IntegralComplexCast: {
7493 if (!Visit(E->getSubExpr()))
7494 return false;
7495
7496 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7497 QualType From
7498 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7499
Richard Smith911e1422012-01-30 22:27:01 +00007500 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7501 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007502 return true;
7503 }
7504
7505 case CK_IntegralComplexToFloatingComplex: {
7506 if (!Visit(E->getSubExpr()))
7507 return false;
7508
Ted Kremenek28831752012-08-23 20:46:57 +00007509 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007510 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007511 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007512 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007513 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7514 To, Result.FloatReal) &&
7515 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7516 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007517 }
7518 }
7519
7520 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007521}
7522
John McCall93d91dc2010-05-07 17:22:02 +00007523bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007524 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007525 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7526
Richard Smith253c2a32012-01-27 01:14:48 +00007527 bool LHSOK = Visit(E->getLHS());
7528 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007529 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007530
John McCall93d91dc2010-05-07 17:22:02 +00007531 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007532 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007533 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007534
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007535 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7536 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007537 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007538 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007539 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007540 if (Result.isComplexFloat()) {
7541 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7542 APFloat::rmNearestTiesToEven);
7543 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7544 APFloat::rmNearestTiesToEven);
7545 } else {
7546 Result.getComplexIntReal() += RHS.getComplexIntReal();
7547 Result.getComplexIntImag() += RHS.getComplexIntImag();
7548 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007549 break;
John McCalle3027922010-08-25 11:45:40 +00007550 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007551 if (Result.isComplexFloat()) {
7552 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7553 APFloat::rmNearestTiesToEven);
7554 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7555 APFloat::rmNearestTiesToEven);
7556 } else {
7557 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7558 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7559 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007560 break;
John McCalle3027922010-08-25 11:45:40 +00007561 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007562 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007563 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007564 APFloat &LHS_r = LHS.getComplexFloatReal();
7565 APFloat &LHS_i = LHS.getComplexFloatImag();
7566 APFloat &RHS_r = RHS.getComplexFloatReal();
7567 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007568
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007569 APFloat Tmp = LHS_r;
7570 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7571 Result.getComplexFloatReal() = Tmp;
7572 Tmp = LHS_i;
7573 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7574 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7575
7576 Tmp = LHS_r;
7577 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7578 Result.getComplexFloatImag() = Tmp;
7579 Tmp = LHS_i;
7580 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7581 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7582 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007583 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007584 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007585 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7586 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007587 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007588 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7589 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7590 }
7591 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007592 case BO_Div:
7593 if (Result.isComplexFloat()) {
7594 ComplexValue LHS = Result;
7595 APFloat &LHS_r = LHS.getComplexFloatReal();
7596 APFloat &LHS_i = LHS.getComplexFloatImag();
7597 APFloat &RHS_r = RHS.getComplexFloatReal();
7598 APFloat &RHS_i = RHS.getComplexFloatImag();
7599 APFloat &Res_r = Result.getComplexFloatReal();
7600 APFloat &Res_i = Result.getComplexFloatImag();
7601
7602 APFloat Den = RHS_r;
7603 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7604 APFloat Tmp = RHS_i;
7605 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7606 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7607
7608 Res_r = LHS_r;
7609 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7610 Tmp = LHS_i;
7611 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7612 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7613 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7614
7615 Res_i = LHS_i;
7616 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7617 Tmp = LHS_r;
7618 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7619 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7620 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7621 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007622 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7623 return Error(E, diag::note_expr_divide_by_zero);
7624
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007625 ComplexValue LHS = Result;
7626 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7627 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7628 Result.getComplexIntReal() =
7629 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7630 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7631 Result.getComplexIntImag() =
7632 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7633 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7634 }
7635 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007636 }
7637
John McCall93d91dc2010-05-07 17:22:02 +00007638 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007639}
7640
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007641bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7642 // Get the operand value into 'Result'.
7643 if (!Visit(E->getSubExpr()))
7644 return false;
7645
7646 switch (E->getOpcode()) {
7647 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007648 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007649 case UO_Extension:
7650 return true;
7651 case UO_Plus:
7652 // The result is always just the subexpr.
7653 return true;
7654 case UO_Minus:
7655 if (Result.isComplexFloat()) {
7656 Result.getComplexFloatReal().changeSign();
7657 Result.getComplexFloatImag().changeSign();
7658 }
7659 else {
7660 Result.getComplexIntReal() = -Result.getComplexIntReal();
7661 Result.getComplexIntImag() = -Result.getComplexIntImag();
7662 }
7663 return true;
7664 case UO_Not:
7665 if (Result.isComplexFloat())
7666 Result.getComplexFloatImag().changeSign();
7667 else
7668 Result.getComplexIntImag() = -Result.getComplexIntImag();
7669 return true;
7670 }
7671}
7672
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007673bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7674 if (E->getNumInits() == 2) {
7675 if (E->getType()->isComplexType()) {
7676 Result.makeComplexFloat();
7677 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7678 return false;
7679 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7680 return false;
7681 } else {
7682 Result.makeComplexInt();
7683 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7684 return false;
7685 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7686 return false;
7687 }
7688 return true;
7689 }
7690 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7691}
7692
Anders Carlsson537969c2008-11-16 20:27:53 +00007693//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007694// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7695// implicit conversion.
7696//===----------------------------------------------------------------------===//
7697
7698namespace {
7699class AtomicExprEvaluator :
7700 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7701 APValue &Result;
7702public:
7703 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7704 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7705
7706 bool Success(const APValue &V, const Expr *E) {
7707 Result = V;
7708 return true;
7709 }
7710
7711 bool ZeroInitialization(const Expr *E) {
7712 ImplicitValueInitExpr VIE(
7713 E->getType()->castAs<AtomicType>()->getValueType());
7714 return Evaluate(Result, Info, &VIE);
7715 }
7716
7717 bool VisitCastExpr(const CastExpr *E) {
7718 switch (E->getCastKind()) {
7719 default:
7720 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7721 case CK_NonAtomicToAtomic:
7722 return Evaluate(Result, Info, E->getSubExpr());
7723 }
7724 }
7725};
7726} // end anonymous namespace
7727
7728static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7729 assert(E->isRValue() && E->getType()->isAtomicType());
7730 return AtomicExprEvaluator(Info, Result).Visit(E);
7731}
7732
7733//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007734// Void expression evaluation, primarily for a cast to void on the LHS of a
7735// comma operator
7736//===----------------------------------------------------------------------===//
7737
7738namespace {
7739class VoidExprEvaluator
7740 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7741public:
7742 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7743
Richard Smith2e312c82012-03-03 22:46:17 +00007744 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007745
7746 bool VisitCastExpr(const CastExpr *E) {
7747 switch (E->getCastKind()) {
7748 default:
7749 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7750 case CK_ToVoid:
7751 VisitIgnoredValue(E->getSubExpr());
7752 return true;
7753 }
7754 }
7755};
7756} // end anonymous namespace
7757
7758static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7759 assert(E->isRValue() && E->getType()->isVoidType());
7760 return VoidExprEvaluator(Info).Visit(E);
7761}
7762
7763//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007764// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007765//===----------------------------------------------------------------------===//
7766
Richard Smith2e312c82012-03-03 22:46:17 +00007767static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007768 // In C, function designators are not lvalues, but we evaluate them as if they
7769 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00007770 QualType T = E->getType();
7771 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00007772 LValue LV;
7773 if (!EvaluateLValue(E, LV, Info))
7774 return false;
7775 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007776 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007777 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007778 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007779 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007780 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007781 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007782 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00007783 LValue LV;
7784 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007785 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007786 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007787 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00007788 llvm::APFloat F(0.0);
7789 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007790 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007791 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00007792 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00007793 ComplexValue C;
7794 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007795 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007796 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00007797 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007798 MemberPtr P;
7799 if (!EvaluateMemberPointer(E, P, Info))
7800 return false;
7801 P.moveInto(Result);
7802 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00007803 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007804 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007805 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007806 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7807 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007808 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007809 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007810 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007811 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007812 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007813 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7814 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00007815 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00007816 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00007817 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007818 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007819 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007820 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007821 if (!EvaluateVoid(E, Info))
7822 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00007823 } else if (T->isAtomicType()) {
7824 if (!EvaluateAtomic(E, Result, Info))
7825 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007826 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007827 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007828 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007829 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007830 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007831 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007832 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007833
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007834 return true;
7835}
7836
Richard Smithb228a862012-02-15 02:18:13 +00007837/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7838/// cases, the in-place evaluation is essential, since later initializers for
7839/// an object can indirectly refer to subobjects which were initialized earlier.
7840static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007841 const Expr *E, bool AllowNonLiteralTypes) {
7842 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007843 return false;
7844
7845 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007846 // Evaluate arrays and record types in-place, so that later initializers can
7847 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007848 if (E->getType()->isArrayType())
7849 return EvaluateArray(E, This, Result, Info);
7850 else if (E->getType()->isRecordType())
7851 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007852 }
7853
7854 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007855 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007856}
7857
Richard Smithf57d8cb2011-12-09 22:58:01 +00007858/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7859/// lvalue-to-rvalue cast if it is an lvalue.
7860static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007861 if (!CheckLiteralType(Info, E))
7862 return false;
7863
Richard Smith2e312c82012-03-03 22:46:17 +00007864 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007865 return false;
7866
7867 if (E->isGLValue()) {
7868 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007869 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007870 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007871 return false;
7872 }
7873
Richard Smith2e312c82012-03-03 22:46:17 +00007874 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007875 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007876}
Richard Smith11562c52011-10-28 17:51:58 +00007877
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007878static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7879 const ASTContext &Ctx, bool &IsConst) {
7880 // Fast-path evaluations of integer literals, since we sometimes see files
7881 // containing vast quantities of these.
7882 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7883 Result.Val = APValue(APSInt(L->getValue(),
7884 L->getType()->isUnsignedIntegerType()));
7885 IsConst = true;
7886 return true;
7887 }
7888
7889 // FIXME: Evaluating values of large array and record types can cause
7890 // performance problems. Only do so in C++11 for now.
7891 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7892 Exp->getType()->isRecordType()) &&
7893 !Ctx.getLangOpts().CPlusPlus11) {
7894 IsConst = false;
7895 return true;
7896 }
7897 return false;
7898}
7899
7900
Richard Smith7b553f12011-10-29 00:50:52 +00007901/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007902/// any crazy technique (that has nothing to do with language standards) that
7903/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007904/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7905/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007906bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007907 bool IsConst;
7908 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7909 return IsConst;
7910
Richard Smithf57d8cb2011-12-09 22:58:01 +00007911 EvalInfo Info(Ctx, Result);
7912 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007913}
7914
Jay Foad39c79802011-01-12 09:06:06 +00007915bool Expr::EvaluateAsBooleanCondition(bool &Result,
7916 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007917 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007918 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007919 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007920}
7921
Richard Smith5fab0c92011-12-28 19:48:30 +00007922bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7923 SideEffectsKind AllowSideEffects) const {
7924 if (!getType()->isIntegralOrEnumerationType())
7925 return false;
7926
Richard Smith11562c52011-10-28 17:51:58 +00007927 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007928 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7929 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007930 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007931
Richard Smith11562c52011-10-28 17:51:58 +00007932 Result = ExprResult.Val.getInt();
7933 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007934}
7935
Jay Foad39c79802011-01-12 09:06:06 +00007936bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007937 EvalInfo Info(Ctx, Result);
7938
John McCall45d55e42010-05-07 21:00:08 +00007939 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007940 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7941 !CheckLValueConstantExpression(Info, getExprLoc(),
7942 Ctx.getLValueReferenceType(getType()), LV))
7943 return false;
7944
Richard Smith2e312c82012-03-03 22:46:17 +00007945 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007946 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007947}
7948
Richard Smithd0b4dd62011-12-19 06:19:21 +00007949bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7950 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007951 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007952 // FIXME: Evaluating initializers for large array and record types can cause
7953 // performance problems. Only do so in C++11 for now.
7954 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007955 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007956 return false;
7957
Richard Smithd0b4dd62011-12-19 06:19:21 +00007958 Expr::EvalStatus EStatus;
7959 EStatus.Diag = &Notes;
7960
7961 EvalInfo InitInfo(Ctx, EStatus);
7962 InitInfo.setEvaluatingDecl(VD, Value);
7963
7964 LValue LVal;
7965 LVal.set(VD);
7966
Richard Smithfddd3842011-12-30 21:15:51 +00007967 // C++11 [basic.start.init]p2:
7968 // Variables with static storage duration or thread storage duration shall be
7969 // zero-initialized before any other initialization takes place.
7970 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007971 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007972 !VD->getType()->isReferenceType()) {
7973 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007974 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007975 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007976 return false;
7977 }
7978
Richard Smith7525ff62013-05-09 07:14:00 +00007979 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7980 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007981 EStatus.HasSideEffects)
7982 return false;
7983
7984 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7985 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007986}
7987
Richard Smith7b553f12011-10-29 00:50:52 +00007988/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7989/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007990bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007991 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007992 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007993}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007994
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007995APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007996 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007997 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007998 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007999 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008000 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008001 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008002 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008003
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008004 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008005}
John McCall864e3962010-05-07 05:32:02 +00008006
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008007void Expr::EvaluateForOverflow(const ASTContext &Ctx,
8008 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
8009 bool IsConst;
8010 EvalResult EvalResult;
8011 EvalResult.Diag = Diags;
8012 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8013 EvalInfo Info(Ctx, EvalResult, true);
8014 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8015 }
8016}
8017
Richard Smithe6c01442013-06-05 00:46:14 +00008018bool Expr::EvalResult::isGlobalLValue() const {
8019 assert(Val.isLValue());
8020 return IsGlobalLValue(Val.getLValueBase());
8021}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008022
8023
John McCall864e3962010-05-07 05:32:02 +00008024/// isIntegerConstantExpr - this recursive routine will test if an expression is
8025/// an integer constant expression.
8026
8027/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8028/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008029
8030// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008031// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8032// and a (possibly null) SourceLocation indicating the location of the problem.
8033//
John McCall864e3962010-05-07 05:32:02 +00008034// Note that to reduce code duplication, this helper does no evaluation
8035// itself; the caller checks whether the expression is evaluatable, and
8036// in the rare cases where CheckICE actually cares about the evaluated
8037// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008038
Dan Gohman28ade552010-07-26 21:25:24 +00008039namespace {
8040
Richard Smith9e575da2012-12-28 13:25:52 +00008041enum ICEKind {
8042 /// This expression is an ICE.
8043 IK_ICE,
8044 /// This expression is not an ICE, but if it isn't evaluated, it's
8045 /// a legal subexpression for an ICE. This return value is used to handle
8046 /// the comma operator in C99 mode, and non-constant subexpressions.
8047 IK_ICEIfUnevaluated,
8048 /// This expression is not an ICE, and is not a legal subexpression for one.
8049 IK_NotICE
8050};
8051
John McCall864e3962010-05-07 05:32:02 +00008052struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008053 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008054 SourceLocation Loc;
8055
Richard Smith9e575da2012-12-28 13:25:52 +00008056 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008057};
8058
Dan Gohman28ade552010-07-26 21:25:24 +00008059}
8060
Richard Smith9e575da2012-12-28 13:25:52 +00008061static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8062
8063static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008064
Craig Toppera31a8822013-08-22 07:09:37 +00008065static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008066 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008067 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008068 !EVResult.Val.isInt())
8069 return ICEDiag(IK_NotICE, E->getLocStart());
8070
John McCall864e3962010-05-07 05:32:02 +00008071 return NoDiag();
8072}
8073
Craig Toppera31a8822013-08-22 07:09:37 +00008074static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008075 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008076 if (!E->getType()->isIntegralOrEnumerationType())
8077 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008078
8079 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008080#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008081#define STMT(Node, Base) case Expr::Node##Class:
8082#define EXPR(Node, Base)
8083#include "clang/AST/StmtNodes.inc"
8084 case Expr::PredefinedExprClass:
8085 case Expr::FloatingLiteralClass:
8086 case Expr::ImaginaryLiteralClass:
8087 case Expr::StringLiteralClass:
8088 case Expr::ArraySubscriptExprClass:
8089 case Expr::MemberExprClass:
8090 case Expr::CompoundAssignOperatorClass:
8091 case Expr::CompoundLiteralExprClass:
8092 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008093 case Expr::DesignatedInitExprClass:
8094 case Expr::ImplicitValueInitExprClass:
8095 case Expr::ParenListExprClass:
8096 case Expr::VAArgExprClass:
8097 case Expr::AddrLabelExprClass:
8098 case Expr::StmtExprClass:
8099 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008100 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008101 case Expr::CXXDynamicCastExprClass:
8102 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008103 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008104 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008105 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008106 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008107 case Expr::CXXThisExprClass:
8108 case Expr::CXXThrowExprClass:
8109 case Expr::CXXNewExprClass:
8110 case Expr::CXXDeleteExprClass:
8111 case Expr::CXXPseudoDestructorExprClass:
8112 case Expr::UnresolvedLookupExprClass:
8113 case Expr::DependentScopeDeclRefExprClass:
8114 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008115 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008116 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008117 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008118 case Expr::CXXTemporaryObjectExprClass:
8119 case Expr::CXXUnresolvedConstructExprClass:
8120 case Expr::CXXDependentScopeMemberExprClass:
8121 case Expr::UnresolvedMemberExprClass:
8122 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008123 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008124 case Expr::ObjCArrayLiteralClass:
8125 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008126 case Expr::ObjCEncodeExprClass:
8127 case Expr::ObjCMessageExprClass:
8128 case Expr::ObjCSelectorExprClass:
8129 case Expr::ObjCProtocolExprClass:
8130 case Expr::ObjCIvarRefExprClass:
8131 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008132 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008133 case Expr::ObjCIsaExprClass:
8134 case Expr::ShuffleVectorExprClass:
8135 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008136 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008137 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008138 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008139 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008140 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008141 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008142 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008143 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008144 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008145 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00008146 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008147 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008148 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008149
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008150 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008151 case Expr::GNUNullExprClass:
8152 // GCC considers the GNU __null value to be an integral constant expression.
8153 return NoDiag();
8154
John McCall7c454bb2011-07-15 05:09:51 +00008155 case Expr::SubstNonTypeTemplateParmExprClass:
8156 return
8157 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8158
John McCall864e3962010-05-07 05:32:02 +00008159 case Expr::ParenExprClass:
8160 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008161 case Expr::GenericSelectionExprClass:
8162 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008163 case Expr::IntegerLiteralClass:
8164 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008165 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008166 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008167 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00008168 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00008169 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008170 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008171 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008172 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008173 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008174 return NoDiag();
8175 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008176 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008177 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8178 // constant expressions, but they can never be ICEs because an ICE cannot
8179 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008180 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008181 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00008182 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008183 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008184 }
Richard Smith6365c912012-02-24 22:12:32 +00008185 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008186 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8187 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008188 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008189 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008190 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008191 // Parameter variables are never constants. Without this check,
8192 // getAnyInitializer() can find a default argument, which leads
8193 // to chaos.
8194 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008195 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008196
8197 // C++ 7.1.5.1p2
8198 // A variable of non-volatile const-qualified integral or enumeration
8199 // type initialized by an ICE can be used in ICEs.
8200 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008201 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008202 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008203
Richard Smithd0b4dd62011-12-19 06:19:21 +00008204 const VarDecl *VD;
8205 // Look for a declaration of this variable that has an initializer, and
8206 // check whether it is an ICE.
8207 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8208 return NoDiag();
8209 else
Richard Smith9e575da2012-12-28 13:25:52 +00008210 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008211 }
8212 }
Richard Smith9e575da2012-12-28 13:25:52 +00008213 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008214 }
John McCall864e3962010-05-07 05:32:02 +00008215 case Expr::UnaryOperatorClass: {
8216 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8217 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008218 case UO_PostInc:
8219 case UO_PostDec:
8220 case UO_PreInc:
8221 case UO_PreDec:
8222 case UO_AddrOf:
8223 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008224 // C99 6.6/3 allows increment and decrement within unevaluated
8225 // subexpressions of constant expressions, but they can never be ICEs
8226 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008227 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008228 case UO_Extension:
8229 case UO_LNot:
8230 case UO_Plus:
8231 case UO_Minus:
8232 case UO_Not:
8233 case UO_Real:
8234 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008235 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008236 }
Richard Smith9e575da2012-12-28 13:25:52 +00008237
John McCall864e3962010-05-07 05:32:02 +00008238 // OffsetOf falls through here.
8239 }
8240 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008241 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8242 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8243 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8244 // compliance: we should warn earlier for offsetof expressions with
8245 // array subscripts that aren't ICEs, and if the array subscripts
8246 // are ICEs, the value of the offsetof must be an integer constant.
8247 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008248 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008249 case Expr::UnaryExprOrTypeTraitExprClass: {
8250 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8251 if ((Exp->getKind() == UETT_SizeOf) &&
8252 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008253 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008254 return NoDiag();
8255 }
8256 case Expr::BinaryOperatorClass: {
8257 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8258 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008259 case BO_PtrMemD:
8260 case BO_PtrMemI:
8261 case BO_Assign:
8262 case BO_MulAssign:
8263 case BO_DivAssign:
8264 case BO_RemAssign:
8265 case BO_AddAssign:
8266 case BO_SubAssign:
8267 case BO_ShlAssign:
8268 case BO_ShrAssign:
8269 case BO_AndAssign:
8270 case BO_XorAssign:
8271 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008272 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8273 // constant expressions, but they can never be ICEs because an ICE cannot
8274 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008275 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008276
John McCalle3027922010-08-25 11:45:40 +00008277 case BO_Mul:
8278 case BO_Div:
8279 case BO_Rem:
8280 case BO_Add:
8281 case BO_Sub:
8282 case BO_Shl:
8283 case BO_Shr:
8284 case BO_LT:
8285 case BO_GT:
8286 case BO_LE:
8287 case BO_GE:
8288 case BO_EQ:
8289 case BO_NE:
8290 case BO_And:
8291 case BO_Xor:
8292 case BO_Or:
8293 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008294 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8295 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008296 if (Exp->getOpcode() == BO_Div ||
8297 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008298 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008299 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008300 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008301 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008302 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008303 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008304 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008305 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008306 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008307 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008308 }
8309 }
8310 }
John McCalle3027922010-08-25 11:45:40 +00008311 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008312 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008313 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8314 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008315 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8316 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008317 } else {
8318 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008319 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008320 }
8321 }
Richard Smith9e575da2012-12-28 13:25:52 +00008322 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008323 }
John McCalle3027922010-08-25 11:45:40 +00008324 case BO_LAnd:
8325 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008326 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8327 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008328 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008329 // Rare case where the RHS has a comma "side-effect"; we need
8330 // to actually check the condition to see whether the side
8331 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008332 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008333 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008334 return RHSResult;
8335 return NoDiag();
8336 }
8337
Richard Smith9e575da2012-12-28 13:25:52 +00008338 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008339 }
8340 }
8341 }
8342 case Expr::ImplicitCastExprClass:
8343 case Expr::CStyleCastExprClass:
8344 case Expr::CXXFunctionalCastExprClass:
8345 case Expr::CXXStaticCastExprClass:
8346 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008347 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008348 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008349 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008350 if (isa<ExplicitCastExpr>(E)) {
8351 if (const FloatingLiteral *FL
8352 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8353 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8354 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8355 APSInt IgnoredVal(DestWidth, !DestSigned);
8356 bool Ignored;
8357 // If the value does not fit in the destination type, the behavior is
8358 // undefined, so we are not required to treat it as a constant
8359 // expression.
8360 if (FL->getValue().convertToInteger(IgnoredVal,
8361 llvm::APFloat::rmTowardZero,
8362 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008363 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008364 return NoDiag();
8365 }
8366 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008367 switch (cast<CastExpr>(E)->getCastKind()) {
8368 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008369 case CK_AtomicToNonAtomic:
8370 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008371 case CK_NoOp:
8372 case CK_IntegralToBoolean:
8373 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008374 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008375 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008376 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008377 }
John McCall864e3962010-05-07 05:32:02 +00008378 }
John McCallc07a0c72011-02-17 10:25:35 +00008379 case Expr::BinaryConditionalOperatorClass: {
8380 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8381 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008382 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008383 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008384 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8385 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8386 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008387 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008388 return FalseResult;
8389 }
John McCall864e3962010-05-07 05:32:02 +00008390 case Expr::ConditionalOperatorClass: {
8391 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8392 // If the condition (ignoring parens) is a __builtin_constant_p call,
8393 // then only the true side is actually considered in an integer constant
8394 // expression, and it is fully evaluated. This is an important GNU
8395 // extension. See GCC PR38377 for discussion.
8396 if (const CallExpr *CallCE
8397 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00008398 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8399 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008400 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008401 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008402 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008403
Richard Smithf57d8cb2011-12-09 22:58:01 +00008404 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8405 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008406
Richard Smith9e575da2012-12-28 13:25:52 +00008407 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008408 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008409 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008410 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008411 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008412 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008413 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008414 return NoDiag();
8415 // Rare case where the diagnostics depend on which side is evaluated
8416 // Note that if we get here, CondResult is 0, and at least one of
8417 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008418 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008419 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008420 return TrueResult;
8421 }
8422 case Expr::CXXDefaultArgExprClass:
8423 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008424 case Expr::CXXDefaultInitExprClass:
8425 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008426 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008427 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008428 }
8429 }
8430
David Blaikiee4d798f2012-01-20 21:50:17 +00008431 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008432}
8433
Richard Smithf57d8cb2011-12-09 22:58:01 +00008434/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008435static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008436 const Expr *E,
8437 llvm::APSInt *Value,
8438 SourceLocation *Loc) {
8439 if (!E->getType()->isIntegralOrEnumerationType()) {
8440 if (Loc) *Loc = E->getExprLoc();
8441 return false;
8442 }
8443
Richard Smith66e05fe2012-01-18 05:21:49 +00008444 APValue Result;
8445 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008446 return false;
8447
Richard Smith66e05fe2012-01-18 05:21:49 +00008448 assert(Result.isInt() && "pointer cast to int is not an ICE");
8449 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008450 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008451}
8452
Craig Toppera31a8822013-08-22 07:09:37 +00008453bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8454 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008455 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008456 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8457
Richard Smith9e575da2012-12-28 13:25:52 +00008458 ICEDiag D = CheckICE(this, Ctx);
8459 if (D.Kind != IK_ICE) {
8460 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008461 return false;
8462 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008463 return true;
8464}
8465
Craig Toppera31a8822013-08-22 07:09:37 +00008466bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008467 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008468 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008469 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8470
8471 if (!isIntegerConstantExpr(Ctx, Loc))
8472 return false;
8473 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008474 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008475 return true;
8476}
Richard Smith66e05fe2012-01-18 05:21:49 +00008477
Craig Toppera31a8822013-08-22 07:09:37 +00008478bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008479 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008480}
8481
Craig Toppera31a8822013-08-22 07:09:37 +00008482bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008483 SourceLocation *Loc) const {
8484 // We support this checking in C++98 mode in order to diagnose compatibility
8485 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008486 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008487
Richard Smith98a0a492012-02-14 21:38:30 +00008488 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008489 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008490 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008491 Status.Diag = &Diags;
8492 EvalInfo Info(Ctx, Status);
8493
8494 APValue Scratch;
8495 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8496
8497 if (!Diags.empty()) {
8498 IsConstExpr = false;
8499 if (Loc) *Loc = Diags[0].first;
8500 } else if (!IsConstExpr) {
8501 // FIXME: This shouldn't happen.
8502 if (Loc) *Loc = getExprLoc();
8503 }
8504
8505 return IsConstExpr;
8506}
Richard Smith253c2a32012-01-27 01:14:48 +00008507
8508bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008509 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008510 PartialDiagnosticAt> &Diags) {
8511 // FIXME: It would be useful to check constexpr function templates, but at the
8512 // moment the constant expression evaluator cannot cope with the non-rigorous
8513 // ASTs which we build for dependent expressions.
8514 if (FD->isDependentContext())
8515 return true;
8516
8517 Expr::EvalStatus Status;
8518 Status.Diag = &Diags;
8519
8520 EvalInfo Info(FD->getASTContext(), Status);
8521 Info.CheckingPotentialConstantExpression = true;
8522
8523 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8524 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8525
Richard Smith7525ff62013-05-09 07:14:00 +00008526 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008527 // is a temporary being used as the 'this' pointer.
8528 LValue This;
8529 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008530 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008531
Richard Smith253c2a32012-01-27 01:14:48 +00008532 ArrayRef<const Expr*> Args;
8533
8534 SourceLocation Loc = FD->getLocation();
8535
Richard Smith2e312c82012-03-03 22:46:17 +00008536 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008537 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8538 // Evaluate the call as a constant initializer, to allow the construction
8539 // of objects of non-literal types.
8540 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008541 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008542 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008543 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8544 Args, FD->getBody(), Info, Scratch);
8545
8546 return Diags.empty();
8547}