blob: 8aea10d516e9ae790eb40b8d1138692b502be39f [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 {
Richard Smith33b44ab2014-07-23 23:50:25 +0000204 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 if (IsOnePastTheEnd)
206 return true;
207 if (MostDerivedArraySize &&
208 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209 return true;
210 return false;
211 }
212
213 /// Check that this refers to a valid subobject.
214 bool isValidSubobject() const {
215 if (Invalid)
216 return false;
217 return !isOnePastTheEnd();
218 }
219 /// Check that this refers to a valid subobject, and if not, produce a
220 /// relevant diagnostic and set the designator as invalid.
221 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222
223 /// Update this designator to refer to the first element within this array.
224 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000225 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000227 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000228
229 // This is a most-derived object.
230 MostDerivedType = CAT->getElementType();
231 MostDerivedArraySize = CAT->getSize().getZExtValue();
232 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000233 }
234 /// Update this designator to refer to the given base or member of this
235 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000237 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000238 APValue::BaseOrMemberType Value(D, Virtual);
239 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000240 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000241
242 // If this isn't a base class, it's a new most-derived object.
243 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244 MostDerivedType = FD->getType();
245 MostDerivedArraySize = 0;
246 MostDerivedPathLength = Entries.size();
247 }
Richard Smith96e0c102011-11-04 02:25:55 +0000248 }
Richard Smith66c96992012-02-18 22:04:06 +0000249 /// Update this designator to refer to the given complex component.
250 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 PathEntry Entry;
252 Entry.ArrayIndex = Imag;
253 Entries.push_back(Entry);
254
255 // This is technically a most-derived object, though in practice this
256 // is unlikely to matter.
257 MostDerivedType = EltTy;
258 MostDerivedArraySize = 2;
259 MostDerivedPathLength = Entries.size();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000264 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000266 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269 setInvalid();
270 }
Richard Smith96e0c102011-11-04 02:25:55 +0000271 return;
272 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000273 // [expr.add]p4: For the purposes of these operators, a pointer to a
274 // nonarray object behaves the same as a pointer to the first element of
275 // an array of length one with the type of the object as its element type.
276 if (IsOnePastTheEnd && N == (uint64_t)-1)
277 IsOnePastTheEnd = false;
278 else if (!IsOnePastTheEnd && N == 1)
279 IsOnePastTheEnd = true;
280 else if (N != 0) {
281 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000282 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000283 }
Richard Smith96e0c102011-11-04 02:25:55 +0000284 }
285 };
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// A stack frame in the constexpr call stack.
288 struct CallStackFrame {
289 EvalInfo &Info;
290
291 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000292 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000293
Richard Smithf6f003a2011-12-16 19:06:07 +0000294 /// CallLoc - The location of the call expression for this call.
295 SourceLocation CallLoc;
296
297 /// Callee - The function which was called.
298 const FunctionDecl *Callee;
299
Richard Smithb228a862012-02-15 02:18:13 +0000300 /// Index - The call index of this call.
301 unsigned Index;
302
Richard Smithd62306a2011-11-10 06:34:14 +0000303 /// This - The binding for the this pointer in this call, if any.
304 const LValue *This;
305
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000306 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000308 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000309
Eli Friedman4830ec82012-06-25 21:21:08 +0000310 // Note that we intentionally use std::map here so that references to
311 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000312 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 typedef MapTy::const_iterator temp_iterator;
314 /// Temporaries - Temporary lvalues materialized within this stack frame.
315 MapTy Temporaries;
316
Richard Smithf6f003a2011-12-16 19:06:07 +0000317 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000319 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000320 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000321
322 APValue *getTemporary(const void *Key) {
323 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000324 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000325 }
326 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000327 };
328
Richard Smith852c9db2013-04-20 22:23:05 +0000329 /// Temporarily override 'this'.
330 class ThisOverrideRAII {
331 public:
332 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333 : Frame(Frame), OldThis(Frame.This) {
334 if (Enable)
335 Frame.This = NewThis;
336 }
337 ~ThisOverrideRAII() {
338 Frame.This = OldThis;
339 }
340 private:
341 CallStackFrame &Frame;
342 const LValue *OldThis;
343 };
344
Richard Smith92b1ce02011-12-12 09:28:41 +0000345 /// A partial diagnostic which we might know in advance that we are not going
346 /// to emit.
347 class OptionalDiagnostic {
348 PartialDiagnostic *Diag;
349
350 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000351 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000353
354 template<typename T>
355 OptionalDiagnostic &operator<<(const T &v) {
356 if (Diag)
357 *Diag << v;
358 return *this;
359 }
Richard Smithfe800032012-01-31 04:08:20 +0000360
361 OptionalDiagnostic &operator<<(const APSInt &I) {
362 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000363 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000364 I.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
369
370 OptionalDiagnostic &operator<<(const APFloat &F) {
371 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000372 // FIXME: Force the precision of the source value down so we don't
373 // print digits which are usually useless (we don't really care here if
374 // we truncate a digit by accident in edge cases). Ideally,
375 // APFloat::toString would automatically print the shortest
376 // representation which rounds to the correct value, but it's a bit
377 // tricky to implement.
378 unsigned precision =
379 llvm::APFloat::semanticsPrecision(F.getSemantics());
380 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000381 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000382 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000383 *Diag << StringRef(Buffer.data(), Buffer.size());
384 }
385 return *this;
386 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 };
388
Richard Smith08d6a2c2013-07-24 07:11:57 +0000389 /// A cleanup, and a flag indicating whether it is lifetime-extended.
390 class Cleanup {
391 llvm::PointerIntPair<APValue*, 1, bool> Value;
392
393 public:
394 Cleanup(APValue *Val, bool IsLifetimeExtended)
395 : Value(Val, IsLifetimeExtended) {}
396
397 bool isLifetimeExtended() const { return Value.getInt(); }
398 void endLifetime() {
399 *Value.getPointer() = APValue();
400 }
401 };
402
Richard Smithb228a862012-02-15 02:18:13 +0000403 /// EvalInfo - This is a private struct used by the evaluator to capture
404 /// information about a subexpression as it is folded. It retains information
405 /// about the AST context, but also maintains information about the folded
406 /// expression.
407 ///
408 /// If an expression could be evaluated, it is still possible it is not a C
409 /// "integer constant expression" or constant expression. If not, this struct
410 /// captures information about how and why not.
411 ///
412 /// One bit of information passed *into* the request for constant folding
413 /// indicates whether the subexpression is "evaluated" or not according to C
414 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415 /// evaluate the expression regardless of what the RHS is, but C only allows
416 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000417 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000418 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000419
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420 /// EvalStatus - Contains information about the evaluation.
421 Expr::EvalStatus &EvalStatus;
422
423 /// CurrentCall - The top of the constexpr call stack.
424 CallStackFrame *CurrentCall;
425
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000426 /// CallStackDepth - The number of calls in the call stack right now.
427 unsigned CallStackDepth;
428
Richard Smithb228a862012-02-15 02:18:13 +0000429 /// NextCallIndex - The next call index to assign.
430 unsigned NextCallIndex;
431
Richard Smitha3d3bd22013-05-08 02:12:03 +0000432 /// StepsLeft - The remaining number of evaluation steps we're permitted
433 /// to perform. This is essentially a limit for the number of statements
434 /// we will evaluate.
435 unsigned StepsLeft;
436
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000438 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 CallStackFrame BottomFrame;
440
Richard Smith08d6a2c2013-07-24 07:11:57 +0000441 /// A stack of values whose lifetimes end at the end of some surrounding
442 /// evaluation frame.
443 llvm::SmallVector<Cleanup, 16> CleanupStack;
444
Richard Smithd62306a2011-11-10 06:34:14 +0000445 /// EvaluatingDecl - This is the declaration whose initializer is being
446 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000447 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000448
449 /// EvaluatingDeclValue - This is the value being constructed for the
450 /// declaration whose initializer is being evaluated, if any.
451 APValue *EvaluatingDeclValue;
452
Richard Smith357362d2011-12-13 06:39:58 +0000453 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454 /// notes attached to it will also be stored, otherwise they will not be.
455 bool HasActiveDiagnostic;
456
Richard Smith6d4c6582013-11-05 22:18:15 +0000457 enum EvaluationMode {
458 /// Evaluate as a constant expression. Stop if we find that the expression
459 /// is not a constant expression.
460 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461
Richard Smith6d4c6582013-11-05 22:18:15 +0000462 /// Evaluate as a potential constant expression. Keep going if we hit a
463 /// construct that we can't evaluate yet (because we don't yet know the
464 /// value of something) but stop if we hit something that could never be
465 /// a constant expression.
466 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000467
Richard Smith6d4c6582013-11-05 22:18:15 +0000468 /// Fold the expression to a constant. Stop if we hit a side-effect that
469 /// we can't model.
470 EM_ConstantFold,
471
472 /// Evaluate the expression looking for integer overflow and similar
473 /// issues. Don't worry about side-effects, and try to visit all
474 /// subexpressions.
475 EM_EvaluateForOverflow,
476
477 /// Evaluate in any way we know how. Don't worry about side-effects that
478 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000479 EM_IgnoreSideEffects,
480
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression. Some expressions can be retried in the
483 /// optimizer if we don't constant fold them here, but in an unevaluated
484 /// context we try to fold them immediately since the optimizer never
485 /// gets a chance to look at it.
486 EM_ConstantExpressionUnevaluated,
487
488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression. Some expressions can be retried in the
492 /// optimizer if we don't constant fold them here, but in an unevaluated
493 /// context we try to fold them immediately since the optimizer never
494 /// gets a chance to look at it.
495 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000496 } EvalMode;
497
498 /// Are we checking whether the expression is a potential constant
499 /// expression?
500 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000501 return EvalMode == EM_PotentialConstantExpression ||
502 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000503 }
504
505 /// Are we checking an expression for overflow?
506 // FIXME: We should check for any kind of undefined or suspicious behavior
507 // in such constructs, not just overflow.
508 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509
510 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000511 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000512 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000513 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000514 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515 EvaluatingDecl((const ValueDecl *)nullptr),
516 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000518
Richard Smith7525ff62013-05-09 07:14:00 +0000519 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000521 EvaluatingDeclValue = &Value;
522 }
523
David Blaikiebbafb8a2012-03-11 07:00:24 +0000524 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000525
Richard Smith357362d2011-12-13 06:39:58 +0000526 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000527 // Don't perform any constexpr calls (other than the call we're checking)
528 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000529 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000530 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000531 if (NextCallIndex == 0) {
532 // NextCallIndex has wrapped around.
533 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534 return false;
535 }
Richard Smith357362d2011-12-13 06:39:58 +0000536 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537 return true;
538 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539 << getLangOpts().ConstexprCallDepth;
540 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000541 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000542
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackFrame *getCallFrame(unsigned CallIndex) {
544 assert(CallIndex && "no call index in getCallFrame");
545 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546 // be null in this loop.
547 CallStackFrame *Frame = CurrentCall;
548 while (Frame->Index > CallIndex)
549 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000551 }
552
Richard Smitha3d3bd22013-05-08 02:12:03 +0000553 bool nextStep(const Stmt *S) {
554 if (!StepsLeft) {
555 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556 return false;
557 }
558 --StepsLeft;
559 return true;
560 }
561
Richard Smith357362d2011-12-13 06:39:58 +0000562 private:
563 /// Add a diagnostic to the diagnostics list.
564 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567 return EvalStatus.Diag->back().second;
568 }
569
Richard Smithf6f003a2011-12-16 19:06:07 +0000570 /// Add notes containing a call stack to the current point of evaluation.
571 void addCallStack(unsigned Limit);
572
Richard Smith357362d2011-12-13 06:39:58 +0000573 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000575 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000577 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 // If we have a prior diagnostic, it will be noting that the expression
580 // isn't a constant expression. This diagnostic is more important,
581 // unless we require this evaluation to produce a constant expression.
582 //
583 // FIXME: We might want to show both diagnostics to the user in
584 // EM_ConstantFold mode.
585 if (!EvalStatus.Diag->empty()) {
586 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000587 case EM_ConstantFold:
588 case EM_IgnoreSideEffects:
589 case EM_EvaluateForOverflow:
590 if (!EvalStatus.HasSideEffects)
591 break;
592 // We've had side-effects; we want the diagnostic from them, not
593 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000594 case EM_ConstantExpression:
595 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000596 case EM_ConstantExpressionUnevaluated:
597 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 HasActiveDiagnostic = false;
599 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000600 }
601 }
602
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 unsigned CallStackNotes = CallStackDepth - 1;
604 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605 if (Limit)
606 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000607 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000608 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000609
Richard Smith357362d2011-12-13 06:39:58 +0000610 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000611 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000612 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000614 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000615 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000617 }
Richard Smith357362d2011-12-13 06:39:58 +0000618 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000619 return OptionalDiagnostic();
620 }
621
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623 = diag::note_invalid_subexpr_in_const_expr,
624 unsigned ExtraNotes = 0) {
625 if (EvalStatus.Diag)
626 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627 HasActiveDiagnostic = false;
628 return OptionalDiagnostic();
629 }
630
Richard Smith92b1ce02011-12-12 09:28:41 +0000631 /// Diagnose that the evaluation does not produce a C++11 core constant
632 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000633 ///
634 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000636 template<typename LocArg>
637 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000638 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000639 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000640 // Don't override a previous diagnostic. Don't bother collecting
641 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000642 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000643 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 return Diag(Loc, DiagId, ExtraNotes);
647 }
648
649 /// Add a note to a prior diagnostic.
650 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651 if (!HasActiveDiagnostic)
652 return OptionalDiagnostic();
653 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000654 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000655
656 /// Add a stack of notes to a prior diagnostic.
657 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658 if (HasActiveDiagnostic) {
659 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660 Diags.begin(), Diags.end());
661 }
662 }
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Should we continue evaluation after encountering a side-effect that we
665 /// couldn't model?
666 bool keepEvaluatingAfterSideEffect() {
667 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000668 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000669 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000670 case EM_EvaluateForOverflow:
671 case EM_IgnoreSideEffects:
672 return true;
673
Richard Smith6d4c6582013-11-05 22:18:15 +0000674 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 case EM_ConstantFold:
677 return false;
678 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000679 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000680 }
681
682 /// Note that we have had a side-effect, and determine whether we should
683 /// keep evaluating.
684 bool noteSideEffect() {
685 EvalStatus.HasSideEffects = true;
686 return keepEvaluatingAfterSideEffect();
687 }
688
Richard Smith253c2a32012-01-27 01:14:48 +0000689 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000691 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 if (!StepsLeft)
693 return false;
694
695 switch (EvalMode) {
696 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_EvaluateForOverflow:
699 return true;
700
701 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_ConstantFold:
704 case EM_IgnoreSideEffects:
705 return false;
706 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000707 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000708 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000709 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000710
711 /// Object used to treat all foldable expressions as constant expressions.
712 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000714 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 bool HadNoPriorDiags;
716 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000717
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 explicit FoldConstant(EvalInfo &Info, bool Enabled)
719 : Info(Info),
720 Enabled(Enabled),
721 HadNoPriorDiags(Info.EvalStatus.Diag &&
722 Info.EvalStatus.Diag->empty() &&
723 !Info.EvalStatus.HasSideEffects),
724 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000725 if (Enabled &&
726 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000729 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 void keepDiagnostics() { Enabled = false; }
731 ~FoldConstant() {
732 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000733 !Info.EvalStatus.HasSideEffects)
734 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000736 }
737 };
Richard Smith17100ba2012-02-16 02:46:34 +0000738
739 /// RAII object used to suppress diagnostics and side-effects from a
740 /// speculative evaluation.
741 class SpeculativeEvaluationRAII {
742 EvalInfo &Info;
743 Expr::EvalStatus Old;
744
745 public:
746 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000747 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000748 : Info(Info), Old(Info.EvalStatus) {
749 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 // If we're speculatively evaluating, we may have skipped over some
751 // evaluations and missed out a side effect.
752 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000753 }
754 ~SpeculativeEvaluationRAII() {
755 Info.EvalStatus = Old;
756 }
757 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000758
759 /// RAII object wrapping a full-expression or block scope, and handling
760 /// the ending of the lifetime of temporaries created within it.
761 template<bool IsFullExpression>
762 class ScopeRAII {
763 EvalInfo &Info;
764 unsigned OldStackSize;
765 public:
766 ScopeRAII(EvalInfo &Info)
767 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768 ~ScopeRAII() {
769 // Body moved to a static method to encourage the compiler to inline away
770 // instances of this class.
771 cleanup(Info, OldStackSize);
772 }
773 private:
774 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775 unsigned NewEnd = OldStackSize;
776 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777 I != N; ++I) {
778 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779 // Full-expression cleanup of a lifetime-extended temporary: nothing
780 // to do, just move this cleanup to the right place in the stack.
781 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782 ++NewEnd;
783 } else {
784 // End the lifetime of the object.
785 Info.CleanupStack[I].endLifetime();
786 }
787 }
788 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789 Info.CleanupStack.end());
790 }
791 };
792 typedef ScopeRAII<false> BlockScopeRAII;
793 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000794}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000795
Richard Smitha8105bc2012-01-06 16:39:00 +0000796bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797 CheckSubobjectKind CSK) {
798 if (Invalid)
799 return false;
800 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000801 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000802 << CSK;
803 setInvalid();
804 return false;
805 }
806 return true;
807}
808
809void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810 const Expr *E, uint64_t N) {
811 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000812 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000813 << static_cast<int>(N) << /*array*/ 0
814 << static_cast<unsigned>(MostDerivedArraySize);
815 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000816 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000817 << static_cast<int>(N) << /*non-array*/ 1;
818 setInvalid();
819}
820
Richard Smithf6f003a2011-12-16 19:06:07 +0000821CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000823 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000824 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000825 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000826 Info.CurrentCall = this;
827 ++Info.CallStackDepth;
828}
829
830CallStackFrame::~CallStackFrame() {
831 assert(Info.CurrentCall == this && "calls retired out of order");
832 --Info.CallStackDepth;
833 Info.CurrentCall = Caller;
834}
835
Richard Smith08d6a2c2013-07-24 07:11:57 +0000836APValue &CallStackFrame::createTemporary(const void *Key,
837 bool IsLifetimeExtended) {
838 APValue &Result = Temporaries[Key];
839 assert(Result.isUninit() && "temporary created multiple times");
840 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841 return Result;
842}
843
Richard Smith84401042013-06-03 05:03:02 +0000844static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000845
846void EvalInfo::addCallStack(unsigned Limit) {
847 // Determine which calls to skip, if any.
848 unsigned ActiveCalls = CallStackDepth - 1;
849 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850 if (Limit && Limit < ActiveCalls) {
851 SkipStart = Limit / 2 + Limit % 2;
852 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000853 }
854
Richard Smithf6f003a2011-12-16 19:06:07 +0000855 // Walk the call stack and add the diagnostics.
856 unsigned CallIdx = 0;
857 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858 Frame = Frame->Caller, ++CallIdx) {
859 // Skip this call?
860 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861 if (CallIdx == SkipStart) {
862 // Note that we're skipping calls.
863 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864 << unsigned(ActiveCalls - Limit);
865 }
866 continue;
867 }
868
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000869 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 llvm::raw_svector_ostream Out(Buffer);
871 describeCall(Frame, Out);
872 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873 }
874}
875
876namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000877 struct ComplexValue {
878 private:
879 bool IsInt;
880
881 public:
882 APSInt IntReal, IntImag;
883 APFloat FloatReal, FloatImag;
884
885 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886
887 void makeComplexFloat() { IsInt = false; }
888 bool isComplexFloat() const { return !IsInt; }
889 APFloat &getComplexFloatReal() { return FloatReal; }
890 APFloat &getComplexFloatImag() { return FloatImag; }
891
892 void makeComplexInt() { IsInt = true; }
893 bool isComplexInt() const { return IsInt; }
894 APSInt &getComplexIntReal() { return IntReal; }
895 APSInt &getComplexIntImag() { return IntImag; }
896
Richard Smith2e312c82012-03-03 22:46:17 +0000897 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000898 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000899 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000900 else
Richard Smith2e312c82012-03-03 22:46:17 +0000901 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000902 }
Richard Smith2e312c82012-03-03 22:46:17 +0000903 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000904 assert(v.isComplexFloat() || v.isComplexInt());
905 if (v.isComplexFloat()) {
906 makeComplexFloat();
907 FloatReal = v.getComplexFloatReal();
908 FloatImag = v.getComplexFloatImag();
909 } else {
910 makeComplexInt();
911 IntReal = v.getComplexIntReal();
912 IntImag = v.getComplexIntImag();
913 }
914 }
John McCall93d91dc2010-05-07 17:22:02 +0000915 };
John McCall45d55e42010-05-07 21:00:08 +0000916
917 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000918 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000919 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000920 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000921 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000922
Richard Smithce40ad62011-11-12 22:28:03 +0000923 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000925 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000926 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000927 SubobjectDesignator &getLValueDesignator() { return Designator; }
928 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000929
Richard Smith2e312c82012-03-03 22:46:17 +0000930 void moveInto(APValue &V) const {
931 if (Designator.Invalid)
932 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933 else
934 V = APValue(Base, Offset, Designator.Entries,
935 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000936 }
Richard Smith2e312c82012-03-03 22:46:17 +0000937 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000938 assert(V.isLValue());
939 Base = V.getLValueBase();
940 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000941 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000942 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000943 }
944
Richard Smithb228a862012-02-15 02:18:13 +0000945 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000946 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000947 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000948 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000949 Designator = SubobjectDesignator(getType(B));
950 }
951
952 // Check that this LValue is not based on a null pointer. If it is, produce
953 // a diagnostic and mark the designator as invalid.
954 bool checkNullPointer(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Designator.Invalid)
957 return false;
958 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 Designator.setInvalid();
962 return false;
963 }
964 return true;
965 }
966
967 // Check this LValue refers to an object. If not, set the designator to be
968 // invalid and emit a diagnostic.
969 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000970 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000971 Designator.checkSubobject(Info, E, CSK);
972 }
973
974 void addDecl(EvalInfo &Info, const Expr *E,
975 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000976 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
977 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000978 }
979 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (checkSubobject(Info, E, CSK_ArrayToPointer))
981 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000982 }
Richard Smith66c96992012-02-18 22:04:06 +0000983 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000984 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
985 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000986 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000987 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000988 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +0000989 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000990 }
John McCall45d55e42010-05-07 21:00:08 +0000991 };
Richard Smith027bf112011-11-17 22:56:20 +0000992
993 struct MemberPtr {
994 MemberPtr() {}
995 explicit MemberPtr(const ValueDecl *Decl) :
996 DeclAndIsDerivedMember(Decl, false), Path() {}
997
998 /// The member or (direct or indirect) field referred to by this member
999 /// pointer, or 0 if this is a null member pointer.
1000 const ValueDecl *getDecl() const {
1001 return DeclAndIsDerivedMember.getPointer();
1002 }
1003 /// Is this actually a member of some type derived from the relevant class?
1004 bool isDerivedMember() const {
1005 return DeclAndIsDerivedMember.getInt();
1006 }
1007 /// Get the class which the declaration actually lives in.
1008 const CXXRecordDecl *getContainingRecord() const {
1009 return cast<CXXRecordDecl>(
1010 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1011 }
1012
Richard Smith2e312c82012-03-03 22:46:17 +00001013 void moveInto(APValue &V) const {
1014 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001015 }
Richard Smith2e312c82012-03-03 22:46:17 +00001016 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001017 assert(V.isMemberPointer());
1018 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1019 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1020 Path.clear();
1021 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1022 Path.insert(Path.end(), P.begin(), P.end());
1023 }
1024
1025 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1026 /// whether the member is a member of some class derived from the class type
1027 /// of the member pointer.
1028 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1029 /// Path - The path of base/derived classes from the member declaration's
1030 /// class (exclusive) to the class type of the member pointer (inclusive).
1031 SmallVector<const CXXRecordDecl*, 4> Path;
1032
1033 /// Perform a cast towards the class of the Decl (either up or down the
1034 /// hierarchy).
1035 bool castBack(const CXXRecordDecl *Class) {
1036 assert(!Path.empty());
1037 const CXXRecordDecl *Expected;
1038 if (Path.size() >= 2)
1039 Expected = Path[Path.size() - 2];
1040 else
1041 Expected = getContainingRecord();
1042 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1043 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1044 // if B does not contain the original member and is not a base or
1045 // derived class of the class containing the original member, the result
1046 // of the cast is undefined.
1047 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1048 // (D::*). We consider that to be a language defect.
1049 return false;
1050 }
1051 Path.pop_back();
1052 return true;
1053 }
1054 /// Perform a base-to-derived member pointer cast.
1055 bool castToDerived(const CXXRecordDecl *Derived) {
1056 if (!getDecl())
1057 return true;
1058 if (!isDerivedMember()) {
1059 Path.push_back(Derived);
1060 return true;
1061 }
1062 if (!castBack(Derived))
1063 return false;
1064 if (Path.empty())
1065 DeclAndIsDerivedMember.setInt(false);
1066 return true;
1067 }
1068 /// Perform a derived-to-base member pointer cast.
1069 bool castToBase(const CXXRecordDecl *Base) {
1070 if (!getDecl())
1071 return true;
1072 if (Path.empty())
1073 DeclAndIsDerivedMember.setInt(true);
1074 if (isDerivedMember()) {
1075 Path.push_back(Base);
1076 return true;
1077 }
1078 return castBack(Base);
1079 }
1080 };
Richard Smith357362d2011-12-13 06:39:58 +00001081
Richard Smith7bb00672012-02-01 01:42:44 +00001082 /// Compare two member pointers, which are assumed to be of the same type.
1083 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1084 if (!LHS.getDecl() || !RHS.getDecl())
1085 return !LHS.getDecl() && !RHS.getDecl();
1086 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1087 return false;
1088 return LHS.Path == RHS.Path;
1089 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001090}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001091
Richard Smith2e312c82012-03-03 22:46:17 +00001092static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001093static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1094 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001095 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001096static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1097static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001098static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1099 EvalInfo &Info);
1100static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001101static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001102static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001103 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001104static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001105static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001106static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001107
1108//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001109// Misc utilities
1110//===----------------------------------------------------------------------===//
1111
Richard Smith84401042013-06-03 05:03:02 +00001112/// Produce a string describing the given constexpr call.
1113static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1114 unsigned ArgIndex = 0;
1115 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1116 !isa<CXXConstructorDecl>(Frame->Callee) &&
1117 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1118
1119 if (!IsMemberCall)
1120 Out << *Frame->Callee << '(';
1121
1122 if (Frame->This && IsMemberCall) {
1123 APValue Val;
1124 Frame->This->moveInto(Val);
1125 Val.printPretty(Out, Frame->Info.Ctx,
1126 Frame->This->Designator.MostDerivedType);
1127 // FIXME: Add parens around Val if needed.
1128 Out << "->" << *Frame->Callee << '(';
1129 IsMemberCall = false;
1130 }
1131
1132 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1133 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1134 if (ArgIndex > (unsigned)IsMemberCall)
1135 Out << ", ";
1136
1137 const ParmVarDecl *Param = *I;
1138 const APValue &Arg = Frame->Arguments[ArgIndex];
1139 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1140
1141 if (ArgIndex == 0 && IsMemberCall)
1142 Out << "->" << *Frame->Callee << '(';
1143 }
1144
1145 Out << ')';
1146}
1147
Richard Smithd9f663b2013-04-22 15:31:51 +00001148/// Evaluate an expression to see if it had side-effects, and discard its
1149/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001150/// \return \c true if the caller should keep evaluating.
1151static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001152 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001153 if (!Evaluate(Scratch, Info, E))
1154 // We don't need the value, but we might have skipped a side effect here.
1155 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001156 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001157}
1158
Richard Smith861b5b52013-05-07 23:34:45 +00001159/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1160/// return its existing value.
1161static int64_t getExtValue(const APSInt &Value) {
1162 return Value.isSigned() ? Value.getSExtValue()
1163 : static_cast<int64_t>(Value.getZExtValue());
1164}
1165
Richard Smithd62306a2011-11-10 06:34:14 +00001166/// Should this call expression be treated as a string literal?
1167static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001168 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001169 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1170 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1171}
1172
Richard Smithce40ad62011-11-12 22:28:03 +00001173static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001174 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1175 // constant expression of pointer type that evaluates to...
1176
1177 // ... a null pointer value, or a prvalue core constant expression of type
1178 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001179 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001180
Richard Smithce40ad62011-11-12 22:28:03 +00001181 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1182 // ... the address of an object with static storage duration,
1183 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1184 return VD->hasGlobalStorage();
1185 // ... the address of a function,
1186 return isa<FunctionDecl>(D);
1187 }
1188
1189 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001190 switch (E->getStmtClass()) {
1191 default:
1192 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001193 case Expr::CompoundLiteralExprClass: {
1194 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1195 return CLE->isFileScope() && CLE->isLValue();
1196 }
Richard Smithe6c01442013-06-05 00:46:14 +00001197 case Expr::MaterializeTemporaryExprClass:
1198 // A materialized temporary might have been lifetime-extended to static
1199 // storage duration.
1200 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001201 // A string literal has static storage duration.
1202 case Expr::StringLiteralClass:
1203 case Expr::PredefinedExprClass:
1204 case Expr::ObjCStringLiteralClass:
1205 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001206 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001207 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001208 return true;
1209 case Expr::CallExprClass:
1210 return IsStringLiteralCall(cast<CallExpr>(E));
1211 // For GCC compatibility, &&label has static storage duration.
1212 case Expr::AddrLabelExprClass:
1213 return true;
1214 // A Block literal expression may be used as the initialization value for
1215 // Block variables at global or local static scope.
1216 case Expr::BlockExprClass:
1217 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001218 case Expr::ImplicitValueInitExprClass:
1219 // FIXME:
1220 // We can never form an lvalue with an implicit value initialization as its
1221 // base through expression evaluation, so these only appear in one case: the
1222 // implicit variable declaration we invent when checking whether a constexpr
1223 // constructor can produce a constant expression. We must assume that such
1224 // an expression might be a global lvalue.
1225 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001226 }
John McCall95007602010-05-10 23:27:23 +00001227}
1228
Richard Smithb228a862012-02-15 02:18:13 +00001229static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1230 assert(Base && "no location for a null lvalue");
1231 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1232 if (VD)
1233 Info.Note(VD->getLocation(), diag::note_declared_at);
1234 else
Ted Kremenek28831752012-08-23 20:46:57 +00001235 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001236 diag::note_constexpr_temporary_here);
1237}
1238
Richard Smith80815602011-11-07 05:07:52 +00001239/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001240/// value for an address or reference constant expression. Return true if we
1241/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001242static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1243 QualType Type, const LValue &LVal) {
1244 bool IsReferenceType = Type->isReferenceType();
1245
Richard Smith357362d2011-12-13 06:39:58 +00001246 APValue::LValueBase Base = LVal.getLValueBase();
1247 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1248
Richard Smith0dea49e2012-02-18 04:58:18 +00001249 // Check that the object is a global. Note that the fake 'this' object we
1250 // manufacture when checking potential constant expressions is conservatively
1251 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001252 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001253 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001254 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001255 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1256 << IsReferenceType << !Designator.Entries.empty()
1257 << !!VD << VD;
1258 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001259 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001260 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001261 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001262 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001263 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001264 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001265 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001266 LVal.getLValueCallIndex() == 0) &&
1267 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001268
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001269 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1270 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001271 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001272 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001273 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001274
Hans Wennborg82dd8772014-06-25 22:19:48 +00001275 // A dllimport variable never acts like a constant.
1276 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001277 return false;
1278 }
1279 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1280 // __declspec(dllimport) must be handled very carefully:
1281 // We must never initialize an expression with the thunk in C++.
1282 // Doing otherwise would allow the same id-expression to yield
1283 // different addresses for the same function in different translation
1284 // units. However, this means that we must dynamically initialize the
1285 // expression with the contents of the import address table at runtime.
1286 //
1287 // The C language has no notion of ODR; furthermore, it has no notion of
1288 // dynamic initialization. This means that we are permitted to
1289 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001290 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001291 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001292 }
1293 }
1294
Richard Smitha8105bc2012-01-06 16:39:00 +00001295 // Allow address constant expressions to be past-the-end pointers. This is
1296 // an extension: the standard requires them to point to an object.
1297 if (!IsReferenceType)
1298 return true;
1299
1300 // A reference constant expression must refer to an object.
1301 if (!Base) {
1302 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001303 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001304 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001305 }
1306
Richard Smith357362d2011-12-13 06:39:58 +00001307 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001308 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001309 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001310 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001311 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001312 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001313 }
1314
Richard Smith80815602011-11-07 05:07:52 +00001315 return true;
1316}
1317
Richard Smithfddd3842011-12-30 21:15:51 +00001318/// Check that this core constant expression is of literal type, and if not,
1319/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001320static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001321 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001322 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001323 return true;
1324
Richard Smith7525ff62013-05-09 07:14:00 +00001325 // C++1y: A constant initializer for an object o [...] may also invoke
1326 // constexpr constructors for o and its subobjects even if those objects
1327 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001328 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001329 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001330 return true;
1331
Richard Smithfddd3842011-12-30 21:15:51 +00001332 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001333 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001334 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001335 << E->getType();
1336 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001337 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001338 return false;
1339}
1340
Richard Smith0b0a0b62011-10-29 20:57:55 +00001341/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001342/// constant expression. If not, report an appropriate diagnostic. Does not
1343/// check that the expression is of literal type.
1344static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1345 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001346 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001347 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1348 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001349 return false;
1350 }
1351
Richard Smith77be48a2014-07-31 06:31:19 +00001352 // We allow _Atomic(T) to be initialized from anything that T can be
1353 // initialized from.
1354 if (const AtomicType *AT = Type->getAs<AtomicType>())
1355 Type = AT->getValueType();
1356
Richard Smithb228a862012-02-15 02:18:13 +00001357 // Core issue 1454: For a literal constant expression of array or class type,
1358 // each subobject of its value shall have been initialized by a constant
1359 // expression.
1360 if (Value.isArray()) {
1361 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1362 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1363 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1364 Value.getArrayInitializedElt(I)))
1365 return false;
1366 }
1367 if (!Value.hasArrayFiller())
1368 return true;
1369 return CheckConstantExpression(Info, DiagLoc, EltTy,
1370 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001371 }
Richard Smithb228a862012-02-15 02:18:13 +00001372 if (Value.isUnion() && Value.getUnionField()) {
1373 return CheckConstantExpression(Info, DiagLoc,
1374 Value.getUnionField()->getType(),
1375 Value.getUnionValue());
1376 }
1377 if (Value.isStruct()) {
1378 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1379 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1380 unsigned BaseIndex = 0;
1381 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1382 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1383 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1384 Value.getStructBase(BaseIndex)))
1385 return false;
1386 }
1387 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001388 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001389 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1390 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001391 return false;
1392 }
1393 }
1394
1395 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001396 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001397 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001398 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1399 }
1400
1401 // Everything else is fine.
1402 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001403}
1404
Benjamin Kramer8407df72015-03-09 16:47:52 +00001405static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001406 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001407}
1408
1409static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001410 if (Value.CallIndex)
1411 return false;
1412 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1413 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001414}
1415
Richard Smithcecf1842011-11-01 21:06:14 +00001416static bool IsWeakLValue(const LValue &Value) {
1417 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001418 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001419}
1420
David Majnemerb5116032014-12-09 23:32:34 +00001421static bool isZeroSized(const LValue &Value) {
1422 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001423 if (Decl && isa<VarDecl>(Decl)) {
1424 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001425 if (Ty->isArrayType())
1426 return Ty->isIncompleteType() ||
1427 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001428 }
1429 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001430}
1431
Richard Smith2e312c82012-03-03 22:46:17 +00001432static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001433 // A null base expression indicates a null pointer. These are always
1434 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001435 if (!Value.getLValueBase()) {
1436 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001437 return true;
1438 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001439
Richard Smith027bf112011-11-17 22:56:20 +00001440 // We have a non-null base. These are generally known to be true, but if it's
1441 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001442 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001443 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001444 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001445}
1446
Richard Smith2e312c82012-03-03 22:46:17 +00001447static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001448 switch (Val.getKind()) {
1449 case APValue::Uninitialized:
1450 return false;
1451 case APValue::Int:
1452 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001453 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001454 case APValue::Float:
1455 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001456 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001457 case APValue::ComplexInt:
1458 Result = Val.getComplexIntReal().getBoolValue() ||
1459 Val.getComplexIntImag().getBoolValue();
1460 return true;
1461 case APValue::ComplexFloat:
1462 Result = !Val.getComplexFloatReal().isZero() ||
1463 !Val.getComplexFloatImag().isZero();
1464 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001465 case APValue::LValue:
1466 return EvalPointerValueAsBool(Val, Result);
1467 case APValue::MemberPointer:
1468 Result = Val.getMemberPointerDecl();
1469 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001470 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001471 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001472 case APValue::Struct:
1473 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001474 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001475 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001476 }
1477
Richard Smith11562c52011-10-28 17:51:58 +00001478 llvm_unreachable("unknown APValue kind");
1479}
1480
1481static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1482 EvalInfo &Info) {
1483 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001484 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001485 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001486 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001487 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001488}
1489
Richard Smith357362d2011-12-13 06:39:58 +00001490template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001491static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001492 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001493 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001494 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001495}
1496
1497static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1498 QualType SrcType, const APFloat &Value,
1499 QualType DestType, APSInt &Result) {
1500 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001501 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001502 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001503
Richard Smith357362d2011-12-13 06:39:58 +00001504 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001505 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001506 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1507 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001508 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001509 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001510}
1511
Richard Smith357362d2011-12-13 06:39:58 +00001512static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1513 QualType SrcType, QualType DestType,
1514 APFloat &Result) {
1515 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001516 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001517 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1518 APFloat::rmNearestTiesToEven, &ignored)
1519 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001520 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001521 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001522}
1523
Richard Smith911e1422012-01-30 22:27:01 +00001524static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1525 QualType DestType, QualType SrcType,
1526 APSInt &Value) {
1527 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001528 APSInt Result = Value;
1529 // Figure out if this is a truncate, extend or noop cast.
1530 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001531 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001532 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001533 return Result;
1534}
1535
Richard Smith357362d2011-12-13 06:39:58 +00001536static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1537 QualType SrcType, const APSInt &Value,
1538 QualType DestType, APFloat &Result) {
1539 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1540 if (Result.convertFromAPInt(Value, Value.isSigned(),
1541 APFloat::rmNearestTiesToEven)
1542 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001543 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001544 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001545}
1546
Richard Smith49ca8aa2013-08-06 07:09:20 +00001547static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1548 APValue &Value, const FieldDecl *FD) {
1549 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1550
1551 if (!Value.isInt()) {
1552 // Trying to store a pointer-cast-to-integer into a bitfield.
1553 // FIXME: In this case, we should provide the diagnostic for casting
1554 // a pointer to an integer.
1555 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1556 Info.Diag(E);
1557 return false;
1558 }
1559
1560 APSInt &Int = Value.getInt();
1561 unsigned OldBitWidth = Int.getBitWidth();
1562 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1563 if (NewBitWidth < OldBitWidth)
1564 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1565 return true;
1566}
1567
Eli Friedman803acb32011-12-22 03:51:45 +00001568static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1569 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001570 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001571 if (!Evaluate(SVal, Info, E))
1572 return false;
1573 if (SVal.isInt()) {
1574 Res = SVal.getInt();
1575 return true;
1576 }
1577 if (SVal.isFloat()) {
1578 Res = SVal.getFloat().bitcastToAPInt();
1579 return true;
1580 }
1581 if (SVal.isVector()) {
1582 QualType VecTy = E->getType();
1583 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1584 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1585 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1586 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1587 Res = llvm::APInt::getNullValue(VecSize);
1588 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1589 APValue &Elt = SVal.getVectorElt(i);
1590 llvm::APInt EltAsInt;
1591 if (Elt.isInt()) {
1592 EltAsInt = Elt.getInt();
1593 } else if (Elt.isFloat()) {
1594 EltAsInt = Elt.getFloat().bitcastToAPInt();
1595 } else {
1596 // Don't try to handle vectors of anything other than int or float
1597 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001598 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001599 return false;
1600 }
1601 unsigned BaseEltSize = EltAsInt.getBitWidth();
1602 if (BigEndian)
1603 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1604 else
1605 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1606 }
1607 return true;
1608 }
1609 // Give up if the input isn't an int, float, or vector. For example, we
1610 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001611 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001612 return false;
1613}
1614
Richard Smith43e77732013-05-07 04:50:00 +00001615/// Perform the given integer operation, which is known to need at most BitWidth
1616/// bits, and check for overflow in the original type (if that type was not an
1617/// unsigned type).
1618template<typename Operation>
1619static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1620 const APSInt &LHS, const APSInt &RHS,
1621 unsigned BitWidth, Operation Op) {
1622 if (LHS.isUnsigned())
1623 return Op(LHS, RHS);
1624
1625 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1626 APSInt Result = Value.trunc(LHS.getBitWidth());
1627 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001628 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001629 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1630 diag::warn_integer_constant_overflow)
1631 << Result.toString(10) << E->getType();
1632 else
1633 HandleOverflow(Info, E, Value, E->getType());
1634 }
1635 return Result;
1636}
1637
1638/// Perform the given binary integer operation.
1639static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1640 BinaryOperatorKind Opcode, APSInt RHS,
1641 APSInt &Result) {
1642 switch (Opcode) {
1643 default:
1644 Info.Diag(E);
1645 return false;
1646 case BO_Mul:
1647 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1648 std::multiplies<APSInt>());
1649 return true;
1650 case BO_Add:
1651 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1652 std::plus<APSInt>());
1653 return true;
1654 case BO_Sub:
1655 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1656 std::minus<APSInt>());
1657 return true;
1658 case BO_And: Result = LHS & RHS; return true;
1659 case BO_Xor: Result = LHS ^ RHS; return true;
1660 case BO_Or: Result = LHS | RHS; return true;
1661 case BO_Div:
1662 case BO_Rem:
1663 if (RHS == 0) {
1664 Info.Diag(E, diag::note_expr_divide_by_zero);
1665 return false;
1666 }
1667 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1668 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1669 LHS.isSigned() && LHS.isMinSignedValue())
1670 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1671 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1672 return true;
1673 case BO_Shl: {
1674 if (Info.getLangOpts().OpenCL)
1675 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1676 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1677 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1678 RHS.isUnsigned());
1679 else if (RHS.isSigned() && RHS.isNegative()) {
1680 // During constant-folding, a negative shift is an opposite shift. Such
1681 // a shift is not a constant expression.
1682 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1683 RHS = -RHS;
1684 goto shift_right;
1685 }
1686 shift_left:
1687 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1688 // the shifted type.
1689 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1690 if (SA != RHS) {
1691 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1692 << RHS << E->getType() << LHS.getBitWidth();
1693 } else if (LHS.isSigned()) {
1694 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1695 // operand, and must not overflow the corresponding unsigned type.
1696 if (LHS.isNegative())
1697 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1698 else if (LHS.countLeadingZeros() < SA)
1699 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1700 }
1701 Result = LHS << SA;
1702 return true;
1703 }
1704 case BO_Shr: {
1705 if (Info.getLangOpts().OpenCL)
1706 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1707 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1708 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1709 RHS.isUnsigned());
1710 else if (RHS.isSigned() && RHS.isNegative()) {
1711 // During constant-folding, a negative shift is an opposite shift. Such a
1712 // shift is not a constant expression.
1713 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1714 RHS = -RHS;
1715 goto shift_left;
1716 }
1717 shift_right:
1718 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1719 // shifted type.
1720 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1721 if (SA != RHS)
1722 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1723 << RHS << E->getType() << LHS.getBitWidth();
1724 Result = LHS >> SA;
1725 return true;
1726 }
1727
1728 case BO_LT: Result = LHS < RHS; return true;
1729 case BO_GT: Result = LHS > RHS; return true;
1730 case BO_LE: Result = LHS <= RHS; return true;
1731 case BO_GE: Result = LHS >= RHS; return true;
1732 case BO_EQ: Result = LHS == RHS; return true;
1733 case BO_NE: Result = LHS != RHS; return true;
1734 }
1735}
1736
Richard Smith861b5b52013-05-07 23:34:45 +00001737/// Perform the given binary floating-point operation, in-place, on LHS.
1738static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1739 APFloat &LHS, BinaryOperatorKind Opcode,
1740 const APFloat &RHS) {
1741 switch (Opcode) {
1742 default:
1743 Info.Diag(E);
1744 return false;
1745 case BO_Mul:
1746 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1747 break;
1748 case BO_Add:
1749 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1750 break;
1751 case BO_Sub:
1752 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1753 break;
1754 case BO_Div:
1755 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1756 break;
1757 }
1758
1759 if (LHS.isInfinity() || LHS.isNaN())
1760 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1761 return true;
1762}
1763
Richard Smitha8105bc2012-01-06 16:39:00 +00001764/// Cast an lvalue referring to a base subobject to a derived class, by
1765/// truncating the lvalue's path to the given length.
1766static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1767 const RecordDecl *TruncatedType,
1768 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001769 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001770
1771 // Check we actually point to a derived class object.
1772 if (TruncatedElements == D.Entries.size())
1773 return true;
1774 assert(TruncatedElements >= D.MostDerivedPathLength &&
1775 "not casting to a derived class");
1776 if (!Result.checkSubobject(Info, E, CSK_Derived))
1777 return false;
1778
1779 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001780 const RecordDecl *RD = TruncatedType;
1781 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001782 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001783 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1784 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001785 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001786 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001787 else
Richard Smithd62306a2011-11-10 06:34:14 +00001788 Result.Offset -= Layout.getBaseClassOffset(Base);
1789 RD = Base;
1790 }
Richard Smith027bf112011-11-17 22:56:20 +00001791 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001792 return true;
1793}
1794
John McCalld7bca762012-05-01 00:38:49 +00001795static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001796 const CXXRecordDecl *Derived,
1797 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001798 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001799 if (!RL) {
1800 if (Derived->isInvalidDecl()) return false;
1801 RL = &Info.Ctx.getASTRecordLayout(Derived);
1802 }
1803
Richard Smithd62306a2011-11-10 06:34:14 +00001804 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001805 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001806 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001807}
1808
Richard Smitha8105bc2012-01-06 16:39:00 +00001809static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001810 const CXXRecordDecl *DerivedDecl,
1811 const CXXBaseSpecifier *Base) {
1812 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1813
John McCalld7bca762012-05-01 00:38:49 +00001814 if (!Base->isVirtual())
1815 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001816
Richard Smitha8105bc2012-01-06 16:39:00 +00001817 SubobjectDesignator &D = Obj.Designator;
1818 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001819 return false;
1820
Richard Smitha8105bc2012-01-06 16:39:00 +00001821 // Extract most-derived object and corresponding type.
1822 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1823 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1824 return false;
1825
1826 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001827 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001828 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1829 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001830 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001831 return true;
1832}
1833
Richard Smith84401042013-06-03 05:03:02 +00001834static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1835 QualType Type, LValue &Result) {
1836 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1837 PathE = E->path_end();
1838 PathI != PathE; ++PathI) {
1839 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1840 *PathI))
1841 return false;
1842 Type = (*PathI)->getType();
1843 }
1844 return true;
1845}
1846
Richard Smithd62306a2011-11-10 06:34:14 +00001847/// Update LVal to refer to the given field, which must be a member of the type
1848/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001849static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001850 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001851 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001852 if (!RL) {
1853 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001854 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001855 }
Richard Smithd62306a2011-11-10 06:34:14 +00001856
1857 unsigned I = FD->getFieldIndex();
1858 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001859 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001860 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001861}
1862
Richard Smith1b78b3d2012-01-25 22:15:11 +00001863/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001864static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001865 LValue &LVal,
1866 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001867 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001868 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001869 return false;
1870 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001871}
1872
Richard Smithd62306a2011-11-10 06:34:14 +00001873/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001874static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1875 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001876 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1877 // extension.
1878 if (Type->isVoidType() || Type->isFunctionType()) {
1879 Size = CharUnits::One();
1880 return true;
1881 }
1882
1883 if (!Type->isConstantSizeType()) {
1884 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001885 // FIXME: Better diagnostic.
1886 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001887 return false;
1888 }
1889
1890 Size = Info.Ctx.getTypeSizeInChars(Type);
1891 return true;
1892}
1893
1894/// Update a pointer value to model pointer arithmetic.
1895/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001896/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001897/// \param LVal - The pointer value to be updated.
1898/// \param EltTy - The pointee type represented by LVal.
1899/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001900static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1901 LValue &LVal, QualType EltTy,
1902 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001903 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001904 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001905 return false;
1906
1907 // Compute the new offset in the appropriate width.
1908 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001909 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001910 return true;
1911}
1912
Richard Smith66c96992012-02-18 22:04:06 +00001913/// Update an lvalue to refer to a component of a complex number.
1914/// \param Info - Information about the ongoing evaluation.
1915/// \param LVal - The lvalue to be updated.
1916/// \param EltTy - The complex number's component type.
1917/// \param Imag - False for the real component, true for the imaginary.
1918static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1919 LValue &LVal, QualType EltTy,
1920 bool Imag) {
1921 if (Imag) {
1922 CharUnits SizeOfComponent;
1923 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1924 return false;
1925 LVal.Offset += SizeOfComponent;
1926 }
1927 LVal.addComplex(Info, E, EltTy, Imag);
1928 return true;
1929}
1930
Richard Smith27908702011-10-24 17:54:18 +00001931/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001932///
1933/// \param Info Information about the ongoing evaluation.
1934/// \param E An expression to be used when printing diagnostics.
1935/// \param VD The variable whose initializer should be obtained.
1936/// \param Frame The frame in which the variable was created. Must be null
1937/// if this variable is not local to the evaluation.
1938/// \param Result Filled in with a pointer to the value of the variable.
1939static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1940 const VarDecl *VD, CallStackFrame *Frame,
1941 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001942 // If this is a parameter to an active constexpr function call, perform
1943 // argument substitution.
1944 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001945 // Assume arguments of a potential constant expression are unknown
1946 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001947 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001948 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001949 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001950 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001951 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001952 }
Richard Smith3229b742013-05-05 21:17:10 +00001953 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001954 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001955 }
Richard Smith27908702011-10-24 17:54:18 +00001956
Richard Smithd9f663b2013-04-22 15:31:51 +00001957 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001958 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001959 Result = Frame->getTemporary(VD);
1960 assert(Result && "missing value for local variable");
1961 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001962 }
1963
Richard Smithd0b4dd62011-12-19 06:19:21 +00001964 // Dig out the initializer, and use the declaration which it's attached to.
1965 const Expr *Init = VD->getAnyInitializer(VD);
1966 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001967 // If we're checking a potential constant expression, the variable could be
1968 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001969 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001970 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001971 return false;
1972 }
1973
Richard Smithd62306a2011-11-10 06:34:14 +00001974 // If we're currently evaluating the initializer of this declaration, use that
1975 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001976 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001977 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001978 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001979 }
1980
Richard Smithcecf1842011-11-01 21:06:14 +00001981 // Never evaluate the initializer of a weak variable. We can't be sure that
1982 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001983 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001984 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001985 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001986 }
Richard Smithcecf1842011-11-01 21:06:14 +00001987
Richard Smithd0b4dd62011-12-19 06:19:21 +00001988 // Check that we can fold the initializer. In C++, we will have already done
1989 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001990 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001991 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001992 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001993 Notes.size() + 1) << VD;
1994 Info.Note(VD->getLocation(), diag::note_declared_at);
1995 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001996 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001997 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001998 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001999 Notes.size() + 1) << VD;
2000 Info.Note(VD->getLocation(), diag::note_declared_at);
2001 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002002 }
Richard Smith27908702011-10-24 17:54:18 +00002003
Richard Smith3229b742013-05-05 21:17:10 +00002004 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002005 return true;
Richard Smith27908702011-10-24 17:54:18 +00002006}
2007
Richard Smith11562c52011-10-28 17:51:58 +00002008static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002009 Qualifiers Quals = T.getQualifiers();
2010 return Quals.hasConst() && !Quals.hasVolatile();
2011}
2012
Richard Smithe97cbd72011-11-11 04:05:33 +00002013/// Get the base index of the given base class within an APValue representing
2014/// the given derived class.
2015static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2016 const CXXRecordDecl *Base) {
2017 Base = Base->getCanonicalDecl();
2018 unsigned Index = 0;
2019 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2020 E = Derived->bases_end(); I != E; ++I, ++Index) {
2021 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2022 return Index;
2023 }
2024
2025 llvm_unreachable("base class missing from derived class's bases list");
2026}
2027
Richard Smith3da88fa2013-04-26 14:36:30 +00002028/// Extract the value of a character from a string literal.
2029static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2030 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002031 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2032 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2033 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002034 const StringLiteral *S = cast<StringLiteral>(Lit);
2035 const ConstantArrayType *CAT =
2036 Info.Ctx.getAsConstantArrayType(S->getType());
2037 assert(CAT && "string literal isn't an array");
2038 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002039 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002040
2041 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002042 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002043 if (Index < S->getLength())
2044 Value = S->getCodeUnit(Index);
2045 return Value;
2046}
2047
Richard Smith3da88fa2013-04-26 14:36:30 +00002048// Expand a string literal into an array of characters.
2049static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2050 APValue &Result) {
2051 const StringLiteral *S = cast<StringLiteral>(Lit);
2052 const ConstantArrayType *CAT =
2053 Info.Ctx.getAsConstantArrayType(S->getType());
2054 assert(CAT && "string literal isn't an array");
2055 QualType CharType = CAT->getElementType();
2056 assert(CharType->isIntegerType() && "unexpected character type");
2057
2058 unsigned Elts = CAT->getSize().getZExtValue();
2059 Result = APValue(APValue::UninitArray(),
2060 std::min(S->getLength(), Elts), Elts);
2061 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2062 CharType->isUnsignedIntegerType());
2063 if (Result.hasArrayFiller())
2064 Result.getArrayFiller() = APValue(Value);
2065 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2066 Value = S->getCodeUnit(I);
2067 Result.getArrayInitializedElt(I) = APValue(Value);
2068 }
2069}
2070
2071// Expand an array so that it has more than Index filled elements.
2072static void expandArray(APValue &Array, unsigned Index) {
2073 unsigned Size = Array.getArraySize();
2074 assert(Index < Size);
2075
2076 // Always at least double the number of elements for which we store a value.
2077 unsigned OldElts = Array.getArrayInitializedElts();
2078 unsigned NewElts = std::max(Index+1, OldElts * 2);
2079 NewElts = std::min(Size, std::max(NewElts, 8u));
2080
2081 // Copy the data across.
2082 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2083 for (unsigned I = 0; I != OldElts; ++I)
2084 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2085 for (unsigned I = OldElts; I != NewElts; ++I)
2086 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2087 if (NewValue.hasArrayFiller())
2088 NewValue.getArrayFiller() = Array.getArrayFiller();
2089 Array.swap(NewValue);
2090}
2091
Richard Smithb01fe402014-09-16 01:24:02 +00002092/// Determine whether a type would actually be read by an lvalue-to-rvalue
2093/// conversion. If it's of class type, we may assume that the copy operation
2094/// is trivial. Note that this is never true for a union type with fields
2095/// (because the copy always "reads" the active member) and always true for
2096/// a non-class type.
2097static bool isReadByLvalueToRvalueConversion(QualType T) {
2098 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2099 if (!RD || (RD->isUnion() && !RD->field_empty()))
2100 return true;
2101 if (RD->isEmpty())
2102 return false;
2103
2104 for (auto *Field : RD->fields())
2105 if (isReadByLvalueToRvalueConversion(Field->getType()))
2106 return true;
2107
2108 for (auto &BaseSpec : RD->bases())
2109 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2110 return true;
2111
2112 return false;
2113}
2114
2115/// Diagnose an attempt to read from any unreadable field within the specified
2116/// type, which might be a class type.
2117static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2118 QualType T) {
2119 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2120 if (!RD)
2121 return false;
2122
2123 if (!RD->hasMutableFields())
2124 return false;
2125
2126 for (auto *Field : RD->fields()) {
2127 // If we're actually going to read this field in some way, then it can't
2128 // be mutable. If we're in a union, then assigning to a mutable field
2129 // (even an empty one) can change the active member, so that's not OK.
2130 // FIXME: Add core issue number for the union case.
2131 if (Field->isMutable() &&
2132 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2133 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2134 Info.Note(Field->getLocation(), diag::note_declared_at);
2135 return true;
2136 }
2137
2138 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2139 return true;
2140 }
2141
2142 for (auto &BaseSpec : RD->bases())
2143 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2144 return true;
2145
2146 // All mutable fields were empty, and thus not actually read.
2147 return false;
2148}
2149
Richard Smith861b5b52013-05-07 23:34:45 +00002150/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002151enum AccessKinds {
2152 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002153 AK_Assign,
2154 AK_Increment,
2155 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002156};
2157
Richard Smith3229b742013-05-05 21:17:10 +00002158/// A handle to a complete object (an object that is not a subobject of
2159/// another object).
2160struct CompleteObject {
2161 /// The value of the complete object.
2162 APValue *Value;
2163 /// The type of the complete object.
2164 QualType Type;
2165
Craig Topper36250ad2014-05-12 05:36:57 +00002166 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002167 CompleteObject(APValue *Value, QualType Type)
2168 : Value(Value), Type(Type) {
2169 assert(Value && "missing value for complete object");
2170 }
2171
Aaron Ballman67347662015-02-15 22:00:28 +00002172 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002173};
2174
Richard Smith3da88fa2013-04-26 14:36:30 +00002175/// Find the designated sub-object of an rvalue.
2176template<typename SubobjectHandler>
2177typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002178findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002179 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002180 if (Sub.Invalid)
2181 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002182 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002183 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002184 if (Info.getLangOpts().CPlusPlus11)
2185 Info.Diag(E, diag::note_constexpr_access_past_end)
2186 << handler.AccessKind;
2187 else
2188 Info.Diag(E);
2189 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002190 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002191
Richard Smith3229b742013-05-05 21:17:10 +00002192 APValue *O = Obj.Value;
2193 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002194 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002195
Richard Smithd62306a2011-11-10 06:34:14 +00002196 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002197 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2198 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002199 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002200 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2201 return handler.failed();
2202 }
2203
Richard Smith49ca8aa2013-08-06 07:09:20 +00002204 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002205 // If we are reading an object of class type, there may still be more
2206 // things we need to check: if there are any mutable subobjects, we
2207 // cannot perform this read. (This only happens when performing a trivial
2208 // copy or assignment.)
2209 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2210 diagnoseUnreadableFields(Info, E, ObjType))
2211 return handler.failed();
2212
Richard Smith49ca8aa2013-08-06 07:09:20 +00002213 if (!handler.found(*O, ObjType))
2214 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002215
Richard Smith49ca8aa2013-08-06 07:09:20 +00002216 // If we modified a bit-field, truncate it to the right width.
2217 if (handler.AccessKind != AK_Read &&
2218 LastField && LastField->isBitField() &&
2219 !truncateBitfieldValue(Info, E, *O, LastField))
2220 return false;
2221
2222 return true;
2223 }
2224
Craig Topper36250ad2014-05-12 05:36:57 +00002225 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002226 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002227 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002228 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002229 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002230 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002231 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002232 // Note, it should not be possible to form a pointer with a valid
2233 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002234 if (Info.getLangOpts().CPlusPlus11)
2235 Info.Diag(E, diag::note_constexpr_access_past_end)
2236 << handler.AccessKind;
2237 else
2238 Info.Diag(E);
2239 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002240 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002241
2242 ObjType = CAT->getElementType();
2243
Richard Smith14a94132012-02-17 03:35:37 +00002244 // An array object is represented as either an Array APValue or as an
2245 // LValue which refers to a string literal.
2246 if (O->isLValue()) {
2247 assert(I == N - 1 && "extracting subobject of character?");
2248 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002249 if (handler.AccessKind != AK_Read)
2250 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2251 *O);
2252 else
2253 return handler.foundString(*O, ObjType, Index);
2254 }
2255
2256 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002257 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002258 else if (handler.AccessKind != AK_Read) {
2259 expandArray(*O, Index);
2260 O = &O->getArrayInitializedElt(Index);
2261 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002262 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002263 } else if (ObjType->isAnyComplexType()) {
2264 // Next subobject is a complex number.
2265 uint64_t Index = Sub.Entries[I].ArrayIndex;
2266 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002267 if (Info.getLangOpts().CPlusPlus11)
2268 Info.Diag(E, diag::note_constexpr_access_past_end)
2269 << handler.AccessKind;
2270 else
2271 Info.Diag(E);
2272 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002273 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002274
2275 bool WasConstQualified = ObjType.isConstQualified();
2276 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2277 if (WasConstQualified)
2278 ObjType.addConst();
2279
Richard Smith66c96992012-02-18 22:04:06 +00002280 assert(I == N - 1 && "extracting subobject of scalar?");
2281 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002282 return handler.found(Index ? O->getComplexIntImag()
2283 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002284 } else {
2285 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002286 return handler.found(Index ? O->getComplexFloatImag()
2287 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002288 }
Richard Smithd62306a2011-11-10 06:34:14 +00002289 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002290 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002291 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002292 << Field;
2293 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002294 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002295 }
2296
Richard Smithd62306a2011-11-10 06:34:14 +00002297 // Next subobject is a class, struct or union field.
2298 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2299 if (RD->isUnion()) {
2300 const FieldDecl *UnionField = O->getUnionField();
2301 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002302 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002303 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2304 << handler.AccessKind << Field << !UnionField << UnionField;
2305 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002306 }
Richard Smithd62306a2011-11-10 06:34:14 +00002307 O = &O->getUnionValue();
2308 } else
2309 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002310
2311 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002312 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002313 if (WasConstQualified && !Field->isMutable())
2314 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002315
2316 if (ObjType.isVolatileQualified()) {
2317 if (Info.getLangOpts().CPlusPlus) {
2318 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002319 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2320 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002321 Info.Note(Field->getLocation(), diag::note_declared_at);
2322 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002323 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002324 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002325 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002326 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002327
2328 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002329 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002330 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002331 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2332 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2333 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002334
2335 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002336 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002337 if (WasConstQualified)
2338 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002339 }
2340 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002341}
2342
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002343namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002344struct ExtractSubobjectHandler {
2345 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002346 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002347
2348 static const AccessKinds AccessKind = AK_Read;
2349
2350 typedef bool result_type;
2351 bool failed() { return false; }
2352 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002353 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002354 return true;
2355 }
2356 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002357 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 return true;
2359 }
2360 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002361 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002362 return true;
2363 }
2364 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002365 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002366 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2367 return true;
2368 }
2369};
Richard Smith3229b742013-05-05 21:17:10 +00002370} // end anonymous namespace
2371
Richard Smith3da88fa2013-04-26 14:36:30 +00002372const AccessKinds ExtractSubobjectHandler::AccessKind;
2373
2374/// Extract the designated sub-object of an rvalue.
2375static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002376 const CompleteObject &Obj,
2377 const SubobjectDesignator &Sub,
2378 APValue &Result) {
2379 ExtractSubobjectHandler Handler = { Info, Result };
2380 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002381}
2382
Richard Smith3229b742013-05-05 21:17:10 +00002383namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002384struct ModifySubobjectHandler {
2385 EvalInfo &Info;
2386 APValue &NewVal;
2387 const Expr *E;
2388
2389 typedef bool result_type;
2390 static const AccessKinds AccessKind = AK_Assign;
2391
2392 bool checkConst(QualType QT) {
2393 // Assigning to a const object has undefined behavior.
2394 if (QT.isConstQualified()) {
2395 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2396 return false;
2397 }
2398 return true;
2399 }
2400
2401 bool failed() { return false; }
2402 bool found(APValue &Subobj, QualType SubobjType) {
2403 if (!checkConst(SubobjType))
2404 return false;
2405 // We've been given ownership of NewVal, so just swap it in.
2406 Subobj.swap(NewVal);
2407 return true;
2408 }
2409 bool found(APSInt &Value, QualType SubobjType) {
2410 if (!checkConst(SubobjType))
2411 return false;
2412 if (!NewVal.isInt()) {
2413 // Maybe trying to write a cast pointer value into a complex?
2414 Info.Diag(E);
2415 return false;
2416 }
2417 Value = NewVal.getInt();
2418 return true;
2419 }
2420 bool found(APFloat &Value, QualType SubobjType) {
2421 if (!checkConst(SubobjType))
2422 return false;
2423 Value = NewVal.getFloat();
2424 return true;
2425 }
2426 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2427 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2428 }
2429};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002430} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002431
Richard Smith3229b742013-05-05 21:17:10 +00002432const AccessKinds ModifySubobjectHandler::AccessKind;
2433
Richard Smith3da88fa2013-04-26 14:36:30 +00002434/// Update the designated sub-object of an rvalue to the given value.
2435static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002436 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002437 const SubobjectDesignator &Sub,
2438 APValue &NewVal) {
2439 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002440 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002441}
2442
Richard Smith84f6dcf2012-02-02 01:16:57 +00002443/// Find the position where two subobject designators diverge, or equivalently
2444/// the length of the common initial subsequence.
2445static unsigned FindDesignatorMismatch(QualType ObjType,
2446 const SubobjectDesignator &A,
2447 const SubobjectDesignator &B,
2448 bool &WasArrayIndex) {
2449 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2450 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002451 if (!ObjType.isNull() &&
2452 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002453 // Next subobject is an array element.
2454 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2455 WasArrayIndex = true;
2456 return I;
2457 }
Richard Smith66c96992012-02-18 22:04:06 +00002458 if (ObjType->isAnyComplexType())
2459 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2460 else
2461 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002462 } else {
2463 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2464 WasArrayIndex = false;
2465 return I;
2466 }
2467 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2468 // Next subobject is a field.
2469 ObjType = FD->getType();
2470 else
2471 // Next subobject is a base class.
2472 ObjType = QualType();
2473 }
2474 }
2475 WasArrayIndex = false;
2476 return I;
2477}
2478
2479/// Determine whether the given subobject designators refer to elements of the
2480/// same array object.
2481static bool AreElementsOfSameArray(QualType ObjType,
2482 const SubobjectDesignator &A,
2483 const SubobjectDesignator &B) {
2484 if (A.Entries.size() != B.Entries.size())
2485 return false;
2486
2487 bool IsArray = A.MostDerivedArraySize != 0;
2488 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2489 // A is a subobject of the array element.
2490 return false;
2491
2492 // If A (and B) designates an array element, the last entry will be the array
2493 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2494 // of length 1' case, and the entire path must match.
2495 bool WasArrayIndex;
2496 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2497 return CommonLength >= A.Entries.size() - IsArray;
2498}
2499
Richard Smith3229b742013-05-05 21:17:10 +00002500/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002501static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2502 AccessKinds AK, const LValue &LVal,
2503 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002504 if (!LVal.Base) {
2505 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2506 return CompleteObject();
2507 }
2508
Craig Topper36250ad2014-05-12 05:36:57 +00002509 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002510 if (LVal.CallIndex) {
2511 Frame = Info.getCallFrame(LVal.CallIndex);
2512 if (!Frame) {
2513 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2514 << AK << LVal.Base.is<const ValueDecl*>();
2515 NoteLValueLocation(Info, LVal.Base);
2516 return CompleteObject();
2517 }
Richard Smith3229b742013-05-05 21:17:10 +00002518 }
2519
2520 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2521 // is not a constant expression (even if the object is non-volatile). We also
2522 // apply this rule to C++98, in order to conform to the expected 'volatile'
2523 // semantics.
2524 if (LValType.isVolatileQualified()) {
2525 if (Info.getLangOpts().CPlusPlus)
2526 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2527 << AK << LValType;
2528 else
2529 Info.Diag(E);
2530 return CompleteObject();
2531 }
2532
2533 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002534 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002535 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002536
2537 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2538 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2539 // In C++11, constexpr, non-volatile variables initialized with constant
2540 // expressions are constant expressions too. Inside constexpr functions,
2541 // parameters are constant expressions even if they're non-const.
2542 // In C++1y, objects local to a constant expression (those with a Frame) are
2543 // both readable and writable inside constant expressions.
2544 // In C, such things can also be folded, although they are not ICEs.
2545 const VarDecl *VD = dyn_cast<VarDecl>(D);
2546 if (VD) {
2547 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2548 VD = VDef;
2549 }
2550 if (!VD || VD->isInvalidDecl()) {
2551 Info.Diag(E);
2552 return CompleteObject();
2553 }
2554
2555 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002556 if (BaseType.isVolatileQualified()) {
2557 if (Info.getLangOpts().CPlusPlus) {
2558 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2559 << AK << 1 << VD;
2560 Info.Note(VD->getLocation(), diag::note_declared_at);
2561 } else {
2562 Info.Diag(E);
2563 }
2564 return CompleteObject();
2565 }
2566
2567 // Unless we're looking at a local variable or argument in a constexpr call,
2568 // the variable we're reading must be const.
2569 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002570 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002571 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2572 // OK, we can read and modify an object if we're in the process of
2573 // evaluating its initializer, because its lifetime began in this
2574 // evaluation.
2575 } else if (AK != AK_Read) {
2576 // All the remaining cases only permit reading.
2577 Info.Diag(E, diag::note_constexpr_modify_global);
2578 return CompleteObject();
2579 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002580 // OK, we can read this variable.
2581 } else if (BaseType->isIntegralOrEnumerationType()) {
2582 if (!BaseType.isConstQualified()) {
2583 if (Info.getLangOpts().CPlusPlus) {
2584 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2585 Info.Note(VD->getLocation(), diag::note_declared_at);
2586 } else {
2587 Info.Diag(E);
2588 }
2589 return CompleteObject();
2590 }
2591 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2592 // We support folding of const floating-point types, in order to make
2593 // static const data members of such types (supported as an extension)
2594 // more useful.
2595 if (Info.getLangOpts().CPlusPlus11) {
2596 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2597 Info.Note(VD->getLocation(), diag::note_declared_at);
2598 } else {
2599 Info.CCEDiag(E);
2600 }
2601 } else {
2602 // FIXME: Allow folding of values of any literal type in all languages.
2603 if (Info.getLangOpts().CPlusPlus11) {
2604 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2605 Info.Note(VD->getLocation(), diag::note_declared_at);
2606 } else {
2607 Info.Diag(E);
2608 }
2609 return CompleteObject();
2610 }
2611 }
2612
2613 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2614 return CompleteObject();
2615 } else {
2616 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2617
2618 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002619 if (const MaterializeTemporaryExpr *MTE =
2620 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2621 assert(MTE->getStorageDuration() == SD_Static &&
2622 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002623
Richard Smithe6c01442013-06-05 00:46:14 +00002624 // Per C++1y [expr.const]p2:
2625 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2626 // - a [...] glvalue of integral or enumeration type that refers to
2627 // a non-volatile const object [...]
2628 // [...]
2629 // - a [...] glvalue of literal type that refers to a non-volatile
2630 // object whose lifetime began within the evaluation of e.
2631 //
2632 // C++11 misses the 'began within the evaluation of e' check and
2633 // instead allows all temporaries, including things like:
2634 // int &&r = 1;
2635 // int x = ++r;
2636 // constexpr int k = r;
2637 // Therefore we use the C++1y rules in C++11 too.
2638 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2639 const ValueDecl *ED = MTE->getExtendingDecl();
2640 if (!(BaseType.isConstQualified() &&
2641 BaseType->isIntegralOrEnumerationType()) &&
2642 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2643 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2644 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2645 return CompleteObject();
2646 }
2647
2648 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2649 assert(BaseVal && "got reference to unevaluated temporary");
2650 } else {
2651 Info.Diag(E);
2652 return CompleteObject();
2653 }
2654 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002655 BaseVal = Frame->getTemporary(Base);
2656 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002657 }
Richard Smith3229b742013-05-05 21:17:10 +00002658
2659 // Volatile temporary objects cannot be accessed in constant expressions.
2660 if (BaseType.isVolatileQualified()) {
2661 if (Info.getLangOpts().CPlusPlus) {
2662 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2663 << AK << 0;
2664 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2665 } else {
2666 Info.Diag(E);
2667 }
2668 return CompleteObject();
2669 }
2670 }
2671
Richard Smith7525ff62013-05-09 07:14:00 +00002672 // During the construction of an object, it is not yet 'const'.
2673 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2674 // and this doesn't do quite the right thing for const subobjects of the
2675 // object under construction.
2676 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2677 BaseType = Info.Ctx.getCanonicalType(BaseType);
2678 BaseType.removeLocalConst();
2679 }
2680
Richard Smith6d4c6582013-11-05 22:18:15 +00002681 // In C++1y, we can't safely access any mutable state when we might be
2682 // evaluating after an unmodeled side effect or an evaluation failure.
2683 //
2684 // FIXME: Not all local state is mutable. Allow local constant subobjects
2685 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002686 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002687 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002688 return CompleteObject();
2689
2690 return CompleteObject(BaseVal, BaseType);
2691}
2692
Richard Smith243ef902013-05-05 23:31:59 +00002693/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2694/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2695/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002696///
2697/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002698/// \param Conv - The expression for which we are performing the conversion.
2699/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002700/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2701/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002702/// \param LVal - The glvalue on which we are attempting to perform this action.
2703/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002704static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002705 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002706 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002707 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002708 return false;
2709
Richard Smith3229b742013-05-05 21:17:10 +00002710 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002711 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002712 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002713 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2714 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2715 // initializer until now for such expressions. Such an expression can't be
2716 // an ICE in C, so this only matters for fold.
2717 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2718 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002719 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002720 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002721 }
Richard Smith3229b742013-05-05 21:17:10 +00002722 APValue Lit;
2723 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2724 return false;
2725 CompleteObject LitObj(&Lit, Base->getType());
2726 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002727 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002728 // We represent a string literal array as an lvalue pointing at the
2729 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002730 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002731 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2732 CompleteObject StrObj(&Str, Base->getType());
2733 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002734 }
Richard Smith11562c52011-10-28 17:51:58 +00002735 }
2736
Richard Smith3229b742013-05-05 21:17:10 +00002737 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2738 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002739}
2740
2741/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002742static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002744 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 return false;
2746
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002747 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002748 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002749 return false;
2750 }
2751
Richard Smith3229b742013-05-05 21:17:10 +00002752 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2753 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002754}
2755
Richard Smith243ef902013-05-05 23:31:59 +00002756static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2757 return T->isSignedIntegerType() &&
2758 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2759}
2760
2761namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002762struct CompoundAssignSubobjectHandler {
2763 EvalInfo &Info;
2764 const Expr *E;
2765 QualType PromotedLHSType;
2766 BinaryOperatorKind Opcode;
2767 const APValue &RHS;
2768
2769 static const AccessKinds AccessKind = AK_Assign;
2770
2771 typedef bool result_type;
2772
2773 bool checkConst(QualType QT) {
2774 // Assigning to a const object has undefined behavior.
2775 if (QT.isConstQualified()) {
2776 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2777 return false;
2778 }
2779 return true;
2780 }
2781
2782 bool failed() { return false; }
2783 bool found(APValue &Subobj, QualType SubobjType) {
2784 switch (Subobj.getKind()) {
2785 case APValue::Int:
2786 return found(Subobj.getInt(), SubobjType);
2787 case APValue::Float:
2788 return found(Subobj.getFloat(), SubobjType);
2789 case APValue::ComplexInt:
2790 case APValue::ComplexFloat:
2791 // FIXME: Implement complex compound assignment.
2792 Info.Diag(E);
2793 return false;
2794 case APValue::LValue:
2795 return foundPointer(Subobj, SubobjType);
2796 default:
2797 // FIXME: can this happen?
2798 Info.Diag(E);
2799 return false;
2800 }
2801 }
2802 bool found(APSInt &Value, QualType SubobjType) {
2803 if (!checkConst(SubobjType))
2804 return false;
2805
2806 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2807 // We don't support compound assignment on integer-cast-to-pointer
2808 // values.
2809 Info.Diag(E);
2810 return false;
2811 }
2812
2813 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2814 SubobjType, Value);
2815 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2816 return false;
2817 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2818 return true;
2819 }
2820 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002821 return checkConst(SubobjType) &&
2822 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2823 Value) &&
2824 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2825 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002826 }
2827 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2828 if (!checkConst(SubobjType))
2829 return false;
2830
2831 QualType PointeeType;
2832 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2833 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002834
2835 if (PointeeType.isNull() || !RHS.isInt() ||
2836 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002837 Info.Diag(E);
2838 return false;
2839 }
2840
Richard Smith861b5b52013-05-07 23:34:45 +00002841 int64_t Offset = getExtValue(RHS.getInt());
2842 if (Opcode == BO_Sub)
2843 Offset = -Offset;
2844
2845 LValue LVal;
2846 LVal.setFrom(Info.Ctx, Subobj);
2847 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2848 return false;
2849 LVal.moveInto(Subobj);
2850 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002851 }
2852 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2853 llvm_unreachable("shouldn't encounter string elements here");
2854 }
2855};
2856} // end anonymous namespace
2857
2858const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2859
2860/// Perform a compound assignment of LVal <op>= RVal.
2861static bool handleCompoundAssignment(
2862 EvalInfo &Info, const Expr *E,
2863 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2864 BinaryOperatorKind Opcode, const APValue &RVal) {
2865 if (LVal.Designator.Invalid)
2866 return false;
2867
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002868 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002869 Info.Diag(E);
2870 return false;
2871 }
2872
2873 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2874 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2875 RVal };
2876 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2877}
2878
2879namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002880struct IncDecSubobjectHandler {
2881 EvalInfo &Info;
2882 const Expr *E;
2883 AccessKinds AccessKind;
2884 APValue *Old;
2885
2886 typedef bool result_type;
2887
2888 bool checkConst(QualType QT) {
2889 // Assigning to a const object has undefined behavior.
2890 if (QT.isConstQualified()) {
2891 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2892 return false;
2893 }
2894 return true;
2895 }
2896
2897 bool failed() { return false; }
2898 bool found(APValue &Subobj, QualType SubobjType) {
2899 // Stash the old value. Also clear Old, so we don't clobber it later
2900 // if we're post-incrementing a complex.
2901 if (Old) {
2902 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002903 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002904 }
2905
2906 switch (Subobj.getKind()) {
2907 case APValue::Int:
2908 return found(Subobj.getInt(), SubobjType);
2909 case APValue::Float:
2910 return found(Subobj.getFloat(), SubobjType);
2911 case APValue::ComplexInt:
2912 return found(Subobj.getComplexIntReal(),
2913 SubobjType->castAs<ComplexType>()->getElementType()
2914 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2915 case APValue::ComplexFloat:
2916 return found(Subobj.getComplexFloatReal(),
2917 SubobjType->castAs<ComplexType>()->getElementType()
2918 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2919 case APValue::LValue:
2920 return foundPointer(Subobj, SubobjType);
2921 default:
2922 // FIXME: can this happen?
2923 Info.Diag(E);
2924 return false;
2925 }
2926 }
2927 bool found(APSInt &Value, QualType SubobjType) {
2928 if (!checkConst(SubobjType))
2929 return false;
2930
2931 if (!SubobjType->isIntegerType()) {
2932 // We don't support increment / decrement on integer-cast-to-pointer
2933 // values.
2934 Info.Diag(E);
2935 return false;
2936 }
2937
2938 if (Old) *Old = APValue(Value);
2939
2940 // bool arithmetic promotes to int, and the conversion back to bool
2941 // doesn't reduce mod 2^n, so special-case it.
2942 if (SubobjType->isBooleanType()) {
2943 if (AccessKind == AK_Increment)
2944 Value = 1;
2945 else
2946 Value = !Value;
2947 return true;
2948 }
2949
2950 bool WasNegative = Value.isNegative();
2951 if (AccessKind == AK_Increment) {
2952 ++Value;
2953
2954 if (!WasNegative && Value.isNegative() &&
2955 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2956 APSInt ActualValue(Value, /*IsUnsigned*/true);
2957 HandleOverflow(Info, E, ActualValue, SubobjType);
2958 }
2959 } else {
2960 --Value;
2961
2962 if (WasNegative && !Value.isNegative() &&
2963 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2964 unsigned BitWidth = Value.getBitWidth();
2965 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2966 ActualValue.setBit(BitWidth);
2967 HandleOverflow(Info, E, ActualValue, SubobjType);
2968 }
2969 }
2970 return true;
2971 }
2972 bool found(APFloat &Value, QualType SubobjType) {
2973 if (!checkConst(SubobjType))
2974 return false;
2975
2976 if (Old) *Old = APValue(Value);
2977
2978 APFloat One(Value.getSemantics(), 1);
2979 if (AccessKind == AK_Increment)
2980 Value.add(One, APFloat::rmNearestTiesToEven);
2981 else
2982 Value.subtract(One, APFloat::rmNearestTiesToEven);
2983 return true;
2984 }
2985 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2986 if (!checkConst(SubobjType))
2987 return false;
2988
2989 QualType PointeeType;
2990 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2991 PointeeType = PT->getPointeeType();
2992 else {
2993 Info.Diag(E);
2994 return false;
2995 }
2996
2997 LValue LVal;
2998 LVal.setFrom(Info.Ctx, Subobj);
2999 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3000 AccessKind == AK_Increment ? 1 : -1))
3001 return false;
3002 LVal.moveInto(Subobj);
3003 return true;
3004 }
3005 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3006 llvm_unreachable("shouldn't encounter string elements here");
3007 }
3008};
3009} // end anonymous namespace
3010
3011/// Perform an increment or decrement on LVal.
3012static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3013 QualType LValType, bool IsIncrement, APValue *Old) {
3014 if (LVal.Designator.Invalid)
3015 return false;
3016
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003017 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003018 Info.Diag(E);
3019 return false;
3020 }
3021
3022 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3023 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3024 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3025 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3026}
3027
Richard Smithe97cbd72011-11-11 04:05:33 +00003028/// Build an lvalue for the object argument of a member function call.
3029static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3030 LValue &This) {
3031 if (Object->getType()->isPointerType())
3032 return EvaluatePointer(Object, This, Info);
3033
3034 if (Object->isGLValue())
3035 return EvaluateLValue(Object, This, Info);
3036
Richard Smithd9f663b2013-04-22 15:31:51 +00003037 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003038 return EvaluateTemporary(Object, This, Info);
3039
Richard Smith3e79a572014-06-11 19:53:12 +00003040 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003041 return false;
3042}
3043
3044/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3045/// lvalue referring to the result.
3046///
3047/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003048/// \param LV - An lvalue referring to the base of the member pointer.
3049/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003050/// \param IncludeMember - Specifies whether the member itself is included in
3051/// the resulting LValue subobject designator. This is not possible when
3052/// creating a bound member function.
3053/// \return The field or method declaration to which the member pointer refers,
3054/// or 0 if evaluation fails.
3055static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003056 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003057 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003058 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003059 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003060 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003061 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003062 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003063
3064 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3065 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003066 if (!MemPtr.getDecl()) {
3067 // FIXME: Specific diagnostic.
3068 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003069 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003070 }
Richard Smith253c2a32012-01-27 01:14:48 +00003071
Richard Smith027bf112011-11-17 22:56:20 +00003072 if (MemPtr.isDerivedMember()) {
3073 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003074 // The end of the derived-to-base path for the base object must match the
3075 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003076 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003077 LV.Designator.Entries.size()) {
3078 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003079 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003080 }
Richard Smith027bf112011-11-17 22:56:20 +00003081 unsigned PathLengthToMember =
3082 LV.Designator.Entries.size() - MemPtr.Path.size();
3083 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3084 const CXXRecordDecl *LVDecl = getAsBaseClass(
3085 LV.Designator.Entries[PathLengthToMember + I]);
3086 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003087 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3088 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003089 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003090 }
Richard Smith027bf112011-11-17 22:56:20 +00003091 }
3092
3093 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003094 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003095 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003096 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003097 } else if (!MemPtr.Path.empty()) {
3098 // Extend the LValue path with the member pointer's path.
3099 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3100 MemPtr.Path.size() + IncludeMember);
3101
3102 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003103 if (const PointerType *PT = LVType->getAs<PointerType>())
3104 LVType = PT->getPointeeType();
3105 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3106 assert(RD && "member pointer access on non-class-type expression");
3107 // The first class in the path is that of the lvalue.
3108 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3109 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003110 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003111 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003112 RD = Base;
3113 }
3114 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003115 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3116 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003117 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003118 }
3119
3120 // Add the member. Note that we cannot build bound member functions here.
3121 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003122 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003123 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003124 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003125 } else if (const IndirectFieldDecl *IFD =
3126 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003127 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003128 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003129 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003130 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003131 }
Richard Smith027bf112011-11-17 22:56:20 +00003132 }
3133
3134 return MemPtr.getDecl();
3135}
3136
Richard Smith84401042013-06-03 05:03:02 +00003137static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3138 const BinaryOperator *BO,
3139 LValue &LV,
3140 bool IncludeMember = true) {
3141 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3142
3143 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3144 if (Info.keepEvaluatingAfterFailure()) {
3145 MemberPtr MemPtr;
3146 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3147 }
Craig Topper36250ad2014-05-12 05:36:57 +00003148 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003149 }
3150
3151 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3152 BO->getRHS(), IncludeMember);
3153}
3154
Richard Smith027bf112011-11-17 22:56:20 +00003155/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3156/// the provided lvalue, which currently refers to the base object.
3157static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3158 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003159 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003160 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003161 return false;
3162
Richard Smitha8105bc2012-01-06 16:39:00 +00003163 QualType TargetQT = E->getType();
3164 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3165 TargetQT = PT->getPointeeType();
3166
3167 // Check this cast lands within the final derived-to-base subobject path.
3168 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003169 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003170 << D.MostDerivedType << TargetQT;
3171 return false;
3172 }
3173
Richard Smith027bf112011-11-17 22:56:20 +00003174 // Check the type of the final cast. We don't need to check the path,
3175 // since a cast can only be formed if the path is unique.
3176 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003177 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3178 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003179 if (NewEntriesSize == D.MostDerivedPathLength)
3180 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3181 else
Richard Smith027bf112011-11-17 22:56:20 +00003182 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003183 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003184 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003185 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003186 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003187 }
Richard Smith027bf112011-11-17 22:56:20 +00003188
3189 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003190 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003191}
3192
Mike Stump876387b2009-10-27 22:09:17 +00003193namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003194enum EvalStmtResult {
3195 /// Evaluation failed.
3196 ESR_Failed,
3197 /// Hit a 'return' statement.
3198 ESR_Returned,
3199 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003200 ESR_Succeeded,
3201 /// Hit a 'continue' statement.
3202 ESR_Continue,
3203 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003204 ESR_Break,
3205 /// Still scanning for 'case' or 'default' statement.
3206 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003207};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003208}
Richard Smith254a73d2011-10-28 22:34:42 +00003209
Richard Smithd9f663b2013-04-22 15:31:51 +00003210static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3211 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3212 // We don't need to evaluate the initializer for a static local.
3213 if (!VD->hasLocalStorage())
3214 return true;
3215
3216 LValue Result;
3217 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003218 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003219
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003220 const Expr *InitE = VD->getInit();
3221 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003222 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3223 << false << VD->getType();
3224 Val = APValue();
3225 return false;
3226 }
3227
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003228 if (InitE->isValueDependent())
3229 return false;
3230
3231 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003232 // Wipe out any partially-computed value, to allow tracking that this
3233 // evaluation failed.
3234 Val = APValue();
3235 return false;
3236 }
3237 }
3238
3239 return true;
3240}
3241
Richard Smith4e18ca52013-05-06 05:56:11 +00003242/// Evaluate a condition (either a variable declaration or an expression).
3243static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3244 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003245 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003246 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3247 return false;
3248 return EvaluateAsBooleanCondition(Cond, Result, Info);
3249}
3250
Richard Smith52a980a2015-08-28 02:43:42 +00003251/// \brief A location where the result (returned value) of evaluating a
3252/// statement should be stored.
3253struct StmtResult {
3254 /// The APValue that should be filled in with the returned value.
3255 APValue &Value;
3256 /// The location containing the result, if any (used to support RVO).
3257 const LValue *Slot;
3258};
3259
3260static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003261 const Stmt *S,
3262 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003263
3264/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003265static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003266 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003267 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003268 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003269 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003270 case ESR_Break:
3271 return ESR_Succeeded;
3272 case ESR_Succeeded:
3273 case ESR_Continue:
3274 return ESR_Continue;
3275 case ESR_Failed:
3276 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003277 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003278 return ESR;
3279 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003280 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003281}
3282
Richard Smith496ddcf2013-05-12 17:32:42 +00003283/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003284static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003285 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003286 BlockScopeRAII Scope(Info);
3287
Richard Smith496ddcf2013-05-12 17:32:42 +00003288 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003289 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003290 {
3291 FullExpressionRAII Scope(Info);
3292 if (SS->getConditionVariable() &&
3293 !EvaluateDecl(Info, SS->getConditionVariable()))
3294 return ESR_Failed;
3295 if (!EvaluateInteger(SS->getCond(), Value, Info))
3296 return ESR_Failed;
3297 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003298
3299 // Find the switch case corresponding to the value of the condition.
3300 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003301 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003302 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3303 SC = SC->getNextSwitchCase()) {
3304 if (isa<DefaultStmt>(SC)) {
3305 Found = SC;
3306 continue;
3307 }
3308
3309 const CaseStmt *CS = cast<CaseStmt>(SC);
3310 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3311 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3312 : LHS;
3313 if (LHS <= Value && Value <= RHS) {
3314 Found = SC;
3315 break;
3316 }
3317 }
3318
3319 if (!Found)
3320 return ESR_Succeeded;
3321
3322 // Search the switch body for the switch case and evaluate it from there.
3323 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3324 case ESR_Break:
3325 return ESR_Succeeded;
3326 case ESR_Succeeded:
3327 case ESR_Continue:
3328 case ESR_Failed:
3329 case ESR_Returned:
3330 return ESR;
3331 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003332 // This can only happen if the switch case is nested within a statement
3333 // expression. We have no intention of supporting that.
3334 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3335 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003336 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003337 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003338}
3339
Richard Smith254a73d2011-10-28 22:34:42 +00003340// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003341static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003342 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003343 if (!Info.nextStep(S))
3344 return ESR_Failed;
3345
Richard Smith496ddcf2013-05-12 17:32:42 +00003346 // If we're hunting down a 'case' or 'default' label, recurse through
3347 // substatements until we hit the label.
3348 if (Case) {
3349 // FIXME: We don't start the lifetime of objects whose initialization we
3350 // jump over. However, such objects must be of class type with a trivial
3351 // default constructor that initialize all subobjects, so must be empty,
3352 // so this almost never matters.
3353 switch (S->getStmtClass()) {
3354 case Stmt::CompoundStmtClass:
3355 // FIXME: Precompute which substatement of a compound statement we
3356 // would jump to, and go straight there rather than performing a
3357 // linear scan each time.
3358 case Stmt::LabelStmtClass:
3359 case Stmt::AttributedStmtClass:
3360 case Stmt::DoStmtClass:
3361 break;
3362
3363 case Stmt::CaseStmtClass:
3364 case Stmt::DefaultStmtClass:
3365 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003366 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003367 break;
3368
3369 case Stmt::IfStmtClass: {
3370 // FIXME: Precompute which side of an 'if' we would jump to, and go
3371 // straight there rather than scanning both sides.
3372 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003373
3374 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3375 // preceded by our switch label.
3376 BlockScopeRAII Scope(Info);
3377
Richard Smith496ddcf2013-05-12 17:32:42 +00003378 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3379 if (ESR != ESR_CaseNotFound || !IS->getElse())
3380 return ESR;
3381 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3382 }
3383
3384 case Stmt::WhileStmtClass: {
3385 EvalStmtResult ESR =
3386 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3387 if (ESR != ESR_Continue)
3388 return ESR;
3389 break;
3390 }
3391
3392 case Stmt::ForStmtClass: {
3393 const ForStmt *FS = cast<ForStmt>(S);
3394 EvalStmtResult ESR =
3395 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3396 if (ESR != ESR_Continue)
3397 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003398 if (FS->getInc()) {
3399 FullExpressionRAII IncScope(Info);
3400 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3401 return ESR_Failed;
3402 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003403 break;
3404 }
3405
3406 case Stmt::DeclStmtClass:
3407 // FIXME: If the variable has initialization that can't be jumped over,
3408 // bail out of any immediately-surrounding compound-statement too.
3409 default:
3410 return ESR_CaseNotFound;
3411 }
3412 }
3413
Richard Smith254a73d2011-10-28 22:34:42 +00003414 switch (S->getStmtClass()) {
3415 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003416 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003417 // Don't bother evaluating beyond an expression-statement which couldn't
3418 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003419 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003420 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003421 return ESR_Failed;
3422 return ESR_Succeeded;
3423 }
3424
3425 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003426 return ESR_Failed;
3427
3428 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003429 return ESR_Succeeded;
3430
Richard Smithd9f663b2013-04-22 15:31:51 +00003431 case Stmt::DeclStmtClass: {
3432 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003433 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003434 // Each declaration initialization is its own full-expression.
3435 // FIXME: This isn't quite right; if we're performing aggregate
3436 // initialization, each braced subexpression is its own full-expression.
3437 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003438 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003439 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003440 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003441 return ESR_Succeeded;
3442 }
3443
Richard Smith357362d2011-12-13 06:39:58 +00003444 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003445 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003446 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003447 if (RetExpr &&
3448 !(Result.Slot
3449 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3450 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003451 return ESR_Failed;
3452 return ESR_Returned;
3453 }
Richard Smith254a73d2011-10-28 22:34:42 +00003454
3455 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003456 BlockScopeRAII Scope(Info);
3457
Richard Smith254a73d2011-10-28 22:34:42 +00003458 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003459 for (const auto *BI : CS->body()) {
3460 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003461 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003462 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003463 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003464 return ESR;
3465 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003466 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003467 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003468
3469 case Stmt::IfStmtClass: {
3470 const IfStmt *IS = cast<IfStmt>(S);
3471
3472 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003473 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003474 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003475 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003476 return ESR_Failed;
3477
3478 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3479 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3480 if (ESR != ESR_Succeeded)
3481 return ESR;
3482 }
3483 return ESR_Succeeded;
3484 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003485
3486 case Stmt::WhileStmtClass: {
3487 const WhileStmt *WS = cast<WhileStmt>(S);
3488 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003489 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003490 bool Continue;
3491 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3492 Continue))
3493 return ESR_Failed;
3494 if (!Continue)
3495 break;
3496
3497 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3498 if (ESR != ESR_Continue)
3499 return ESR;
3500 }
3501 return ESR_Succeeded;
3502 }
3503
3504 case Stmt::DoStmtClass: {
3505 const DoStmt *DS = cast<DoStmt>(S);
3506 bool Continue;
3507 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003508 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003509 if (ESR != ESR_Continue)
3510 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003511 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003512
Richard Smith08d6a2c2013-07-24 07:11:57 +00003513 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003514 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3515 return ESR_Failed;
3516 } while (Continue);
3517 return ESR_Succeeded;
3518 }
3519
3520 case Stmt::ForStmtClass: {
3521 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003523 if (FS->getInit()) {
3524 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3525 if (ESR != ESR_Succeeded)
3526 return ESR;
3527 }
3528 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003529 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003530 bool Continue = true;
3531 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3532 FS->getCond(), Continue))
3533 return ESR_Failed;
3534 if (!Continue)
3535 break;
3536
3537 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3538 if (ESR != ESR_Continue)
3539 return ESR;
3540
Richard Smith08d6a2c2013-07-24 07:11:57 +00003541 if (FS->getInc()) {
3542 FullExpressionRAII IncScope(Info);
3543 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3544 return ESR_Failed;
3545 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003546 }
3547 return ESR_Succeeded;
3548 }
3549
Richard Smith896e0d72013-05-06 06:51:17 +00003550 case Stmt::CXXForRangeStmtClass: {
3551 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003552 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003553
3554 // Initialize the __range variable.
3555 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3556 if (ESR != ESR_Succeeded)
3557 return ESR;
3558
3559 // Create the __begin and __end iterators.
3560 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3561 if (ESR != ESR_Succeeded)
3562 return ESR;
3563
3564 while (true) {
3565 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003566 {
3567 bool Continue = true;
3568 FullExpressionRAII CondExpr(Info);
3569 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3570 return ESR_Failed;
3571 if (!Continue)
3572 break;
3573 }
Richard Smith896e0d72013-05-06 06:51:17 +00003574
3575 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003576 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003577 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3578 if (ESR != ESR_Succeeded)
3579 return ESR;
3580
3581 // Loop body.
3582 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3583 if (ESR != ESR_Continue)
3584 return ESR;
3585
3586 // Increment: ++__begin
3587 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3588 return ESR_Failed;
3589 }
3590
3591 return ESR_Succeeded;
3592 }
3593
Richard Smith496ddcf2013-05-12 17:32:42 +00003594 case Stmt::SwitchStmtClass:
3595 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3596
Richard Smith4e18ca52013-05-06 05:56:11 +00003597 case Stmt::ContinueStmtClass:
3598 return ESR_Continue;
3599
3600 case Stmt::BreakStmtClass:
3601 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003602
3603 case Stmt::LabelStmtClass:
3604 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3605
3606 case Stmt::AttributedStmtClass:
3607 // As a general principle, C++11 attributes can be ignored without
3608 // any semantic impact.
3609 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3610 Case);
3611
3612 case Stmt::CaseStmtClass:
3613 case Stmt::DefaultStmtClass:
3614 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003615 }
3616}
3617
Richard Smithcc36f692011-12-22 02:22:31 +00003618/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3619/// default constructor. If so, we'll fold it whether or not it's marked as
3620/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3621/// so we need special handling.
3622static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003623 const CXXConstructorDecl *CD,
3624 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003625 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3626 return false;
3627
Richard Smith66e05fe2012-01-18 05:21:49 +00003628 // Value-initialization does not call a trivial default constructor, so such a
3629 // call is a core constant expression whether or not the constructor is
3630 // constexpr.
3631 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003632 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003633 // FIXME: If DiagDecl is an implicitly-declared special member function,
3634 // we should be much more explicit about why it's not constexpr.
3635 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3636 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3637 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003638 } else {
3639 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3640 }
3641 }
3642 return true;
3643}
3644
Richard Smith357362d2011-12-13 06:39:58 +00003645/// CheckConstexprFunction - Check that a function can be called in a constant
3646/// expression.
3647static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3648 const FunctionDecl *Declaration,
3649 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003650 // Potential constant expressions can contain calls to declared, but not yet
3651 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003652 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003653 Declaration->isConstexpr())
3654 return false;
3655
Richard Smith0838f3a2013-05-14 05:18:44 +00003656 // Bail out with no diagnostic if the function declaration itself is invalid.
3657 // We will have produced a relevant diagnostic while parsing it.
3658 if (Declaration->isInvalidDecl())
3659 return false;
3660
Richard Smith357362d2011-12-13 06:39:58 +00003661 // Can we evaluate this function call?
3662 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3663 return true;
3664
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003665 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003666 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003667 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3668 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003669 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3670 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3671 << DiagDecl;
3672 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3673 } else {
3674 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3675 }
3676 return false;
3677}
3678
Richard Smithbe6dd812014-11-19 21:27:17 +00003679/// Determine if a class has any fields that might need to be copied by a
3680/// trivial copy or move operation.
3681static bool hasFields(const CXXRecordDecl *RD) {
3682 if (!RD || RD->isEmpty())
3683 return false;
3684 for (auto *FD : RD->fields()) {
3685 if (FD->isUnnamedBitfield())
3686 continue;
3687 return true;
3688 }
3689 for (auto &Base : RD->bases())
3690 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3691 return true;
3692 return false;
3693}
3694
Richard Smithd62306a2011-11-10 06:34:14 +00003695namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003696typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003697}
3698
3699/// EvaluateArgs - Evaluate the arguments to a function call.
3700static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3701 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003702 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003703 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003704 I != E; ++I) {
3705 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3706 // If we're checking for a potential constant expression, evaluate all
3707 // initializers even if some of them fail.
3708 if (!Info.keepEvaluatingAfterFailure())
3709 return false;
3710 Success = false;
3711 }
3712 }
3713 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003714}
3715
Richard Smith254a73d2011-10-28 22:34:42 +00003716/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003717static bool HandleFunctionCall(SourceLocation CallLoc,
3718 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003719 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003720 EvalInfo &Info, APValue &Result,
3721 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003722 ArgVector ArgValues(Args.size());
3723 if (!EvaluateArgs(Args, ArgValues, Info))
3724 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003725
Richard Smith253c2a32012-01-27 01:14:48 +00003726 if (!Info.CheckCallLimit(CallLoc))
3727 return false;
3728
3729 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003730
3731 // For a trivial copy or move assignment, perform an APValue copy. This is
3732 // essential for unions, where the operations performed by the assignment
3733 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003734 //
3735 // Skip this for non-union classes with no fields; in that case, the defaulted
3736 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003738 if (MD && MD->isDefaulted() &&
3739 (MD->getParent()->isUnion() ||
3740 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003741 assert(This &&
3742 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3743 LValue RHS;
3744 RHS.setFrom(Info.Ctx, ArgValues[0]);
3745 APValue RHSValue;
3746 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3747 RHS, RHSValue))
3748 return false;
3749 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3750 RHSValue))
3751 return false;
3752 This->moveInto(Result);
3753 return true;
3754 }
3755
Richard Smith52a980a2015-08-28 02:43:42 +00003756 StmtResult Ret = {Result, ResultSlot};
3757 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003758 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003759 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003760 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003761 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003762 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003763 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003764}
3765
Richard Smithd62306a2011-11-10 06:34:14 +00003766/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003767static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003768 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003769 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003770 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003771 ArgVector ArgValues(Args.size());
3772 if (!EvaluateArgs(Args, ArgValues, Info))
3773 return false;
3774
Richard Smith253c2a32012-01-27 01:14:48 +00003775 if (!Info.CheckCallLimit(CallLoc))
3776 return false;
3777
Richard Smith3607ffe2012-02-13 03:54:03 +00003778 const CXXRecordDecl *RD = Definition->getParent();
3779 if (RD->getNumVBases()) {
3780 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3781 return false;
3782 }
3783
Richard Smith253c2a32012-01-27 01:14:48 +00003784 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003785
Richard Smith52a980a2015-08-28 02:43:42 +00003786 // FIXME: Creating an APValue just to hold a nonexistent return value is
3787 // wasteful.
3788 APValue RetVal;
3789 StmtResult Ret = {RetVal, nullptr};
3790
Richard Smithd62306a2011-11-10 06:34:14 +00003791 // If it's a delegating constructor, just delegate.
3792 if (Definition->isDelegatingConstructor()) {
3793 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003794 {
3795 FullExpressionRAII InitScope(Info);
3796 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3797 return false;
3798 }
Richard Smith52a980a2015-08-28 02:43:42 +00003799 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003800 }
3801
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003802 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003803 // essential for unions (or classes with anonymous union members), where the
3804 // operations performed by the constructor cannot be represented by
3805 // ctor-initializers.
3806 //
3807 // Skip this for empty non-union classes; we should not perform an
3808 // lvalue-to-rvalue conversion on them because their copy constructor does not
3809 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003810 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003811 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003812 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003813 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003814 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003815 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003816 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003817 }
3818
3819 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003820 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003821 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003822 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003823
John McCalld7bca762012-05-01 00:38:49 +00003824 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003825 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3826
Richard Smith08d6a2c2013-07-24 07:11:57 +00003827 // A scope for temporaries lifetime-extended by reference members.
3828 BlockScopeRAII LifetimeExtendedScope(Info);
3829
Richard Smith253c2a32012-01-27 01:14:48 +00003830 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003831 unsigned BasesSeen = 0;
3832#ifndef NDEBUG
3833 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3834#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003835 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003836 LValue Subobject = This;
3837 APValue *Value = &Result;
3838
3839 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003840 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003841 if (I->isBaseInitializer()) {
3842 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003843#ifndef NDEBUG
3844 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003845 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003846 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3847 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3848 "base class initializers not in expected order");
3849 ++BaseIt;
3850#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003851 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003852 BaseType->getAsCXXRecordDecl(), &Layout))
3853 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003854 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003855 } else if ((FD = I->getMember())) {
3856 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003857 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003858 if (RD->isUnion()) {
3859 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003860 Value = &Result.getUnionValue();
3861 } else {
3862 Value = &Result.getStructField(FD->getFieldIndex());
3863 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003864 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003865 // Walk the indirect field decl's chain to find the object to initialize,
3866 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003867 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003868 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003869 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3870 // Switch the union field if it differs. This happens if we had
3871 // preceding zero-initialization, and we're now initializing a union
3872 // subobject other than the first.
3873 // FIXME: In this case, the values of the other subobjects are
3874 // specified, since zero-initialization sets all padding bits to zero.
3875 if (Value->isUninit() ||
3876 (Value->isUnion() && Value->getUnionField() != FD)) {
3877 if (CD->isUnion())
3878 *Value = APValue(FD);
3879 else
3880 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003881 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003882 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003883 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003884 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003885 if (CD->isUnion())
3886 Value = &Value->getUnionValue();
3887 else
3888 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003889 }
Richard Smithd62306a2011-11-10 06:34:14 +00003890 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003891 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003892 }
Richard Smith253c2a32012-01-27 01:14:48 +00003893
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003895 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3896 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003897 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003898 // If we're checking for a potential constant expression, evaluate all
3899 // initializers even if some of them fail.
3900 if (!Info.keepEvaluatingAfterFailure())
3901 return false;
3902 Success = false;
3903 }
Richard Smithd62306a2011-11-10 06:34:14 +00003904 }
3905
Richard Smithd9f663b2013-04-22 15:31:51 +00003906 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00003907 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003908}
3909
Eli Friedman9a156e52008-11-12 09:44:48 +00003910//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003911// Generic Evaluation
3912//===----------------------------------------------------------------------===//
3913namespace {
3914
Aaron Ballman68af21c2014-01-03 19:26:43 +00003915template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003916class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003917 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003918private:
Richard Smith52a980a2015-08-28 02:43:42 +00003919 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003920 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003921 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003922 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003923 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003924 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003925 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003926
Richard Smith17100ba2012-02-16 02:46:34 +00003927 // Check whether a conditional operator with a non-constant condition is a
3928 // potential constant expression. If neither arm is a potential constant
3929 // expression, then the conditional operator is not either.
3930 template<typename ConditionalOperator>
3931 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003932 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003933
3934 // Speculatively evaluate both arms.
3935 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003936 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003937 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3938
3939 StmtVisitorTy::Visit(E->getFalseExpr());
3940 if (Diag.empty())
3941 return;
3942
3943 Diag.clear();
3944 StmtVisitorTy::Visit(E->getTrueExpr());
3945 if (Diag.empty())
3946 return;
3947 }
3948
3949 Error(E, diag::note_constexpr_conditional_never_const);
3950 }
3951
3952
3953 template<typename ConditionalOperator>
3954 bool HandleConditionalOperator(const ConditionalOperator *E) {
3955 bool BoolResult;
3956 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003957 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003958 CheckPotentialConstantConditional(E);
3959 return false;
3960 }
3961
3962 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3963 return StmtVisitorTy::Visit(EvalExpr);
3964 }
3965
Peter Collingbournee9200682011-05-13 03:29:01 +00003966protected:
3967 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003968 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003969 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3970
Richard Smith92b1ce02011-12-12 09:28:41 +00003971 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003972 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003973 }
3974
Aaron Ballman68af21c2014-01-03 19:26:43 +00003975 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003976
3977public:
3978 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3979
3980 EvalInfo &getEvalInfo() { return Info; }
3981
Richard Smithf57d8cb2011-12-09 22:58:01 +00003982 /// Report an evaluation error. This should only be called when an error is
3983 /// first discovered. When propagating an error, just return false.
3984 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003985 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003986 return false;
3987 }
3988 bool Error(const Expr *E) {
3989 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3990 }
3991
Aaron Ballman68af21c2014-01-03 19:26:43 +00003992 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003993 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003994 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003995 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003996 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003997 }
3998
Aaron Ballman68af21c2014-01-03 19:26:43 +00003999 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004000 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004001 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004003 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004004 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004005 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004006 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004007 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004008 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004009 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004010 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004011 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004012 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004013 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004014 // The initializer may not have been parsed yet, or might be erroneous.
4015 if (!E->getExpr())
4016 return Error(E);
4017 return StmtVisitorTy::Visit(E->getExpr());
4018 }
Richard Smith5894a912011-12-19 22:12:41 +00004019 // We cannot create any objects for which cleanups are required, so there is
4020 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004021 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004022 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004023
Aaron Ballman68af21c2014-01-03 19:26:43 +00004024 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004025 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4026 return static_cast<Derived*>(this)->VisitCastExpr(E);
4027 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004028 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004029 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4030 return static_cast<Derived*>(this)->VisitCastExpr(E);
4031 }
4032
Aaron Ballman68af21c2014-01-03 19:26:43 +00004033 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004034 switch (E->getOpcode()) {
4035 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004036 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004037
4038 case BO_Comma:
4039 VisitIgnoredValue(E->getLHS());
4040 return StmtVisitorTy::Visit(E->getRHS());
4041
4042 case BO_PtrMemD:
4043 case BO_PtrMemI: {
4044 LValue Obj;
4045 if (!HandleMemberPointerAccess(Info, E, Obj))
4046 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004047 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004048 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004049 return false;
4050 return DerivedSuccess(Result, E);
4051 }
4052 }
4053 }
4054
Aaron Ballman68af21c2014-01-03 19:26:43 +00004055 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004056 // Evaluate and cache the common expression. We treat it as a temporary,
4057 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004058 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004059 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004060 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004061
Richard Smith17100ba2012-02-16 02:46:34 +00004062 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004063 }
4064
Aaron Ballman68af21c2014-01-03 19:26:43 +00004065 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004066 bool IsBcpCall = false;
4067 // If the condition (ignoring parens) is a __builtin_constant_p call,
4068 // the result is a constant expression if it can be folded without
4069 // side-effects. This is an important GNU extension. See GCC PR38377
4070 // for discussion.
4071 if (const CallExpr *CallCE =
4072 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004073 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004074 IsBcpCall = true;
4075
4076 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4077 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004078 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004079 return false;
4080
Richard Smith6d4c6582013-11-05 22:18:15 +00004081 FoldConstant Fold(Info, IsBcpCall);
4082 if (!HandleConditionalOperator(E)) {
4083 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004084 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004085 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004086
4087 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004088 }
4089
Aaron Ballman68af21c2014-01-03 19:26:43 +00004090 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004091 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4092 return DerivedSuccess(*Value, E);
4093
4094 const Expr *Source = E->getSourceExpr();
4095 if (!Source)
4096 return Error(E);
4097 if (Source == E) { // sanity checking.
4098 assert(0 && "OpaqueValueExpr recursively refers to itself");
4099 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004100 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004101 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004102 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004103
Aaron Ballman68af21c2014-01-03 19:26:43 +00004104 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004105 APValue Result;
4106 if (!handleCallExpr(E, Result, nullptr))
4107 return false;
4108 return DerivedSuccess(Result, E);
4109 }
4110
4111 bool handleCallExpr(const CallExpr *E, APValue &Result,
4112 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004113 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004114 QualType CalleeType = Callee->getType();
4115
Craig Topper36250ad2014-05-12 05:36:57 +00004116 const FunctionDecl *FD = nullptr;
4117 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004118 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004119 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004120
Richard Smithe97cbd72011-11-11 04:05:33 +00004121 // Extract function decl and 'this' pointer from the callee.
4122 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004123 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004124 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4125 // Explicit bound member calls, such as x.f() or p->g();
4126 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004127 return false;
4128 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004129 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004130 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004131 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4132 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004133 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4134 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004135 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004136 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004137 return Error(Callee);
4138
4139 FD = dyn_cast<FunctionDecl>(Member);
4140 if (!FD)
4141 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004142 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004143 LValue Call;
4144 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004145 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004146
Richard Smitha8105bc2012-01-06 16:39:00 +00004147 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004148 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004149 FD = dyn_cast_or_null<FunctionDecl>(
4150 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004151 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004152 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004153
4154 // Overloaded operator calls to member functions are represented as normal
4155 // calls with '*this' as the first argument.
4156 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4157 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004158 // FIXME: When selecting an implicit conversion for an overloaded
4159 // operator delete, we sometimes try to evaluate calls to conversion
4160 // operators without a 'this' parameter!
4161 if (Args.empty())
4162 return Error(E);
4163
Richard Smithe97cbd72011-11-11 04:05:33 +00004164 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4165 return false;
4166 This = &ThisVal;
4167 Args = Args.slice(1);
4168 }
4169
4170 // Don't call function pointers which have been cast to some other type.
4171 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004172 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004173 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004174 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004175
Richard Smith47b34932012-02-01 02:39:43 +00004176 if (This && !This->checkSubobject(Info, E, CSK_This))
4177 return false;
4178
Richard Smith3607ffe2012-02-13 03:54:03 +00004179 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4180 // calls to such functions in constant expressions.
4181 if (This && !HasQualifier &&
4182 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4183 return Error(E, diag::note_constexpr_virtual_call);
4184
Craig Topper36250ad2014-05-12 05:36:57 +00004185 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004186 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004187
Richard Smith357362d2011-12-13 06:39:58 +00004188 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004189 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4190 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 return false;
4192
Richard Smith52a980a2015-08-28 02:43:42 +00004193 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004194 }
4195
Aaron Ballman68af21c2014-01-03 19:26:43 +00004196 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004197 return StmtVisitorTy::Visit(E->getInitializer());
4198 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004199 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004200 if (E->getNumInits() == 0)
4201 return DerivedZeroInitialization(E);
4202 if (E->getNumInits() == 1)
4203 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004204 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004205 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004206 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004207 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004208 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004209 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004210 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004211 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004212 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004213 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004214 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004215
Richard Smithd62306a2011-11-10 06:34:14 +00004216 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004217 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004218 assert(!E->isArrow() && "missing call to bound member function?");
4219
Richard Smith2e312c82012-03-03 22:46:17 +00004220 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004221 if (!Evaluate(Val, Info, E->getBase()))
4222 return false;
4223
4224 QualType BaseTy = E->getBase()->getType();
4225
4226 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004227 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004228 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004229 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004230 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4231
Richard Smith3229b742013-05-05 21:17:10 +00004232 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004233 SubobjectDesignator Designator(BaseTy);
4234 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004235
Richard Smith3229b742013-05-05 21:17:10 +00004236 APValue Result;
4237 return extractSubobject(Info, E, Obj, Designator, Result) &&
4238 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004239 }
4240
Aaron Ballman68af21c2014-01-03 19:26:43 +00004241 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004242 switch (E->getCastKind()) {
4243 default:
4244 break;
4245
Richard Smitha23ab512013-05-23 00:30:41 +00004246 case CK_AtomicToNonAtomic: {
4247 APValue AtomicVal;
4248 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4249 return false;
4250 return DerivedSuccess(AtomicVal, E);
4251 }
4252
Richard Smith11562c52011-10-28 17:51:58 +00004253 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004254 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004255 return StmtVisitorTy::Visit(E->getSubExpr());
4256
4257 case CK_LValueToRValue: {
4258 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004259 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4260 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004261 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004262 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004263 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004264 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004265 return false;
4266 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004267 }
4268 }
4269
Richard Smithf57d8cb2011-12-09 22:58:01 +00004270 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004271 }
4272
Aaron Ballman68af21c2014-01-03 19:26:43 +00004273 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004274 return VisitUnaryPostIncDec(UO);
4275 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004276 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004277 return VisitUnaryPostIncDec(UO);
4278 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004279 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004280 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004281 return Error(UO);
4282
4283 LValue LVal;
4284 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4285 return false;
4286 APValue RVal;
4287 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4288 UO->isIncrementOp(), &RVal))
4289 return false;
4290 return DerivedSuccess(RVal, UO);
4291 }
4292
Aaron Ballman68af21c2014-01-03 19:26:43 +00004293 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004294 // We will have checked the full-expressions inside the statement expression
4295 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004296 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004297 return Error(E);
4298
Richard Smith08d6a2c2013-07-24 07:11:57 +00004299 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004300 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004301 if (CS->body_empty())
4302 return true;
4303
Richard Smith51f03172013-06-20 03:00:05 +00004304 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4305 BE = CS->body_end();
4306 /**/; ++BI) {
4307 if (BI + 1 == BE) {
4308 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4309 if (!FinalExpr) {
4310 Info.Diag((*BI)->getLocStart(),
4311 diag::note_constexpr_stmt_expr_unsupported);
4312 return false;
4313 }
4314 return this->Visit(FinalExpr);
4315 }
4316
4317 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004318 StmtResult Result = { ReturnValue, nullptr };
4319 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004320 if (ESR != ESR_Succeeded) {
4321 // FIXME: If the statement-expression terminated due to 'return',
4322 // 'break', or 'continue', it would be nice to propagate that to
4323 // the outer statement evaluation rather than bailing out.
4324 if (ESR != ESR_Failed)
4325 Info.Diag((*BI)->getLocStart(),
4326 diag::note_constexpr_stmt_expr_unsupported);
4327 return false;
4328 }
4329 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004330
4331 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004332 }
4333
Richard Smith4a678122011-10-24 18:44:57 +00004334 /// Visit a value which is evaluated, but whose value is ignored.
4335 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004336 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004337 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004338};
4339
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004340}
Peter Collingbournee9200682011-05-13 03:29:01 +00004341
4342//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004343// Common base class for lvalue and temporary evaluation.
4344//===----------------------------------------------------------------------===//
4345namespace {
4346template<class Derived>
4347class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004348 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004349protected:
4350 LValue &Result;
4351 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004352 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004353
4354 bool Success(APValue::LValueBase B) {
4355 Result.set(B);
4356 return true;
4357 }
4358
4359public:
4360 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4361 ExprEvaluatorBaseTy(Info), Result(Result) {}
4362
Richard Smith2e312c82012-03-03 22:46:17 +00004363 bool Success(const APValue &V, const Expr *E) {
4364 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004365 return true;
4366 }
Richard Smith027bf112011-11-17 22:56:20 +00004367
Richard Smith027bf112011-11-17 22:56:20 +00004368 bool VisitMemberExpr(const MemberExpr *E) {
4369 // Handle non-static data members.
4370 QualType BaseTy;
4371 if (E->isArrow()) {
4372 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4373 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004374 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004375 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004376 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004377 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4378 return false;
4379 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004380 } else {
4381 if (!this->Visit(E->getBase()))
4382 return false;
4383 BaseTy = E->getBase()->getType();
4384 }
Richard Smith027bf112011-11-17 22:56:20 +00004385
Richard Smith1b78b3d2012-01-25 22:15:11 +00004386 const ValueDecl *MD = E->getMemberDecl();
4387 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4388 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4389 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4390 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004391 if (!HandleLValueMember(this->Info, E, Result, FD))
4392 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004393 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004394 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4395 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004396 } else
4397 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004398
Richard Smith1b78b3d2012-01-25 22:15:11 +00004399 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004400 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004401 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004402 RefValue))
4403 return false;
4404 return Success(RefValue, E);
4405 }
4406 return true;
4407 }
4408
4409 bool VisitBinaryOperator(const BinaryOperator *E) {
4410 switch (E->getOpcode()) {
4411 default:
4412 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4413
4414 case BO_PtrMemD:
4415 case BO_PtrMemI:
4416 return HandleMemberPointerAccess(this->Info, E, Result);
4417 }
4418 }
4419
4420 bool VisitCastExpr(const CastExpr *E) {
4421 switch (E->getCastKind()) {
4422 default:
4423 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4424
4425 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004426 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004427 if (!this->Visit(E->getSubExpr()))
4428 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004429
4430 // Now figure out the necessary offset to add to the base LV to get from
4431 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004432 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4433 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004434 }
4435 }
4436};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004437}
Richard Smith027bf112011-11-17 22:56:20 +00004438
4439//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004440// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004441//
4442// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4443// function designators (in C), decl references to void objects (in C), and
4444// temporaries (if building with -Wno-address-of-temporary).
4445//
4446// LValue evaluation produces values comprising a base expression of one of the
4447// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004448// - Declarations
4449// * VarDecl
4450// * FunctionDecl
4451// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004452// * CompoundLiteralExpr in C
4453// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004454// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004455// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004456// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004457// * ObjCEncodeExpr
4458// * AddrLabelExpr
4459// * BlockExpr
4460// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004461// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004462// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004463// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004464// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4465// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004466// * A MaterializeTemporaryExpr that has static storage duration, with no
4467// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004468// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004469//===----------------------------------------------------------------------===//
4470namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004471class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004472 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004473public:
Richard Smith027bf112011-11-17 22:56:20 +00004474 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4475 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004476
Richard Smith11562c52011-10-28 17:51:58 +00004477 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004478 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004479
Peter Collingbournee9200682011-05-13 03:29:01 +00004480 bool VisitDeclRefExpr(const DeclRefExpr *E);
4481 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004482 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004483 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4484 bool VisitMemberExpr(const MemberExpr *E);
4485 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4486 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004487 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004488 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004489 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4490 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004491 bool VisitUnaryReal(const UnaryOperator *E);
4492 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004493 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4494 return VisitUnaryPreIncDec(UO);
4495 }
4496 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4497 return VisitUnaryPreIncDec(UO);
4498 }
Richard Smith3229b742013-05-05 21:17:10 +00004499 bool VisitBinAssign(const BinaryOperator *BO);
4500 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004501
Peter Collingbournee9200682011-05-13 03:29:01 +00004502 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004503 switch (E->getCastKind()) {
4504 default:
Richard Smith027bf112011-11-17 22:56:20 +00004505 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004506
Eli Friedmance3e02a2011-10-11 00:13:24 +00004507 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004508 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004509 if (!Visit(E->getSubExpr()))
4510 return false;
4511 Result.Designator.setInvalid();
4512 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004513
Richard Smith027bf112011-11-17 22:56:20 +00004514 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004515 if (!Visit(E->getSubExpr()))
4516 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004517 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004518 }
4519 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004520};
4521} // end anonymous namespace
4522
Richard Smith11562c52011-10-28 17:51:58 +00004523/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004524/// expressions which are not glvalues, in two cases:
4525/// * function designators in C, and
4526/// * "extern void" objects
4527static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4528 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4529 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004530 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004531}
4532
Peter Collingbournee9200682011-05-13 03:29:01 +00004533bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004534 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004535 return Success(FD);
4536 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004537 return VisitVarDecl(E, VD);
4538 return Error(E);
4539}
Richard Smith733237d2011-10-24 23:14:33 +00004540
Richard Smith11562c52011-10-28 17:51:58 +00004541bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004542 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004543 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4544 Frame = Info.CurrentCall;
4545
Richard Smithfec09922011-11-01 16:57:24 +00004546 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004547 if (Frame) {
4548 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004549 return true;
4550 }
Richard Smithce40ad62011-11-12 22:28:03 +00004551 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004552 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004553
Richard Smith3229b742013-05-05 21:17:10 +00004554 APValue *V;
4555 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004556 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004557 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004558 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004559 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4560 return false;
4561 }
Richard Smith3229b742013-05-05 21:17:10 +00004562 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004563}
4564
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004565bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4566 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004567 // Walk through the expression to find the materialized temporary itself.
4568 SmallVector<const Expr *, 2> CommaLHSs;
4569 SmallVector<SubobjectAdjustment, 2> Adjustments;
4570 const Expr *Inner = E->GetTemporaryExpr()->
4571 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004572
Richard Smith84401042013-06-03 05:03:02 +00004573 // If we passed any comma operators, evaluate their LHSs.
4574 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4575 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4576 return false;
4577
Richard Smithe6c01442013-06-05 00:46:14 +00004578 // A materialized temporary with static storage duration can appear within the
4579 // result of a constant expression evaluation, so we need to preserve its
4580 // value for use outside this evaluation.
4581 APValue *Value;
4582 if (E->getStorageDuration() == SD_Static) {
4583 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004584 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004585 Result.set(E);
4586 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004587 Value = &Info.CurrentCall->
4588 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004589 Result.set(E, Info.CurrentCall->Index);
4590 }
4591
Richard Smithea4ad5d2013-06-06 08:19:16 +00004592 QualType Type = Inner->getType();
4593
Richard Smith84401042013-06-03 05:03:02 +00004594 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004595 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4596 (E->getStorageDuration() == SD_Static &&
4597 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4598 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004599 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004600 }
Richard Smith84401042013-06-03 05:03:02 +00004601
4602 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004603 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4604 --I;
4605 switch (Adjustments[I].Kind) {
4606 case SubobjectAdjustment::DerivedToBaseAdjustment:
4607 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4608 Type, Result))
4609 return false;
4610 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4611 break;
4612
4613 case SubobjectAdjustment::FieldAdjustment:
4614 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4615 return false;
4616 Type = Adjustments[I].Field->getType();
4617 break;
4618
4619 case SubobjectAdjustment::MemberPointerAdjustment:
4620 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4621 Adjustments[I].Ptr.RHS))
4622 return false;
4623 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4624 break;
4625 }
4626 }
4627
4628 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004629}
4630
Peter Collingbournee9200682011-05-13 03:29:01 +00004631bool
4632LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004633 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4634 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4635 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004636 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004637}
4638
Richard Smith6e525142011-12-27 12:18:28 +00004639bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004640 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004641 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004642
4643 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4644 << E->getExprOperand()->getType()
4645 << E->getExprOperand()->getSourceRange();
4646 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004647}
4648
Francois Pichet0066db92012-04-16 04:08:35 +00004649bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4650 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004651}
Francois Pichet0066db92012-04-16 04:08:35 +00004652
Peter Collingbournee9200682011-05-13 03:29:01 +00004653bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004654 // Handle static data members.
4655 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4656 VisitIgnoredValue(E->getBase());
4657 return VisitVarDecl(E, VD);
4658 }
4659
Richard Smith254a73d2011-10-28 22:34:42 +00004660 // Handle static member functions.
4661 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4662 if (MD->isStatic()) {
4663 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004664 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004665 }
4666 }
4667
Richard Smithd62306a2011-11-10 06:34:14 +00004668 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004669 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004670}
4671
Peter Collingbournee9200682011-05-13 03:29:01 +00004672bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004673 // FIXME: Deal with vectors as array subscript bases.
4674 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004675 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004676
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004677 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004678 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004679
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004680 APSInt Index;
4681 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004682 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004683
Richard Smith861b5b52013-05-07 23:34:45 +00004684 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4685 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004686}
Eli Friedman9a156e52008-11-12 09:44:48 +00004687
Peter Collingbournee9200682011-05-13 03:29:01 +00004688bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004689 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004690}
4691
Richard Smith66c96992012-02-18 22:04:06 +00004692bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4693 if (!Visit(E->getSubExpr()))
4694 return false;
4695 // __real is a no-op on scalar lvalues.
4696 if (E->getSubExpr()->getType()->isAnyComplexType())
4697 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4698 return true;
4699}
4700
4701bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4702 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4703 "lvalue __imag__ on scalar?");
4704 if (!Visit(E->getSubExpr()))
4705 return false;
4706 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4707 return true;
4708}
4709
Richard Smith243ef902013-05-05 23:31:59 +00004710bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004711 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004712 return Error(UO);
4713
4714 if (!this->Visit(UO->getSubExpr()))
4715 return false;
4716
Richard Smith243ef902013-05-05 23:31:59 +00004717 return handleIncDec(
4718 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004719 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004720}
4721
4722bool LValueExprEvaluator::VisitCompoundAssignOperator(
4723 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004724 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004725 return Error(CAO);
4726
Richard Smith3229b742013-05-05 21:17:10 +00004727 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004728
4729 // The overall lvalue result is the result of evaluating the LHS.
4730 if (!this->Visit(CAO->getLHS())) {
4731 if (Info.keepEvaluatingAfterFailure())
4732 Evaluate(RHS, this->Info, CAO->getRHS());
4733 return false;
4734 }
4735
Richard Smith3229b742013-05-05 21:17:10 +00004736 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4737 return false;
4738
Richard Smith43e77732013-05-07 04:50:00 +00004739 return handleCompoundAssignment(
4740 this->Info, CAO,
4741 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4742 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004743}
4744
4745bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004746 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004747 return Error(E);
4748
Richard Smith3229b742013-05-05 21:17:10 +00004749 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004750
4751 if (!this->Visit(E->getLHS())) {
4752 if (Info.keepEvaluatingAfterFailure())
4753 Evaluate(NewVal, this->Info, E->getRHS());
4754 return false;
4755 }
4756
Richard Smith3229b742013-05-05 21:17:10 +00004757 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4758 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004759
4760 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004761 NewVal);
4762}
4763
Eli Friedman9a156e52008-11-12 09:44:48 +00004764//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004765// Pointer Evaluation
4766//===----------------------------------------------------------------------===//
4767
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004768namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004769class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004770 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004771 LValue &Result;
4772
Peter Collingbournee9200682011-05-13 03:29:01 +00004773 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004774 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004775 return true;
4776 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004777public:
Mike Stump11289f42009-09-09 15:08:12 +00004778
John McCall45d55e42010-05-07 21:00:08 +00004779 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004780 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004781
Richard Smith2e312c82012-03-03 22:46:17 +00004782 bool Success(const APValue &V, const Expr *E) {
4783 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004784 return true;
4785 }
Richard Smithfddd3842011-12-30 21:15:51 +00004786 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004787 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004788 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004789
John McCall45d55e42010-05-07 21:00:08 +00004790 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004791 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004792 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004793 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004794 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004795 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004796 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004797 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004798 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004799 bool VisitCallExpr(const CallExpr *E);
4800 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004801 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004802 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004803 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004804 }
Richard Smithd62306a2011-11-10 06:34:14 +00004805 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004806 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004807 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004808 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004809 if (!Info.CurrentCall->This) {
4810 if (Info.getLangOpts().CPlusPlus11)
4811 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4812 else
4813 Info.Diag(E);
4814 return false;
4815 }
Richard Smithd62306a2011-11-10 06:34:14 +00004816 Result = *Info.CurrentCall->This;
4817 return true;
4818 }
John McCallc07a0c72011-02-17 10:25:35 +00004819
Eli Friedman449fe542009-03-23 04:56:01 +00004820 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004821};
Chris Lattner05706e882008-07-11 18:11:29 +00004822} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004823
John McCall45d55e42010-05-07 21:00:08 +00004824static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004825 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004826 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004827}
4828
John McCall45d55e42010-05-07 21:00:08 +00004829bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004830 if (E->getOpcode() != BO_Add &&
4831 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004832 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004833
Chris Lattner05706e882008-07-11 18:11:29 +00004834 const Expr *PExp = E->getLHS();
4835 const Expr *IExp = E->getRHS();
4836 if (IExp->getType()->isPointerType())
4837 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004838
Richard Smith253c2a32012-01-27 01:14:48 +00004839 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4840 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004842
John McCall45d55e42010-05-07 21:00:08 +00004843 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004844 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004845 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004846
4847 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004848 if (E->getOpcode() == BO_Sub)
4849 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004850
Ted Kremenek28831752012-08-23 20:46:57 +00004851 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004852 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4853 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004854}
Eli Friedman9a156e52008-11-12 09:44:48 +00004855
John McCall45d55e42010-05-07 21:00:08 +00004856bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4857 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004858}
Mike Stump11289f42009-09-09 15:08:12 +00004859
Peter Collingbournee9200682011-05-13 03:29:01 +00004860bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4861 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004862
Eli Friedman847a2bc2009-12-27 05:43:15 +00004863 switch (E->getCastKind()) {
4864 default:
4865 break;
4866
John McCalle3027922010-08-25 11:45:40 +00004867 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004868 case CK_CPointerToObjCPointerCast:
4869 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004870 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004871 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004872 if (!Visit(SubExpr))
4873 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004874 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4875 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4876 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004877 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004878 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004879 if (SubExpr->getType()->isVoidPointerType())
4880 CCEDiag(E, diag::note_constexpr_invalid_cast)
4881 << 3 << SubExpr->getType();
4882 else
4883 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4884 }
Richard Smith96e0c102011-11-04 02:25:55 +00004885 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004886
Anders Carlsson18275092010-10-31 20:41:46 +00004887 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004888 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004889 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004890 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004891 if (!Result.Base && Result.Offset.isZero())
4892 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004893
Richard Smithd62306a2011-11-10 06:34:14 +00004894 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004895 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004896 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4897 castAs<PointerType>()->getPointeeType(),
4898 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004899
Richard Smith027bf112011-11-17 22:56:20 +00004900 case CK_BaseToDerived:
4901 if (!Visit(E->getSubExpr()))
4902 return false;
4903 if (!Result.Base && Result.Offset.isZero())
4904 return true;
4905 return HandleBaseToDerivedCast(Info, E, Result);
4906
Richard Smith0b0a0b62011-10-29 20:57:55 +00004907 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004908 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004909 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004910
John McCalle3027922010-08-25 11:45:40 +00004911 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004912 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4913
Richard Smith2e312c82012-03-03 22:46:17 +00004914 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004915 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004916 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004917
John McCall45d55e42010-05-07 21:00:08 +00004918 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004919 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4920 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004921 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004922 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004923 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004924 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004925 return true;
4926 } else {
4927 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004928 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004929 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004930 }
4931 }
John McCalle3027922010-08-25 11:45:40 +00004932 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004933 if (SubExpr->isGLValue()) {
4934 if (!EvaluateLValue(SubExpr, Result, Info))
4935 return false;
4936 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004937 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004938 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004939 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004940 return false;
4941 }
Richard Smith96e0c102011-11-04 02:25:55 +00004942 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004943 if (const ConstantArrayType *CAT
4944 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4945 Result.addArray(Info, E, CAT);
4946 else
4947 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004948 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004949
John McCalle3027922010-08-25 11:45:40 +00004950 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004951 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004952 }
4953
Richard Smith11562c52011-10-28 17:51:58 +00004954 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004955}
Chris Lattner05706e882008-07-11 18:11:29 +00004956
Hal Finkel0dd05d42014-10-03 17:18:37 +00004957static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4958 // C++ [expr.alignof]p3:
4959 // When alignof is applied to a reference type, the result is the
4960 // alignment of the referenced type.
4961 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4962 T = Ref->getPointeeType();
4963
4964 // __alignof is defined to return the preferred alignment.
4965 return Info.Ctx.toCharUnitsFromBits(
4966 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4967}
4968
4969static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4970 E = E->IgnoreParens();
4971
4972 // The kinds of expressions that we have special-case logic here for
4973 // should be kept up to date with the special checks for those
4974 // expressions in Sema.
4975
4976 // alignof decl is always accepted, even if it doesn't make sense: we default
4977 // to 1 in those cases.
4978 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4979 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4980 /*RefAsPointee*/true);
4981
4982 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4983 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4984 /*RefAsPointee*/true);
4985
4986 return GetAlignOfType(Info, E->getType());
4987}
4988
Peter Collingbournee9200682011-05-13 03:29:01 +00004989bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004990 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004991 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004992
Alp Tokera724cff2013-12-28 21:59:02 +00004993 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004994 case Builtin::BI__builtin_addressof:
4995 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00004996 case Builtin::BI__builtin_assume_aligned: {
4997 // We need to be very careful here because: if the pointer does not have the
4998 // asserted alignment, then the behavior is undefined, and undefined
4999 // behavior is non-constant.
5000 if (!EvaluatePointer(E->getArg(0), Result, Info))
5001 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005002
Hal Finkel0dd05d42014-10-03 17:18:37 +00005003 LValue OffsetResult(Result);
5004 APSInt Alignment;
5005 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5006 return false;
5007 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5008
5009 if (E->getNumArgs() > 2) {
5010 APSInt Offset;
5011 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5012 return false;
5013
5014 int64_t AdditionalOffset = -getExtValue(Offset);
5015 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5016 }
5017
5018 // If there is a base object, then it must have the correct alignment.
5019 if (OffsetResult.Base) {
5020 CharUnits BaseAlignment;
5021 if (const ValueDecl *VD =
5022 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5023 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5024 } else {
5025 BaseAlignment =
5026 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5027 }
5028
5029 if (BaseAlignment < Align) {
5030 Result.Designator.setInvalid();
5031 // FIXME: Quantities here cast to integers because the plural modifier
5032 // does not work on APSInts yet.
5033 CCEDiag(E->getArg(0),
5034 diag::note_constexpr_baa_insufficient_alignment) << 0
5035 << (int) BaseAlignment.getQuantity()
5036 << (unsigned) getExtValue(Alignment);
5037 return false;
5038 }
5039 }
5040
5041 // The offset must also have the correct alignment.
5042 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5043 Result.Designator.setInvalid();
5044 APSInt Offset(64, false);
5045 Offset = OffsetResult.Offset.getQuantity();
5046
5047 if (OffsetResult.Base)
5048 CCEDiag(E->getArg(0),
5049 diag::note_constexpr_baa_insufficient_alignment) << 1
5050 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5051 else
5052 CCEDiag(E->getArg(0),
5053 diag::note_constexpr_baa_value_insufficient_alignment)
5054 << Offset << (unsigned) getExtValue(Alignment);
5055
5056 return false;
5057 }
5058
5059 return true;
5060 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005061 default:
5062 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5063 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005064}
Chris Lattner05706e882008-07-11 18:11:29 +00005065
5066//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005067// Member Pointer Evaluation
5068//===----------------------------------------------------------------------===//
5069
5070namespace {
5071class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005072 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005073 MemberPtr &Result;
5074
5075 bool Success(const ValueDecl *D) {
5076 Result = MemberPtr(D);
5077 return true;
5078 }
5079public:
5080
5081 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5082 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5083
Richard Smith2e312c82012-03-03 22:46:17 +00005084 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005085 Result.setFrom(V);
5086 return true;
5087 }
Richard Smithfddd3842011-12-30 21:15:51 +00005088 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005089 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005090 }
5091
5092 bool VisitCastExpr(const CastExpr *E);
5093 bool VisitUnaryAddrOf(const UnaryOperator *E);
5094};
5095} // end anonymous namespace
5096
5097static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5098 EvalInfo &Info) {
5099 assert(E->isRValue() && E->getType()->isMemberPointerType());
5100 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5101}
5102
5103bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5104 switch (E->getCastKind()) {
5105 default:
5106 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5107
5108 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005109 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005110 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005111
5112 case CK_BaseToDerivedMemberPointer: {
5113 if (!Visit(E->getSubExpr()))
5114 return false;
5115 if (E->path_empty())
5116 return true;
5117 // Base-to-derived member pointer casts store the path in derived-to-base
5118 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5119 // the wrong end of the derived->base arc, so stagger the path by one class.
5120 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5121 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5122 PathI != PathE; ++PathI) {
5123 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5124 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5125 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005126 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005127 }
5128 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5129 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005130 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005131 return true;
5132 }
5133
5134 case CK_DerivedToBaseMemberPointer:
5135 if (!Visit(E->getSubExpr()))
5136 return false;
5137 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5138 PathE = E->path_end(); PathI != PathE; ++PathI) {
5139 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5140 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5141 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005143 }
5144 return true;
5145 }
5146}
5147
5148bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5149 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5150 // member can be formed.
5151 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5152}
5153
5154//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005155// Record Evaluation
5156//===----------------------------------------------------------------------===//
5157
5158namespace {
5159 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005160 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005161 const LValue &This;
5162 APValue &Result;
5163 public:
5164
5165 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5166 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5167
Richard Smith2e312c82012-03-03 22:46:17 +00005168 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005169 Result = V;
5170 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005171 }
Richard Smithfddd3842011-12-30 21:15:51 +00005172 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005173
Richard Smith52a980a2015-08-28 02:43:42 +00005174 bool VisitCallExpr(const CallExpr *E) {
5175 return handleCallExpr(E, Result, &This);
5176 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005177 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005178 bool VisitInitListExpr(const InitListExpr *E);
5179 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005180 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005181 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005182}
Richard Smithd62306a2011-11-10 06:34:14 +00005183
Richard Smithfddd3842011-12-30 21:15:51 +00005184/// Perform zero-initialization on an object of non-union class type.
5185/// C++11 [dcl.init]p5:
5186/// To zero-initialize an object or reference of type T means:
5187/// [...]
5188/// -- if T is a (possibly cv-qualified) non-union class type,
5189/// each non-static data member and each base-class subobject is
5190/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005191static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5192 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005193 const LValue &This, APValue &Result) {
5194 assert(!RD->isUnion() && "Expected non-union class type");
5195 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5196 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005197 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005198
John McCalld7bca762012-05-01 00:38:49 +00005199 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005200 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5201
5202 if (CD) {
5203 unsigned Index = 0;
5204 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005205 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005206 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5207 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005208 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5209 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005210 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005211 Result.getStructBase(Index)))
5212 return false;
5213 }
5214 }
5215
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005216 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005217 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005218 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005219 continue;
5220
5221 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005222 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005223 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005224
David Blaikie2d7c57e2012-04-30 02:36:29 +00005225 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005226 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005227 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005228 return false;
5229 }
5230
5231 return true;
5232}
5233
5234bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5235 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005236 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005237 if (RD->isUnion()) {
5238 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5239 // object's first non-static named data member is zero-initialized
5240 RecordDecl::field_iterator I = RD->field_begin();
5241 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005242 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005243 return true;
5244 }
5245
5246 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005247 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005248 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005249 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005250 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005251 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005252 }
5253
Richard Smith5d108602012-02-17 00:44:16 +00005254 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005255 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005256 return false;
5257 }
5258
Richard Smitha8105bc2012-01-06 16:39:00 +00005259 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005260}
5261
Richard Smithe97cbd72011-11-11 04:05:33 +00005262bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5263 switch (E->getCastKind()) {
5264 default:
5265 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5266
5267 case CK_ConstructorConversion:
5268 return Visit(E->getSubExpr());
5269
5270 case CK_DerivedToBase:
5271 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005272 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005273 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005274 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005275 if (!DerivedObject.isStruct())
5276 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005277
5278 // Derived-to-base rvalue conversion: just slice off the derived part.
5279 APValue *Value = &DerivedObject;
5280 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5281 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5282 PathE = E->path_end(); PathI != PathE; ++PathI) {
5283 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5284 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5285 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5286 RD = Base;
5287 }
5288 Result = *Value;
5289 return true;
5290 }
5291 }
5292}
5293
Richard Smithd62306a2011-11-10 06:34:14 +00005294bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5295 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005296 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005297 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5298
5299 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005300 const FieldDecl *Field = E->getInitializedFieldInUnion();
5301 Result = APValue(Field);
5302 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005303 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005304
5305 // If the initializer list for a union does not contain any elements, the
5306 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005307 // FIXME: The element should be initialized from an initializer list.
5308 // Is this difference ever observable for initializer lists which
5309 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005310 ImplicitValueInitExpr VIE(Field->getType());
5311 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5312
Richard Smithd62306a2011-11-10 06:34:14 +00005313 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005314 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5315 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005316
5317 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5318 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5319 isa<CXXDefaultInitExpr>(InitExpr));
5320
Richard Smithb228a862012-02-15 02:18:13 +00005321 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005322 }
5323
5324 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5325 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005326 Result = APValue(APValue::UninitStruct(), 0,
5327 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005328 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005329 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005330 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005331 // Anonymous bit-fields are not considered members of the class for
5332 // purposes of aggregate initialization.
5333 if (Field->isUnnamedBitfield())
5334 continue;
5335
5336 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005337
Richard Smith253c2a32012-01-27 01:14:48 +00005338 bool HaveInit = ElementNo < E->getNumInits();
5339
5340 // FIXME: Diagnostics here should point to the end of the initializer
5341 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005342 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005343 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005344 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005345
5346 // Perform an implicit value-initialization for members beyond the end of
5347 // the initializer list.
5348 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005349 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005350
Richard Smith852c9db2013-04-20 22:23:05 +00005351 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5352 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5353 isa<CXXDefaultInitExpr>(Init));
5354
Richard Smith49ca8aa2013-08-06 07:09:20 +00005355 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5356 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5357 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005358 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005359 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005360 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005361 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005362 }
5363 }
5364
Richard Smith253c2a32012-01-27 01:14:48 +00005365 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005366}
5367
5368bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5369 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005370 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5371
Richard Smithfddd3842011-12-30 21:15:51 +00005372 bool ZeroInit = E->requiresZeroInitialization();
5373 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005374 // If we've already performed zero-initialization, we're already done.
5375 if (!Result.isUninit())
5376 return true;
5377
Richard Smithda3f4fd2014-03-05 23:32:50 +00005378 // We can get here in two different ways:
5379 // 1) We're performing value-initialization, and should zero-initialize
5380 // the object, or
5381 // 2) We're performing default-initialization of an object with a trivial
5382 // constexpr default constructor, in which case we should start the
5383 // lifetimes of all the base subobjects (there can be no data member
5384 // subobjects in this case) per [basic.life]p1.
5385 // Either way, ZeroInitialization is appropriate.
5386 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005387 }
5388
Craig Topper36250ad2014-05-12 05:36:57 +00005389 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005390 FD->getBody(Definition);
5391
Richard Smith357362d2011-12-13 06:39:58 +00005392 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5393 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005394
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005395 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005396 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005397 if (const MaterializeTemporaryExpr *ME
5398 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5399 return Visit(ME->GetTemporaryExpr());
5400
Richard Smithfddd3842011-12-30 21:15:51 +00005401 if (ZeroInit && !ZeroInitialization(E))
5402 return false;
5403
Craig Topper5fc8fc22014-08-27 06:28:36 +00005404 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005405 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005406 cast<CXXConstructorDecl>(Definition), Info,
5407 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005408}
5409
Richard Smithcc1b96d2013-06-12 22:31:48 +00005410bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5411 const CXXStdInitializerListExpr *E) {
5412 const ConstantArrayType *ArrayType =
5413 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5414
5415 LValue Array;
5416 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5417 return false;
5418
5419 // Get a pointer to the first element of the array.
5420 Array.addArray(Info, E, ArrayType);
5421
5422 // FIXME: Perform the checks on the field types in SemaInit.
5423 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5424 RecordDecl::field_iterator Field = Record->field_begin();
5425 if (Field == Record->field_end())
5426 return Error(E);
5427
5428 // Start pointer.
5429 if (!Field->getType()->isPointerType() ||
5430 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5431 ArrayType->getElementType()))
5432 return Error(E);
5433
5434 // FIXME: What if the initializer_list type has base classes, etc?
5435 Result = APValue(APValue::UninitStruct(), 0, 2);
5436 Array.moveInto(Result.getStructField(0));
5437
5438 if (++Field == Record->field_end())
5439 return Error(E);
5440
5441 if (Field->getType()->isPointerType() &&
5442 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5443 ArrayType->getElementType())) {
5444 // End pointer.
5445 if (!HandleLValueArrayAdjustment(Info, E, Array,
5446 ArrayType->getElementType(),
5447 ArrayType->getSize().getZExtValue()))
5448 return false;
5449 Array.moveInto(Result.getStructField(1));
5450 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5451 // Length.
5452 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5453 else
5454 return Error(E);
5455
5456 if (++Field != Record->field_end())
5457 return Error(E);
5458
5459 return true;
5460}
5461
Richard Smithd62306a2011-11-10 06:34:14 +00005462static bool EvaluateRecord(const Expr *E, const LValue &This,
5463 APValue &Result, EvalInfo &Info) {
5464 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005465 "can't evaluate expression as a record rvalue");
5466 return RecordExprEvaluator(Info, This, Result).Visit(E);
5467}
5468
5469//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005470// Temporary Evaluation
5471//
5472// Temporaries are represented in the AST as rvalues, but generally behave like
5473// lvalues. The full-object of which the temporary is a subobject is implicitly
5474// materialized so that a reference can bind to it.
5475//===----------------------------------------------------------------------===//
5476namespace {
5477class TemporaryExprEvaluator
5478 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5479public:
5480 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5481 LValueExprEvaluatorBaseTy(Info, Result) {}
5482
5483 /// Visit an expression which constructs the value of this temporary.
5484 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005485 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005486 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5487 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005488 }
5489
5490 bool VisitCastExpr(const CastExpr *E) {
5491 switch (E->getCastKind()) {
5492 default:
5493 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5494
5495 case CK_ConstructorConversion:
5496 return VisitConstructExpr(E->getSubExpr());
5497 }
5498 }
5499 bool VisitInitListExpr(const InitListExpr *E) {
5500 return VisitConstructExpr(E);
5501 }
5502 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5503 return VisitConstructExpr(E);
5504 }
5505 bool VisitCallExpr(const CallExpr *E) {
5506 return VisitConstructExpr(E);
5507 }
Richard Smith513955c2014-12-17 19:24:30 +00005508 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5509 return VisitConstructExpr(E);
5510 }
Richard Smith027bf112011-11-17 22:56:20 +00005511};
5512} // end anonymous namespace
5513
5514/// Evaluate an expression of record type as a temporary.
5515static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005516 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005517 return TemporaryExprEvaluator(Info, Result).Visit(E);
5518}
5519
5520//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005521// Vector Evaluation
5522//===----------------------------------------------------------------------===//
5523
5524namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005525 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005526 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005527 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005528 public:
Mike Stump11289f42009-09-09 15:08:12 +00005529
Richard Smith2d406342011-10-22 21:10:00 +00005530 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5531 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005532
Richard Smith2d406342011-10-22 21:10:00 +00005533 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5534 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5535 // FIXME: remove this APValue copy.
5536 Result = APValue(V.data(), V.size());
5537 return true;
5538 }
Richard Smith2e312c82012-03-03 22:46:17 +00005539 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005540 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005541 Result = V;
5542 return true;
5543 }
Richard Smithfddd3842011-12-30 21:15:51 +00005544 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005545
Richard Smith2d406342011-10-22 21:10:00 +00005546 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005547 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005548 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005549 bool VisitInitListExpr(const InitListExpr *E);
5550 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005551 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005552 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005553 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005554 };
5555} // end anonymous namespace
5556
5557static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005558 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005559 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005560}
5561
Richard Smith2d406342011-10-22 21:10:00 +00005562bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5563 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005564 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005565
Richard Smith161f09a2011-12-06 22:44:34 +00005566 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005567 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005568
Eli Friedmanc757de22011-03-25 00:43:55 +00005569 switch (E->getCastKind()) {
5570 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005571 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005572 if (SETy->isIntegerType()) {
5573 APSInt IntResult;
5574 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005575 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005576 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005577 } else if (SETy->isRealFloatingType()) {
5578 APFloat F(0.0);
5579 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005580 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005581 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005582 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005583 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005584 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005585
5586 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005587 SmallVector<APValue, 4> Elts(NElts, Val);
5588 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005589 }
Eli Friedman803acb32011-12-22 03:51:45 +00005590 case CK_BitCast: {
5591 // Evaluate the operand into an APInt we can extract from.
5592 llvm::APInt SValInt;
5593 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5594 return false;
5595 // Extract the elements
5596 QualType EltTy = VTy->getElementType();
5597 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5598 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5599 SmallVector<APValue, 4> Elts;
5600 if (EltTy->isRealFloatingType()) {
5601 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005602 unsigned FloatEltSize = EltSize;
5603 if (&Sem == &APFloat::x87DoubleExtended)
5604 FloatEltSize = 80;
5605 for (unsigned i = 0; i < NElts; i++) {
5606 llvm::APInt Elt;
5607 if (BigEndian)
5608 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5609 else
5610 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005611 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005612 }
5613 } else if (EltTy->isIntegerType()) {
5614 for (unsigned i = 0; i < NElts; i++) {
5615 llvm::APInt Elt;
5616 if (BigEndian)
5617 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5618 else
5619 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5620 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5621 }
5622 } else {
5623 return Error(E);
5624 }
5625 return Success(Elts, E);
5626 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005627 default:
Richard Smith11562c52011-10-28 17:51:58 +00005628 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005629 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005630}
5631
Richard Smith2d406342011-10-22 21:10:00 +00005632bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005633VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005634 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005635 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005636 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005637
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005638 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005639 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005640
Eli Friedmanb9c71292012-01-03 23:24:20 +00005641 // The number of initializers can be less than the number of
5642 // vector elements. For OpenCL, this can be due to nested vector
5643 // initialization. For GCC compatibility, missing trailing elements
5644 // should be initialized with zeroes.
5645 unsigned CountInits = 0, CountElts = 0;
5646 while (CountElts < NumElements) {
5647 // Handle nested vector initialization.
5648 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005649 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005650 APValue v;
5651 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5652 return Error(E);
5653 unsigned vlen = v.getVectorLength();
5654 for (unsigned j = 0; j < vlen; j++)
5655 Elements.push_back(v.getVectorElt(j));
5656 CountElts += vlen;
5657 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005658 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005659 if (CountInits < NumInits) {
5660 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005661 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005662 } else // trailing integer zero.
5663 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5664 Elements.push_back(APValue(sInt));
5665 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005666 } else {
5667 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005668 if (CountInits < NumInits) {
5669 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005670 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005671 } else // trailing float zero.
5672 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5673 Elements.push_back(APValue(f));
5674 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005675 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005676 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005677 }
Richard Smith2d406342011-10-22 21:10:00 +00005678 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005679}
5680
Richard Smith2d406342011-10-22 21:10:00 +00005681bool
Richard Smithfddd3842011-12-30 21:15:51 +00005682VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005683 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005684 QualType EltTy = VT->getElementType();
5685 APValue ZeroElement;
5686 if (EltTy->isIntegerType())
5687 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5688 else
5689 ZeroElement =
5690 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5691
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005692 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005693 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005694}
5695
Richard Smith2d406342011-10-22 21:10:00 +00005696bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005697 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005698 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005699}
5700
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005701//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005702// Array Evaluation
5703//===----------------------------------------------------------------------===//
5704
5705namespace {
5706 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005707 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005708 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005709 APValue &Result;
5710 public:
5711
Richard Smithd62306a2011-11-10 06:34:14 +00005712 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5713 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005714
5715 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005716 assert((V.isArray() || V.isLValue()) &&
5717 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005718 Result = V;
5719 return true;
5720 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005721
Richard Smithfddd3842011-12-30 21:15:51 +00005722 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005723 const ConstantArrayType *CAT =
5724 Info.Ctx.getAsConstantArrayType(E->getType());
5725 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005726 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005727
5728 Result = APValue(APValue::UninitArray(), 0,
5729 CAT->getSize().getZExtValue());
5730 if (!Result.hasArrayFiller()) return true;
5731
Richard Smithfddd3842011-12-30 21:15:51 +00005732 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005733 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005734 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005735 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005736 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005737 }
5738
Richard Smith52a980a2015-08-28 02:43:42 +00005739 bool VisitCallExpr(const CallExpr *E) {
5740 return handleCallExpr(E, Result, &This);
5741 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005742 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005743 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005744 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5745 const LValue &Subobject,
5746 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005747 };
5748} // end anonymous namespace
5749
Richard Smithd62306a2011-11-10 06:34:14 +00005750static bool EvaluateArray(const Expr *E, const LValue &This,
5751 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005752 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005753 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005754}
5755
5756bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5757 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5758 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005759 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005760
Richard Smithca2cfbf2011-12-22 01:07:19 +00005761 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5762 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005763 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005764 LValue LV;
5765 if (!EvaluateLValue(E->getInit(0), LV, Info))
5766 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005767 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005768 LV.moveInto(Val);
5769 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005770 }
5771
Richard Smith253c2a32012-01-27 01:14:48 +00005772 bool Success = true;
5773
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005774 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5775 "zero-initialized array shouldn't have any initialized elts");
5776 APValue Filler;
5777 if (Result.isArray() && Result.hasArrayFiller())
5778 Filler = Result.getArrayFiller();
5779
Richard Smith9543c5e2013-04-22 14:44:29 +00005780 unsigned NumEltsToInit = E->getNumInits();
5781 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005782 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005783
5784 // If the initializer might depend on the array index, run it for each
5785 // array element. For now, just whitelist non-class value-initialization.
5786 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5787 NumEltsToInit = NumElts;
5788
5789 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005790
5791 // If the array was previously zero-initialized, preserve the
5792 // zero-initialized values.
5793 if (!Filler.isUninit()) {
5794 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5795 Result.getArrayInitializedElt(I) = Filler;
5796 if (Result.hasArrayFiller())
5797 Result.getArrayFiller() = Filler;
5798 }
5799
Richard Smithd62306a2011-11-10 06:34:14 +00005800 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005801 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005802 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5803 const Expr *Init =
5804 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005805 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005806 Info, Subobject, Init) ||
5807 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005808 CAT->getElementType(), 1)) {
5809 if (!Info.keepEvaluatingAfterFailure())
5810 return false;
5811 Success = false;
5812 }
Richard Smithd62306a2011-11-10 06:34:14 +00005813 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005814
Richard Smith9543c5e2013-04-22 14:44:29 +00005815 if (!Result.hasArrayFiller())
5816 return Success;
5817
5818 // If we get here, we have a trivial filler, which we can just evaluate
5819 // once and splat over the rest of the array elements.
5820 assert(FillerExpr && "no array filler for incomplete init list");
5821 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5822 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005823}
5824
Richard Smith027bf112011-11-17 22:56:20 +00005825bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005826 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5827}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005828
Richard Smith9543c5e2013-04-22 14:44:29 +00005829bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5830 const LValue &Subobject,
5831 APValue *Value,
5832 QualType Type) {
5833 bool HadZeroInit = !Value->isUninit();
5834
5835 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5836 unsigned N = CAT->getSize().getZExtValue();
5837
5838 // Preserve the array filler if we had prior zero-initialization.
5839 APValue Filler =
5840 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5841 : APValue();
5842
5843 *Value = APValue(APValue::UninitArray(), N, N);
5844
5845 if (HadZeroInit)
5846 for (unsigned I = 0; I != N; ++I)
5847 Value->getArrayInitializedElt(I) = Filler;
5848
5849 // Initialize the elements.
5850 LValue ArrayElt = Subobject;
5851 ArrayElt.addArray(Info, E, CAT);
5852 for (unsigned I = 0; I != N; ++I)
5853 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5854 CAT->getElementType()) ||
5855 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5856 CAT->getElementType(), 1))
5857 return false;
5858
5859 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005860 }
Richard Smith027bf112011-11-17 22:56:20 +00005861
Richard Smith9543c5e2013-04-22 14:44:29 +00005862 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005863 return Error(E);
5864
Richard Smith027bf112011-11-17 22:56:20 +00005865 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005866
Richard Smithfddd3842011-12-30 21:15:51 +00005867 bool ZeroInit = E->requiresZeroInitialization();
5868 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005869 if (HadZeroInit)
5870 return true;
5871
Richard Smithda3f4fd2014-03-05 23:32:50 +00005872 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5873 ImplicitValueInitExpr VIE(Type);
5874 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005875 }
5876
Craig Topper36250ad2014-05-12 05:36:57 +00005877 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005878 FD->getBody(Definition);
5879
Richard Smith357362d2011-12-13 06:39:58 +00005880 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5881 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005882
Richard Smith9eae7232012-01-12 18:54:33 +00005883 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005884 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005885 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005886 return false;
5887 }
5888
Craig Topper5fc8fc22014-08-27 06:28:36 +00005889 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005890 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005891 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005892 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005893}
5894
Richard Smithf3e9e432011-11-07 09:22:26 +00005895//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005896// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005897//
5898// As a GNU extension, we support casting pointers to sufficiently-wide integer
5899// types and back in constant folding. Integer values are thus represented
5900// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005901//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005902
5903namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005904class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005905 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005906 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005907public:
Richard Smith2e312c82012-03-03 22:46:17 +00005908 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005909 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005910
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005911 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005912 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005913 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005914 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005915 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005916 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005917 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005918 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005919 return true;
5920 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005921 bool Success(const llvm::APSInt &SI, const Expr *E) {
5922 return Success(SI, E, Result);
5923 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005925 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005926 assert(E->getType()->isIntegralOrEnumerationType() &&
5927 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005928 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005929 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005930 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005931 Result.getInt().setIsUnsigned(
5932 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005933 return true;
5934 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005935 bool Success(const llvm::APInt &I, const Expr *E) {
5936 return Success(I, E, Result);
5937 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005938
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005939 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005940 assert(E->getType()->isIntegralOrEnumerationType() &&
5941 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005942 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005943 return true;
5944 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005945 bool Success(uint64_t Value, const Expr *E) {
5946 return Success(Value, E, Result);
5947 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005948
Ken Dyckdbc01912011-03-11 02:13:43 +00005949 bool Success(CharUnits Size, const Expr *E) {
5950 return Success(Size.getQuantity(), E);
5951 }
5952
Richard Smith2e312c82012-03-03 22:46:17 +00005953 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005954 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005955 Result = V;
5956 return true;
5957 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005958 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005959 }
Mike Stump11289f42009-09-09 15:08:12 +00005960
Richard Smithfddd3842011-12-30 21:15:51 +00005961 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005962
Peter Collingbournee9200682011-05-13 03:29:01 +00005963 //===--------------------------------------------------------------------===//
5964 // Visitor Methods
5965 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005966
Chris Lattner7174bf32008-07-12 00:38:25 +00005967 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005968 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005969 }
5970 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005971 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005972 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005973
5974 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5975 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005976 if (CheckReferencedDecl(E, E->getDecl()))
5977 return true;
5978
5979 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005980 }
5981 bool VisitMemberExpr(const MemberExpr *E) {
5982 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005983 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005984 return true;
5985 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005986
5987 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005988 }
5989
Peter Collingbournee9200682011-05-13 03:29:01 +00005990 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005991 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005992 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005993 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005994
Peter Collingbournee9200682011-05-13 03:29:01 +00005995 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005996 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005997
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005998 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005999 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006000 }
Mike Stump11289f42009-09-09 15:08:12 +00006001
Ted Kremeneke65b0862012-03-06 20:05:56 +00006002 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6003 return Success(E->getValue(), E);
6004 }
6005
Richard Smith4ce706a2011-10-11 21:43:33 +00006006 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006007 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006008 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006009 }
6010
Douglas Gregor29c42f22012-02-24 07:38:34 +00006011 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6012 return Success(E->getValue(), E);
6013 }
6014
John Wiegley6242b6a2011-04-28 00:16:57 +00006015 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6016 return Success(E->getValue(), E);
6017 }
6018
John Wiegleyf9f65842011-04-25 06:54:41 +00006019 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6020 return Success(E->getValue(), E);
6021 }
6022
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006023 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006024 bool VisitUnaryImag(const UnaryOperator *E);
6025
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006026 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006027 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006028
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006029private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006030 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006031 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006032};
Chris Lattner05706e882008-07-11 18:11:29 +00006033} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006034
Richard Smith11562c52011-10-28 17:51:58 +00006035/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6036/// produce either the integer value or a pointer.
6037///
6038/// GCC has a heinous extension which folds casts between pointer types and
6039/// pointer-sized integral types. We support this by allowing the evaluation of
6040/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6041/// Some simple arithmetic on such values is supported (they are treated much
6042/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006043static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006044 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006045 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006046 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006047}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006048
Richard Smithf57d8cb2011-12-09 22:58:01 +00006049static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006050 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006051 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006052 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006053 if (!Val.isInt()) {
6054 // FIXME: It would be better to produce the diagnostic for casting
6055 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006056 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006057 return false;
6058 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006059 Result = Val.getInt();
6060 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006061}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006062
Richard Smithf57d8cb2011-12-09 22:58:01 +00006063/// Check whether the given declaration can be directly converted to an integral
6064/// rvalue. If not, no diagnostic is produced; there are other things we can
6065/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006066bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006067 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006068 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006069 // Check for signedness/width mismatches between E type and ECD value.
6070 bool SameSign = (ECD->getInitVal().isSigned()
6071 == E->getType()->isSignedIntegerOrEnumerationType());
6072 bool SameWidth = (ECD->getInitVal().getBitWidth()
6073 == Info.Ctx.getIntWidth(E->getType()));
6074 if (SameSign && SameWidth)
6075 return Success(ECD->getInitVal(), E);
6076 else {
6077 // Get rid of mismatch (otherwise Success assertions will fail)
6078 // by computing a new value matching the type of E.
6079 llvm::APSInt Val = ECD->getInitVal();
6080 if (!SameSign)
6081 Val.setIsSigned(!ECD->getInitVal().isSigned());
6082 if (!SameWidth)
6083 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6084 return Success(Val, E);
6085 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006086 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006087 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006088}
6089
Chris Lattner86ee2862008-10-06 06:40:35 +00006090/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6091/// as GCC.
6092static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6093 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006094 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006095 enum gcc_type_class {
6096 no_type_class = -1,
6097 void_type_class, integer_type_class, char_type_class,
6098 enumeral_type_class, boolean_type_class,
6099 pointer_type_class, reference_type_class, offset_type_class,
6100 real_type_class, complex_type_class,
6101 function_type_class, method_type_class,
6102 record_type_class, union_type_class,
6103 array_type_class, string_type_class,
6104 lang_type_class
6105 };
Mike Stump11289f42009-09-09 15:08:12 +00006106
6107 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006108 // ideal, however it is what gcc does.
6109 if (E->getNumArgs() == 0)
6110 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006111
Chris Lattner86ee2862008-10-06 06:40:35 +00006112 QualType ArgTy = E->getArg(0)->getType();
6113 if (ArgTy->isVoidType())
6114 return void_type_class;
6115 else if (ArgTy->isEnumeralType())
6116 return enumeral_type_class;
6117 else if (ArgTy->isBooleanType())
6118 return boolean_type_class;
6119 else if (ArgTy->isCharType())
6120 return string_type_class; // gcc doesn't appear to use char_type_class
6121 else if (ArgTy->isIntegerType())
6122 return integer_type_class;
6123 else if (ArgTy->isPointerType())
6124 return pointer_type_class;
6125 else if (ArgTy->isReferenceType())
6126 return reference_type_class;
6127 else if (ArgTy->isRealType())
6128 return real_type_class;
6129 else if (ArgTy->isComplexType())
6130 return complex_type_class;
6131 else if (ArgTy->isFunctionType())
6132 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006133 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006134 return record_type_class;
6135 else if (ArgTy->isUnionType())
6136 return union_type_class;
6137 else if (ArgTy->isArrayType())
6138 return array_type_class;
6139 else if (ArgTy->isUnionType())
6140 return union_type_class;
6141 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006142 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006143}
6144
Richard Smith5fab0c92011-12-28 19:48:30 +00006145/// EvaluateBuiltinConstantPForLValue - Determine the result of
6146/// __builtin_constant_p when applied to the given lvalue.
6147///
6148/// An lvalue is only "constant" if it is a pointer or reference to the first
6149/// character of a string literal.
6150template<typename LValue>
6151static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006152 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006153 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6154}
6155
6156/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6157/// GCC as we can manage.
6158static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6159 QualType ArgType = Arg->getType();
6160
6161 // __builtin_constant_p always has one operand. The rules which gcc follows
6162 // are not precisely documented, but are as follows:
6163 //
6164 // - If the operand is of integral, floating, complex or enumeration type,
6165 // and can be folded to a known value of that type, it returns 1.
6166 // - If the operand and can be folded to a pointer to the first character
6167 // of a string literal (or such a pointer cast to an integral type), it
6168 // returns 1.
6169 //
6170 // Otherwise, it returns 0.
6171 //
6172 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6173 // its support for this does not currently work.
6174 if (ArgType->isIntegralOrEnumerationType()) {
6175 Expr::EvalResult Result;
6176 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6177 return false;
6178
6179 APValue &V = Result.Val;
6180 if (V.getKind() == APValue::Int)
6181 return true;
6182
6183 return EvaluateBuiltinConstantPForLValue(V);
6184 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6185 return Arg->isEvaluatable(Ctx);
6186 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6187 LValue LV;
6188 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006189 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006190 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6191 : EvaluatePointer(Arg, LV, Info)) &&
6192 !Status.HasSideEffects)
6193 return EvaluateBuiltinConstantPForLValue(LV);
6194 }
6195
6196 // Anything else isn't considered to be sufficiently constant.
6197 return false;
6198}
6199
John McCall95007602010-05-10 23:27:23 +00006200/// Retrieves the "underlying object type" of the given expression,
6201/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006202static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006203 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6204 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006205 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006206 } else if (const Expr *E = B.get<const Expr*>()) {
6207 if (isa<CompoundLiteralExpr>(E))
6208 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006209 }
6210
6211 return QualType();
6212}
6213
George Burgess IVbdb5b262015-08-19 02:19:07 +00006214bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6215 unsigned Type) {
6216 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006217 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006218 {
6219 // The operand of __builtin_object_size is never evaluated for side-effects.
6220 // If there are any, but we can determine the pointed-to object anyway, then
6221 // ignore the side-effects.
6222 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006223 FoldConstant Fold(Info, true);
Richard Smith01ade172012-05-23 04:13:20 +00006224 if (!EvaluatePointer(E->getArg(0), Base, Info))
6225 return false;
6226 }
John McCall95007602010-05-10 23:27:23 +00006227
George Burgess IVbdb5b262015-08-19 02:19:07 +00006228 CharUnits BaseOffset = Base.getLValueOffset();
6229
6230 // If we point to before the start of the object, there are no
6231 // accessible bytes.
6232 if (BaseOffset < CharUnits::Zero())
6233 return Success(0, E);
6234
6235 // MostDerivedType is null if we're dealing with a literal such as nullptr or
6236 // (char*)0x100000. Lower it to LLVM in either case so it can figure out what
6237 // to do with it.
6238 // FIXME(gbiv): Try to do a better job with this in clang.
6239 if (Base.Designator.MostDerivedType.isNull())
Nico Weber19999b42015-08-18 20:32:55 +00006240 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006241
6242 // If Type & 1 is 0, the object in question is the complete object; reset to
6243 // a complete object designator in that case.
6244 //
6245 // If Type is 1 and we've lost track of the subobject, just find the complete
6246 // object instead. (If Type is 3, that's not correct behavior and we should
6247 // return 0 instead.)
6248 LValue End = Base;
6249 if (((Type & 1) == 0) || (End.Designator.Invalid && Type == 1)) {
6250 QualType T = getObjectType(End.getLValueBase());
6251 if (T.isNull())
6252 End.Designator.setInvalid();
6253 else {
6254 End.Designator = SubobjectDesignator(T);
6255 End.Offset = CharUnits::Zero();
6256 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006257 }
John McCall95007602010-05-10 23:27:23 +00006258
George Burgess IVbdb5b262015-08-19 02:19:07 +00006259 // FIXME: We should produce a valid object size for an unknown object with a
6260 // known designator, if Type & 1 is 1. For instance:
6261 //
6262 // extern struct X { char buff[32]; int a, b, c; } *p;
6263 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6264 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6265 //
6266 // This is GCC's behavior. We currently don't do this, but (hopefully) will in
6267 // the near future.
6268
6269 // If it is not possible to determine which objects ptr points to at compile
6270 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6271 // and (size_t) 0 for type 2 or 3.
6272 if (End.Designator.Invalid)
6273 return false;
6274
6275 // According to the GCC documentation, we want the size of the subobject
6276 // denoted by the pointer. But that's not quite right -- what we actually
6277 // want is the size of the immediately-enclosing array, if there is one.
6278 int64_t AmountToAdd = 1;
6279 if (End.Designator.MostDerivedArraySize &&
6280 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6281 // We got a pointer to an array. Step to its end.
6282 AmountToAdd = End.Designator.MostDerivedArraySize -
6283 End.Designator.Entries.back().ArrayIndex;
6284 } else if (End.Designator.IsOnePastTheEnd) {
6285 // We're already pointing at the end of the object.
6286 AmountToAdd = 0;
6287 }
6288
6289 if (End.Designator.MostDerivedType->isIncompleteType() ||
6290 End.Designator.MostDerivedType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006291 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006292
George Burgess IVbdb5b262015-08-19 02:19:07 +00006293 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6294 AmountToAdd))
6295 return false;
John McCall95007602010-05-10 23:27:23 +00006296
George Burgess IVbdb5b262015-08-19 02:19:07 +00006297 auto EndOffset = End.getLValueOffset();
6298 if (BaseOffset > EndOffset)
6299 return Success(0, E);
6300
6301 return Success(EndOffset - BaseOffset, E);
John McCall95007602010-05-10 23:27:23 +00006302}
6303
Peter Collingbournee9200682011-05-13 03:29:01 +00006304bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006305 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006306 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006307 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006308
6309 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006310 // The type was checked when we built the expression.
6311 unsigned Type =
6312 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6313 assert(Type <= 3 && "unexpected type");
6314
6315 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006316 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006317
Richard Smith0421ce72012-08-07 04:16:51 +00006318 // If evaluating the argument has side-effects, we can't determine the size
6319 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6320 // handle all cases where the expression has side-effects.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006321 // Likewise, if Type is 3, we must handle this because CodeGen cannot give a
6322 // conservatively correct answer in that case.
6323 if (E->getArg(0)->HasSideEffects(Info.Ctx) || Type == 3)
6324 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006325
Richard Smith01ade172012-05-23 04:13:20 +00006326 // Expression had no side effects, but we couldn't statically determine the
6327 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006328 switch (Info.EvalMode) {
6329 case EvalInfo::EM_ConstantExpression:
6330 case EvalInfo::EM_PotentialConstantExpression:
6331 case EvalInfo::EM_ConstantFold:
6332 case EvalInfo::EM_EvaluateForOverflow:
6333 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006334 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006335 return Error(E);
6336 case EvalInfo::EM_ConstantExpressionUnevaluated:
6337 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006338 // Reduce it to a constant now.
6339 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006340 }
Mike Stump722cedf2009-10-26 18:35:08 +00006341 }
6342
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006343 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006344 case Builtin::BI__builtin_bswap32:
6345 case Builtin::BI__builtin_bswap64: {
6346 APSInt Val;
6347 if (!EvaluateInteger(E->getArg(0), Val, Info))
6348 return false;
6349
6350 return Success(Val.byteSwap(), E);
6351 }
6352
Richard Smith8889a3d2013-06-13 06:26:32 +00006353 case Builtin::BI__builtin_classify_type:
6354 return Success(EvaluateBuiltinClassifyType(E), E);
6355
6356 // FIXME: BI__builtin_clrsb
6357 // FIXME: BI__builtin_clrsbl
6358 // FIXME: BI__builtin_clrsbll
6359
Richard Smith80b3c8e2013-06-13 05:04:16 +00006360 case Builtin::BI__builtin_clz:
6361 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006362 case Builtin::BI__builtin_clzll:
6363 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006364 APSInt Val;
6365 if (!EvaluateInteger(E->getArg(0), Val, Info))
6366 return false;
6367 if (!Val)
6368 return Error(E);
6369
6370 return Success(Val.countLeadingZeros(), E);
6371 }
6372
Richard Smith8889a3d2013-06-13 06:26:32 +00006373 case Builtin::BI__builtin_constant_p:
6374 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6375
Richard Smith80b3c8e2013-06-13 05:04:16 +00006376 case Builtin::BI__builtin_ctz:
6377 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006378 case Builtin::BI__builtin_ctzll:
6379 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006380 APSInt Val;
6381 if (!EvaluateInteger(E->getArg(0), Val, Info))
6382 return false;
6383 if (!Val)
6384 return Error(E);
6385
6386 return Success(Val.countTrailingZeros(), E);
6387 }
6388
Richard Smith8889a3d2013-06-13 06:26:32 +00006389 case Builtin::BI__builtin_eh_return_data_regno: {
6390 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6391 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6392 return Success(Operand, E);
6393 }
6394
6395 case Builtin::BI__builtin_expect:
6396 return Visit(E->getArg(0));
6397
6398 case Builtin::BI__builtin_ffs:
6399 case Builtin::BI__builtin_ffsl:
6400 case Builtin::BI__builtin_ffsll: {
6401 APSInt Val;
6402 if (!EvaluateInteger(E->getArg(0), Val, Info))
6403 return false;
6404
6405 unsigned N = Val.countTrailingZeros();
6406 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6407 }
6408
6409 case Builtin::BI__builtin_fpclassify: {
6410 APFloat Val(0.0);
6411 if (!EvaluateFloat(E->getArg(5), Val, Info))
6412 return false;
6413 unsigned Arg;
6414 switch (Val.getCategory()) {
6415 case APFloat::fcNaN: Arg = 0; break;
6416 case APFloat::fcInfinity: Arg = 1; break;
6417 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6418 case APFloat::fcZero: Arg = 4; break;
6419 }
6420 return Visit(E->getArg(Arg));
6421 }
6422
6423 case Builtin::BI__builtin_isinf_sign: {
6424 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006425 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006426 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6427 }
6428
Richard Smithea3019d2013-10-15 19:07:14 +00006429 case Builtin::BI__builtin_isinf: {
6430 APFloat Val(0.0);
6431 return EvaluateFloat(E->getArg(0), Val, Info) &&
6432 Success(Val.isInfinity() ? 1 : 0, E);
6433 }
6434
6435 case Builtin::BI__builtin_isfinite: {
6436 APFloat Val(0.0);
6437 return EvaluateFloat(E->getArg(0), Val, Info) &&
6438 Success(Val.isFinite() ? 1 : 0, E);
6439 }
6440
6441 case Builtin::BI__builtin_isnan: {
6442 APFloat Val(0.0);
6443 return EvaluateFloat(E->getArg(0), Val, Info) &&
6444 Success(Val.isNaN() ? 1 : 0, E);
6445 }
6446
6447 case Builtin::BI__builtin_isnormal: {
6448 APFloat Val(0.0);
6449 return EvaluateFloat(E->getArg(0), Val, Info) &&
6450 Success(Val.isNormal() ? 1 : 0, E);
6451 }
6452
Richard Smith8889a3d2013-06-13 06:26:32 +00006453 case Builtin::BI__builtin_parity:
6454 case Builtin::BI__builtin_parityl:
6455 case Builtin::BI__builtin_parityll: {
6456 APSInt Val;
6457 if (!EvaluateInteger(E->getArg(0), Val, Info))
6458 return false;
6459
6460 return Success(Val.countPopulation() % 2, E);
6461 }
6462
Richard Smith80b3c8e2013-06-13 05:04:16 +00006463 case Builtin::BI__builtin_popcount:
6464 case Builtin::BI__builtin_popcountl:
6465 case Builtin::BI__builtin_popcountll: {
6466 APSInt Val;
6467 if (!EvaluateInteger(E->getArg(0), Val, Info))
6468 return false;
6469
6470 return Success(Val.countPopulation(), E);
6471 }
6472
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006473 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006474 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006475 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006476 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006477 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6478 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006479 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006480 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006481 case Builtin::BI__builtin_strlen: {
6482 // As an extension, we support __builtin_strlen() as a constant expression,
6483 // and support folding strlen() to a constant.
6484 LValue String;
6485 if (!EvaluatePointer(E->getArg(0), String, Info))
6486 return false;
6487
6488 // Fast path: if it's a string literal, search the string value.
6489 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6490 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006491 // The string literal may have embedded null characters. Find the first
6492 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006493 StringRef Str = S->getBytes();
6494 int64_t Off = String.Offset.getQuantity();
6495 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6496 S->getCharByteWidth() == 1) {
6497 Str = Str.substr(Off);
6498
6499 StringRef::size_type Pos = Str.find(0);
6500 if (Pos != StringRef::npos)
6501 Str = Str.substr(0, Pos);
6502
6503 return Success(Str.size(), E);
6504 }
6505
6506 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006507 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006508
6509 // Slow path: scan the bytes of the string looking for the terminating 0.
6510 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6511 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6512 APValue Char;
6513 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6514 !Char.isInt())
6515 return false;
6516 if (!Char.getInt())
6517 return Success(Strlen, E);
6518 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6519 return false;
6520 }
6521 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006522
Richard Smith01ba47d2012-04-13 00:45:38 +00006523 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006524 case Builtin::BI__atomic_is_lock_free:
6525 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006526 APSInt SizeVal;
6527 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6528 return false;
6529
6530 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6531 // of two less than the maximum inline atomic width, we know it is
6532 // lock-free. If the size isn't a power of two, or greater than the
6533 // maximum alignment where we promote atomics, we know it is not lock-free
6534 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6535 // the answer can only be determined at runtime; for example, 16-byte
6536 // atomics have lock-free implementations on some, but not all,
6537 // x86-64 processors.
6538
6539 // Check power-of-two.
6540 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006541 if (Size.isPowerOfTwo()) {
6542 // Check against inlining width.
6543 unsigned InlineWidthBits =
6544 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6545 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6546 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6547 Size == CharUnits::One() ||
6548 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6549 Expr::NPC_NeverValueDependent))
6550 // OK, we will inline appropriately-aligned operations of this size,
6551 // and _Atomic(T) is appropriately-aligned.
6552 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006553
Richard Smith01ba47d2012-04-13 00:45:38 +00006554 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6555 castAs<PointerType>()->getPointeeType();
6556 if (!PointeeType->isIncompleteType() &&
6557 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6558 // OK, we will inline operations on this object.
6559 return Success(1, E);
6560 }
6561 }
6562 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006563
Richard Smith01ba47d2012-04-13 00:45:38 +00006564 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6565 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006566 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006567 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006568}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006569
Richard Smith8b3497e2011-10-31 01:37:14 +00006570static bool HasSameBase(const LValue &A, const LValue &B) {
6571 if (!A.getLValueBase())
6572 return !B.getLValueBase();
6573 if (!B.getLValueBase())
6574 return false;
6575
Richard Smithce40ad62011-11-12 22:28:03 +00006576 if (A.getLValueBase().getOpaqueValue() !=
6577 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006578 const Decl *ADecl = GetLValueBaseDecl(A);
6579 if (!ADecl)
6580 return false;
6581 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006582 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006583 return false;
6584 }
6585
6586 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006587 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006588}
6589
Richard Smithd20f1e62014-10-21 23:01:04 +00006590/// \brief Determine whether this is a pointer past the end of the complete
6591/// object referred to by the lvalue.
6592static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6593 const LValue &LV) {
6594 // A null pointer can be viewed as being "past the end" but we don't
6595 // choose to look at it that way here.
6596 if (!LV.getLValueBase())
6597 return false;
6598
6599 // If the designator is valid and refers to a subobject, we're not pointing
6600 // past the end.
6601 if (!LV.getLValueDesignator().Invalid &&
6602 !LV.getLValueDesignator().isOnePastTheEnd())
6603 return false;
6604
David Majnemerc378ca52015-08-29 08:32:55 +00006605 // A pointer to an incomplete type might be past-the-end if the type's size is
6606 // zero. We cannot tell because the type is incomplete.
6607 QualType Ty = getType(LV.getLValueBase());
6608 if (Ty->isIncompleteType())
6609 return true;
6610
Richard Smithd20f1e62014-10-21 23:01:04 +00006611 // We're a past-the-end pointer if we point to the byte after the object,
6612 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006613 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006614 return LV.getLValueOffset() == Size;
6615}
6616
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006617namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006618
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006619/// \brief Data recursive integer evaluator of certain binary operators.
6620///
6621/// We use a data recursive algorithm for binary operators so that we are able
6622/// to handle extreme cases of chained binary operators without causing stack
6623/// overflow.
6624class DataRecursiveIntBinOpEvaluator {
6625 struct EvalResult {
6626 APValue Val;
6627 bool Failed;
6628
6629 EvalResult() : Failed(false) { }
6630
6631 void swap(EvalResult &RHS) {
6632 Val.swap(RHS.Val);
6633 Failed = RHS.Failed;
6634 RHS.Failed = false;
6635 }
6636 };
6637
6638 struct Job {
6639 const Expr *E;
6640 EvalResult LHSResult; // meaningful only for binary operator expression.
6641 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006642
David Blaikie73726062015-08-12 23:09:24 +00006643 Job() = default;
6644 Job(Job &&J)
6645 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6646 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6647 J.StoredInfo = nullptr;
6648 }
6649
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006650 void startSpeculativeEval(EvalInfo &Info) {
6651 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006652 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006653 StoredInfo = &Info;
6654 }
6655 ~Job() {
6656 if (StoredInfo) {
6657 StoredInfo->EvalStatus = OldEvalStatus;
6658 }
6659 }
6660 private:
David Blaikie73726062015-08-12 23:09:24 +00006661 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006662 Expr::EvalStatus OldEvalStatus;
6663 };
6664
6665 SmallVector<Job, 16> Queue;
6666
6667 IntExprEvaluator &IntEval;
6668 EvalInfo &Info;
6669 APValue &FinalResult;
6670
6671public:
6672 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6673 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6674
6675 /// \brief True if \param E is a binary operator that we are going to handle
6676 /// data recursively.
6677 /// We handle binary operators that are comma, logical, or that have operands
6678 /// with integral or enumeration type.
6679 static bool shouldEnqueue(const BinaryOperator *E) {
6680 return E->getOpcode() == BO_Comma ||
6681 E->isLogicalOp() ||
6682 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6683 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006684 }
6685
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006686 bool Traverse(const BinaryOperator *E) {
6687 enqueue(E);
6688 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006689 while (!Queue.empty())
6690 process(PrevResult);
6691
6692 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006693
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006694 FinalResult.swap(PrevResult.Val);
6695 return true;
6696 }
6697
6698private:
6699 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6700 return IntEval.Success(Value, E, Result);
6701 }
6702 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6703 return IntEval.Success(Value, E, Result);
6704 }
6705 bool Error(const Expr *E) {
6706 return IntEval.Error(E);
6707 }
6708 bool Error(const Expr *E, diag::kind D) {
6709 return IntEval.Error(E, D);
6710 }
6711
6712 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6713 return Info.CCEDiag(E, D);
6714 }
6715
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006716 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6717 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006718 bool &SuppressRHSDiags);
6719
6720 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6721 const BinaryOperator *E, APValue &Result);
6722
6723 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6724 Result.Failed = !Evaluate(Result.Val, Info, E);
6725 if (Result.Failed)
6726 Result.Val = APValue();
6727 }
6728
Richard Trieuba4d0872012-03-21 23:30:30 +00006729 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006730
6731 void enqueue(const Expr *E) {
6732 E = E->IgnoreParens();
6733 Queue.resize(Queue.size()+1);
6734 Queue.back().E = E;
6735 Queue.back().Kind = Job::AnyExprKind;
6736 }
6737};
6738
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006739}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006740
6741bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006742 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006743 bool &SuppressRHSDiags) {
6744 if (E->getOpcode() == BO_Comma) {
6745 // Ignore LHS but note if we could not evaluate it.
6746 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006747 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006748 return true;
6749 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006750
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006751 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006752 bool LHSAsBool;
6753 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006754 // We were able to evaluate the LHS, see if we can get away with not
6755 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006756 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6757 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006758 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006759 }
6760 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006761 LHSResult.Failed = true;
6762
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006763 // Since we weren't able to evaluate the left hand side, it
6764 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006765 if (!Info.noteSideEffect())
6766 return false;
6767
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006768 // We can't evaluate the LHS; however, sometimes the result
6769 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6770 // Don't ignore RHS and suppress diagnostics from this arm.
6771 SuppressRHSDiags = true;
6772 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006773
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006774 return true;
6775 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006776
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006777 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6778 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006779
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006780 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006781 return false; // Ignore RHS;
6782
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006783 return true;
6784}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006785
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006786bool DataRecursiveIntBinOpEvaluator::
6787 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6788 const BinaryOperator *E, APValue &Result) {
6789 if (E->getOpcode() == BO_Comma) {
6790 if (RHSResult.Failed)
6791 return false;
6792 Result = RHSResult.Val;
6793 return true;
6794 }
6795
6796 if (E->isLogicalOp()) {
6797 bool lhsResult, rhsResult;
6798 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6799 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6800
6801 if (LHSIsOK) {
6802 if (RHSIsOK) {
6803 if (E->getOpcode() == BO_LOr)
6804 return Success(lhsResult || rhsResult, E, Result);
6805 else
6806 return Success(lhsResult && rhsResult, E, Result);
6807 }
6808 } else {
6809 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006810 // We can't evaluate the LHS; however, sometimes the result
6811 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6812 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006813 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006814 }
6815 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006816
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006817 return false;
6818 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006819
6820 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6821 E->getRHS()->getType()->isIntegralOrEnumerationType());
6822
6823 if (LHSResult.Failed || RHSResult.Failed)
6824 return false;
6825
6826 const APValue &LHSVal = LHSResult.Val;
6827 const APValue &RHSVal = RHSResult.Val;
6828
6829 // Handle cases like (unsigned long)&a + 4.
6830 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6831 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006832 CharUnits AdditionalOffset =
6833 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006834 if (E->getOpcode() == BO_Add)
6835 Result.getLValueOffset() += AdditionalOffset;
6836 else
6837 Result.getLValueOffset() -= AdditionalOffset;
6838 return true;
6839 }
6840
6841 // Handle cases like 4 + (unsigned long)&a
6842 if (E->getOpcode() == BO_Add &&
6843 RHSVal.isLValue() && LHSVal.isInt()) {
6844 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006845 Result.getLValueOffset() +=
6846 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006847 return true;
6848 }
6849
6850 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6851 // Handle (intptr_t)&&A - (intptr_t)&&B.
6852 if (!LHSVal.getLValueOffset().isZero() ||
6853 !RHSVal.getLValueOffset().isZero())
6854 return false;
6855 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6856 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6857 if (!LHSExpr || !RHSExpr)
6858 return false;
6859 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6860 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6861 if (!LHSAddrExpr || !RHSAddrExpr)
6862 return false;
6863 // Make sure both labels come from the same function.
6864 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6865 RHSAddrExpr->getLabel()->getDeclContext())
6866 return false;
6867 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6868 return true;
6869 }
Richard Smith43e77732013-05-07 04:50:00 +00006870
6871 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006872 if (!LHSVal.isInt() || !RHSVal.isInt())
6873 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006874
6875 // Set up the width and signedness manually, in case it can't be deduced
6876 // from the operation we're performing.
6877 // FIXME: Don't do this in the cases where we can deduce it.
6878 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6879 E->getType()->isUnsignedIntegerOrEnumerationType());
6880 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6881 RHSVal.getInt(), Value))
6882 return false;
6883 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006884}
6885
Richard Trieuba4d0872012-03-21 23:30:30 +00006886void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006887 Job &job = Queue.back();
6888
6889 switch (job.Kind) {
6890 case Job::AnyExprKind: {
6891 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6892 if (shouldEnqueue(Bop)) {
6893 job.Kind = Job::BinOpKind;
6894 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006895 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006896 }
6897 }
6898
6899 EvaluateExpr(job.E, Result);
6900 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006901 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006902 }
6903
6904 case Job::BinOpKind: {
6905 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006906 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006907 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006908 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006909 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006910 }
6911 if (SuppressRHSDiags)
6912 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006913 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006914 job.Kind = Job::BinOpVisitedLHSKind;
6915 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006916 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006917 }
6918
6919 case Job::BinOpVisitedLHSKind: {
6920 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6921 EvalResult RHS;
6922 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006923 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006924 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006925 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006926 }
6927 }
6928
6929 llvm_unreachable("Invalid Job::Kind!");
6930}
6931
6932bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00006933 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006934 return Error(E);
6935
6936 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6937 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006938
Anders Carlssonacc79812008-11-16 07:17:21 +00006939 QualType LHSTy = E->getLHS()->getType();
6940 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006941
Chandler Carruthb29a7432014-10-11 11:03:30 +00006942 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006943 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00006944 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00006945 if (E->isAssignmentOp()) {
6946 LValue LV;
6947 EvaluateLValue(E->getLHS(), LV, Info);
6948 LHSOK = false;
6949 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00006950 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6951 if (LHSOK) {
6952 LHS.makeComplexFloat();
6953 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6954 }
6955 } else {
6956 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6957 }
Richard Smith253c2a32012-01-27 01:14:48 +00006958 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006959 return false;
6960
Chandler Carruthb29a7432014-10-11 11:03:30 +00006961 if (E->getRHS()->getType()->isRealFloatingType()) {
6962 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6963 return false;
6964 RHS.makeComplexFloat();
6965 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6966 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006967 return false;
6968
6969 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006970 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006971 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006972 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006973 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6974
John McCalle3027922010-08-25 11:45:40 +00006975 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006976 return Success((CR_r == APFloat::cmpEqual &&
6977 CR_i == APFloat::cmpEqual), E);
6978 else {
John McCalle3027922010-08-25 11:45:40 +00006979 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006980 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006981 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006982 CR_r == APFloat::cmpLessThan ||
6983 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006984 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006985 CR_i == APFloat::cmpLessThan ||
6986 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006987 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006988 } else {
John McCalle3027922010-08-25 11:45:40 +00006989 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006990 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6991 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6992 else {
John McCalle3027922010-08-25 11:45:40 +00006993 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006994 "Invalid compex comparison.");
6995 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6996 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6997 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006998 }
6999 }
Mike Stump11289f42009-09-09 15:08:12 +00007000
Anders Carlssonacc79812008-11-16 07:17:21 +00007001 if (LHSTy->isRealFloatingType() &&
7002 RHSTy->isRealFloatingType()) {
7003 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007004
Richard Smith253c2a32012-01-27 01:14:48 +00007005 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7006 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007007 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007008
Richard Smith253c2a32012-01-27 01:14:48 +00007009 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007010 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007011
Anders Carlssonacc79812008-11-16 07:17:21 +00007012 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007013
Anders Carlssonacc79812008-11-16 07:17:21 +00007014 switch (E->getOpcode()) {
7015 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007016 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007017 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007018 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007019 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007020 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007021 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007022 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007023 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007024 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007025 E);
John McCalle3027922010-08-25 11:45:40 +00007026 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007027 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007028 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007029 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007030 || CR == APFloat::cmpLessThan
7031 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007032 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007033 }
Mike Stump11289f42009-09-09 15:08:12 +00007034
Eli Friedmana38da572009-04-28 19:17:36 +00007035 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007036 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007037 LValue LHSValue, RHSValue;
7038
7039 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7040 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007041 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007042
Richard Smith253c2a32012-01-27 01:14:48 +00007043 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007044 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007045
Richard Smith8b3497e2011-10-31 01:37:14 +00007046 // Reject differing bases from the normal codepath; we special-case
7047 // comparisons to null.
7048 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007049 if (E->getOpcode() == BO_Sub) {
7050 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007051 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7052 return false;
7053 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007054 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007055 if (!LHSExpr || !RHSExpr)
7056 return false;
7057 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7058 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7059 if (!LHSAddrExpr || !RHSAddrExpr)
7060 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007061 // Make sure both labels come from the same function.
7062 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7063 RHSAddrExpr->getLabel()->getDeclContext())
7064 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007065 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007066 return true;
7067 }
Richard Smith83c68212011-10-31 05:11:32 +00007068 // Inequalities and subtractions between unrelated pointers have
7069 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007070 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007071 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007072 // A constant address may compare equal to the address of a symbol.
7073 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007074 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007075 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7076 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007077 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007078 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007079 // distinct addresses. In clang, the result of such a comparison is
7080 // unspecified, so it is not a constant expression. However, we do know
7081 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007082 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7083 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007084 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007085 // We can't tell whether weak symbols will end up pointing to the same
7086 // object.
7087 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007088 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007089 // We can't compare the address of the start of one object with the
7090 // past-the-end address of another object, per C++ DR1652.
7091 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7092 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7093 (RHSValue.Base && RHSValue.Offset.isZero() &&
7094 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7095 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007096 // We can't tell whether an object is at the same address as another
7097 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007098 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7099 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007100 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007101 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007102 // (Note that clang defaults to -fmerge-all-constants, which can
7103 // lead to inconsistent results for comparisons involving the address
7104 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007105 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007106 }
Eli Friedman64004332009-03-23 04:38:34 +00007107
Richard Smith1b470412012-02-01 08:10:20 +00007108 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7109 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7110
Richard Smith84f6dcf2012-02-02 01:16:57 +00007111 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7112 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7113
John McCalle3027922010-08-25 11:45:40 +00007114 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007115 // C++11 [expr.add]p6:
7116 // Unless both pointers point to elements of the same array object, or
7117 // one past the last element of the array object, the behavior is
7118 // undefined.
7119 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7120 !AreElementsOfSameArray(getType(LHSValue.Base),
7121 LHSDesignator, RHSDesignator))
7122 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7123
Chris Lattner882bdf22010-04-20 17:13:14 +00007124 QualType Type = E->getLHS()->getType();
7125 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007126
Richard Smithd62306a2011-11-10 06:34:14 +00007127 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007128 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007129 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007130
Richard Smith84c6b3d2013-09-10 21:34:14 +00007131 // As an extension, a type may have zero size (empty struct or union in
7132 // C, array of zero length). Pointer subtraction in such cases has
7133 // undefined behavior, so is not constant.
7134 if (ElementSize.isZero()) {
7135 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7136 << ElementType;
7137 return false;
7138 }
7139
Richard Smith1b470412012-02-01 08:10:20 +00007140 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7141 // and produce incorrect results when it overflows. Such behavior
7142 // appears to be non-conforming, but is common, so perhaps we should
7143 // assume the standard intended for such cases to be undefined behavior
7144 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007145
Richard Smith1b470412012-02-01 08:10:20 +00007146 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7147 // overflow in the final conversion to ptrdiff_t.
7148 APSInt LHS(
7149 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7150 APSInt RHS(
7151 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7152 APSInt ElemSize(
7153 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7154 APSInt TrueResult = (LHS - RHS) / ElemSize;
7155 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7156
7157 if (Result.extend(65) != TrueResult)
7158 HandleOverflow(Info, E, TrueResult, E->getType());
7159 return Success(Result, E);
7160 }
Richard Smithde21b242012-01-31 06:41:30 +00007161
7162 // C++11 [expr.rel]p3:
7163 // Pointers to void (after pointer conversions) can be compared, with a
7164 // result defined as follows: If both pointers represent the same
7165 // address or are both the null pointer value, the result is true if the
7166 // operator is <= or >= and false otherwise; otherwise the result is
7167 // unspecified.
7168 // We interpret this as applying to pointers to *cv* void.
7169 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007170 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007171 CCEDiag(E, diag::note_constexpr_void_comparison);
7172
Richard Smith84f6dcf2012-02-02 01:16:57 +00007173 // C++11 [expr.rel]p2:
7174 // - If two pointers point to non-static data members of the same object,
7175 // or to subobjects or array elements fo such members, recursively, the
7176 // pointer to the later declared member compares greater provided the
7177 // two members have the same access control and provided their class is
7178 // not a union.
7179 // [...]
7180 // - Otherwise pointer comparisons are unspecified.
7181 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7182 E->isRelationalOp()) {
7183 bool WasArrayIndex;
7184 unsigned Mismatch =
7185 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7186 RHSDesignator, WasArrayIndex);
7187 // At the point where the designators diverge, the comparison has a
7188 // specified value if:
7189 // - we are comparing array indices
7190 // - we are comparing fields of a union, or fields with the same access
7191 // Otherwise, the result is unspecified and thus the comparison is not a
7192 // constant expression.
7193 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7194 Mismatch < RHSDesignator.Entries.size()) {
7195 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7196 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7197 if (!LF && !RF)
7198 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7199 else if (!LF)
7200 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7201 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7202 << RF->getParent() << RF;
7203 else if (!RF)
7204 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7205 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7206 << LF->getParent() << LF;
7207 else if (!LF->getParent()->isUnion() &&
7208 LF->getAccess() != RF->getAccess())
7209 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7210 << LF << LF->getAccess() << RF << RF->getAccess()
7211 << LF->getParent();
7212 }
7213 }
7214
Eli Friedman6c31cb42012-04-16 04:30:08 +00007215 // The comparison here must be unsigned, and performed with the same
7216 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007217 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7218 uint64_t CompareLHS = LHSOffset.getQuantity();
7219 uint64_t CompareRHS = RHSOffset.getQuantity();
7220 assert(PtrSize <= 64 && "Unexpected pointer width");
7221 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7222 CompareLHS &= Mask;
7223 CompareRHS &= Mask;
7224
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007225 // If there is a base and this is a relational operator, we can only
7226 // compare pointers within the object in question; otherwise, the result
7227 // depends on where the object is located in memory.
7228 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7229 QualType BaseTy = getType(LHSValue.Base);
7230 if (BaseTy->isIncompleteType())
7231 return Error(E);
7232 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7233 uint64_t OffsetLimit = Size.getQuantity();
7234 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7235 return Error(E);
7236 }
7237
Richard Smith8b3497e2011-10-31 01:37:14 +00007238 switch (E->getOpcode()) {
7239 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007240 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7241 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7242 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7243 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7244 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7245 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007246 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007247 }
7248 }
Richard Smith7bb00672012-02-01 01:42:44 +00007249
7250 if (LHSTy->isMemberPointerType()) {
7251 assert(E->isEqualityOp() && "unexpected member pointer operation");
7252 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7253
7254 MemberPtr LHSValue, RHSValue;
7255
7256 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7257 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7258 return false;
7259
7260 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7261 return false;
7262
7263 // C++11 [expr.eq]p2:
7264 // If both operands are null, they compare equal. Otherwise if only one is
7265 // null, they compare unequal.
7266 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7267 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7268 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7269 }
7270
7271 // Otherwise if either is a pointer to a virtual member function, the
7272 // result is unspecified.
7273 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7274 if (MD->isVirtual())
7275 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7276 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7277 if (MD->isVirtual())
7278 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7279
7280 // Otherwise they compare equal if and only if they would refer to the
7281 // same member of the same most derived object or the same subobject if
7282 // they were dereferenced with a hypothetical object of the associated
7283 // class type.
7284 bool Equal = LHSValue == RHSValue;
7285 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7286 }
7287
Richard Smithab44d9b2012-02-14 22:35:28 +00007288 if (LHSTy->isNullPtrType()) {
7289 assert(E->isComparisonOp() && "unexpected nullptr operation");
7290 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7291 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7292 // are compared, the result is true of the operator is <=, >= or ==, and
7293 // false otherwise.
7294 BinaryOperator::Opcode Opcode = E->getOpcode();
7295 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7296 }
7297
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007298 assert((!LHSTy->isIntegralOrEnumerationType() ||
7299 !RHSTy->isIntegralOrEnumerationType()) &&
7300 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7301 // We can't continue from here for non-integral types.
7302 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007303}
7304
Peter Collingbournee190dee2011-03-11 19:24:49 +00007305/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7306/// a result as the expression's type.
7307bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7308 const UnaryExprOrTypeTraitExpr *E) {
7309 switch(E->getKind()) {
7310 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007311 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007312 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007313 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007314 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007315 }
Eli Friedman64004332009-03-23 04:38:34 +00007316
Peter Collingbournee190dee2011-03-11 19:24:49 +00007317 case UETT_VecStep: {
7318 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007319
Peter Collingbournee190dee2011-03-11 19:24:49 +00007320 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007321 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007322
Peter Collingbournee190dee2011-03-11 19:24:49 +00007323 // The vec_step built-in functions that take a 3-component
7324 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7325 if (n == 3)
7326 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007327
Peter Collingbournee190dee2011-03-11 19:24:49 +00007328 return Success(n, E);
7329 } else
7330 return Success(1, E);
7331 }
7332
7333 case UETT_SizeOf: {
7334 QualType SrcTy = E->getTypeOfArgument();
7335 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7336 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007337 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7338 SrcTy = Ref->getPointeeType();
7339
Richard Smithd62306a2011-11-10 06:34:14 +00007340 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007341 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007342 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007343 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007344 }
Alexey Bataev00396512015-07-02 03:40:19 +00007345 case UETT_OpenMPRequiredSimdAlign:
7346 assert(E->isArgumentType());
7347 return Success(
7348 Info.Ctx.toCharUnitsFromBits(
7349 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7350 .getQuantity(),
7351 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007352 }
7353
7354 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007355}
7356
Peter Collingbournee9200682011-05-13 03:29:01 +00007357bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007358 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007359 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007360 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007361 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007362 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007363 for (unsigned i = 0; i != n; ++i) {
7364 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7365 switch (ON.getKind()) {
7366 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007367 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007368 APSInt IdxResult;
7369 if (!EvaluateInteger(Idx, IdxResult, Info))
7370 return false;
7371 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7372 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007373 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007374 CurrentType = AT->getElementType();
7375 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7376 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007377 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007378 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007379
Douglas Gregor882211c2010-04-28 22:16:22 +00007380 case OffsetOfExpr::OffsetOfNode::Field: {
7381 FieldDecl *MemberDecl = ON.getField();
7382 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007383 if (!RT)
7384 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007385 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007386 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007387 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007388 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007389 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007390 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007391 CurrentType = MemberDecl->getType().getNonReferenceType();
7392 break;
7393 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007394
Douglas Gregor882211c2010-04-28 22:16:22 +00007395 case OffsetOfExpr::OffsetOfNode::Identifier:
7396 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007397
Douglas Gregord1702062010-04-29 00:18:15 +00007398 case OffsetOfExpr::OffsetOfNode::Base: {
7399 CXXBaseSpecifier *BaseSpec = ON.getBase();
7400 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007401 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007402
7403 // Find the layout of the class whose base we are looking into.
7404 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007405 if (!RT)
7406 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007407 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007408 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007409 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7410
7411 // Find the base class itself.
7412 CurrentType = BaseSpec->getType();
7413 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7414 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007415 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007416
7417 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007418 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007419 break;
7420 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007421 }
7422 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007423 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007424}
7425
Chris Lattnere13042c2008-07-11 19:10:17 +00007426bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007427 switch (E->getOpcode()) {
7428 default:
7429 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7430 // See C99 6.6p3.
7431 return Error(E);
7432 case UO_Extension:
7433 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7434 // If so, we could clear the diagnostic ID.
7435 return Visit(E->getSubExpr());
7436 case UO_Plus:
7437 // The result is just the value.
7438 return Visit(E->getSubExpr());
7439 case UO_Minus: {
7440 if (!Visit(E->getSubExpr()))
7441 return false;
7442 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007443 const APSInt &Value = Result.getInt();
7444 if (Value.isSigned() && Value.isMinSignedValue())
7445 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7446 E->getType());
7447 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007448 }
7449 case UO_Not: {
7450 if (!Visit(E->getSubExpr()))
7451 return false;
7452 if (!Result.isInt()) return Error(E);
7453 return Success(~Result.getInt(), E);
7454 }
7455 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007456 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007457 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007458 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007459 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007460 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007461 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007462}
Mike Stump11289f42009-09-09 15:08:12 +00007463
Chris Lattner477c4be2008-07-12 01:15:53 +00007464/// HandleCast - This is used to evaluate implicit or explicit casts where the
7465/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007466bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7467 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007468 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007469 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007470
Eli Friedmanc757de22011-03-25 00:43:55 +00007471 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007472 case CK_BaseToDerived:
7473 case CK_DerivedToBase:
7474 case CK_UncheckedDerivedToBase:
7475 case CK_Dynamic:
7476 case CK_ToUnion:
7477 case CK_ArrayToPointerDecay:
7478 case CK_FunctionToPointerDecay:
7479 case CK_NullToPointer:
7480 case CK_NullToMemberPointer:
7481 case CK_BaseToDerivedMemberPointer:
7482 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007483 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007484 case CK_ConstructorConversion:
7485 case CK_IntegralToPointer:
7486 case CK_ToVoid:
7487 case CK_VectorSplat:
7488 case CK_IntegralToFloating:
7489 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007490 case CK_CPointerToObjCPointerCast:
7491 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007492 case CK_AnyPointerToBlockPointerCast:
7493 case CK_ObjCObjectLValueCast:
7494 case CK_FloatingRealToComplex:
7495 case CK_FloatingComplexToReal:
7496 case CK_FloatingComplexCast:
7497 case CK_FloatingComplexToIntegralComplex:
7498 case CK_IntegralRealToComplex:
7499 case CK_IntegralComplexCast:
7500 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007501 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007502 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007503 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007504 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007505 llvm_unreachable("invalid cast kind for integral value");
7506
Eli Friedman9faf2f92011-03-25 19:07:11 +00007507 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007508 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007509 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007510 case CK_ARCProduceObject:
7511 case CK_ARCConsumeObject:
7512 case CK_ARCReclaimReturnedObject:
7513 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007514 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007515 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007516
Richard Smith4ef685b2012-01-17 21:17:26 +00007517 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007518 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007519 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007520 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007521 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007522
7523 case CK_MemberPointerToBoolean:
7524 case CK_PointerToBoolean:
7525 case CK_IntegralToBoolean:
7526 case CK_FloatingToBoolean:
7527 case CK_FloatingComplexToBoolean:
7528 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007529 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007530 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007531 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007532 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007533 }
7534
Eli Friedmanc757de22011-03-25 00:43:55 +00007535 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007536 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007537 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007538
Eli Friedman742421e2009-02-20 01:15:07 +00007539 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007540 // Allow casts of address-of-label differences if they are no-ops
7541 // or narrowing. (The narrowing case isn't actually guaranteed to
7542 // be constant-evaluatable except in some narrow cases which are hard
7543 // to detect here. We let it through on the assumption the user knows
7544 // what they are doing.)
7545 if (Result.isAddrLabelDiff())
7546 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007547 // Only allow casts of lvalues if they are lossless.
7548 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7549 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007550
Richard Smith911e1422012-01-30 22:27:01 +00007551 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7552 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007553 }
Mike Stump11289f42009-09-09 15:08:12 +00007554
Eli Friedmanc757de22011-03-25 00:43:55 +00007555 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007556 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7557
John McCall45d55e42010-05-07 21:00:08 +00007558 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007559 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007560 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007561
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007562 if (LV.getLValueBase()) {
7563 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007564 // FIXME: Allow a larger integer size than the pointer size, and allow
7565 // narrowing back down to pointer width in subsequent integral casts.
7566 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007567 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007568 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007569
Richard Smithcf74da72011-11-16 07:18:12 +00007570 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007571 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007572 return true;
7573 }
7574
Ken Dyck02990832010-01-15 12:37:54 +00007575 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7576 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007577 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007578 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007579
Eli Friedmanc757de22011-03-25 00:43:55 +00007580 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007581 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007582 if (!EvaluateComplex(SubExpr, C, Info))
7583 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007584 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007585 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007586
Eli Friedmanc757de22011-03-25 00:43:55 +00007587 case CK_FloatingToIntegral: {
7588 APFloat F(0.0);
7589 if (!EvaluateFloat(SubExpr, F, Info))
7590 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007591
Richard Smith357362d2011-12-13 06:39:58 +00007592 APSInt Value;
7593 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7594 return false;
7595 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007596 }
7597 }
Mike Stump11289f42009-09-09 15:08:12 +00007598
Eli Friedmanc757de22011-03-25 00:43:55 +00007599 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007600}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007601
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007602bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7603 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007604 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007605 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7606 return false;
7607 if (!LV.isComplexInt())
7608 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007609 return Success(LV.getComplexIntReal(), E);
7610 }
7611
7612 return Visit(E->getSubExpr());
7613}
7614
Eli Friedman4e7a2412009-02-27 04:45:43 +00007615bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007616 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007617 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007618 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7619 return false;
7620 if (!LV.isComplexInt())
7621 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007622 return Success(LV.getComplexIntImag(), E);
7623 }
7624
Richard Smith4a678122011-10-24 18:44:57 +00007625 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007626 return Success(0, E);
7627}
7628
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007629bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7630 return Success(E->getPackLength(), E);
7631}
7632
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007633bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7634 return Success(E->getValue(), E);
7635}
7636
Chris Lattner05706e882008-07-11 18:11:29 +00007637//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007638// Float Evaluation
7639//===----------------------------------------------------------------------===//
7640
7641namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007642class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007643 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007644 APFloat &Result;
7645public:
7646 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007647 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007648
Richard Smith2e312c82012-03-03 22:46:17 +00007649 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007650 Result = V.getFloat();
7651 return true;
7652 }
Eli Friedman24c01542008-08-22 00:06:13 +00007653
Richard Smithfddd3842011-12-30 21:15:51 +00007654 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007655 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7656 return true;
7657 }
7658
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007659 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007660
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007661 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007662 bool VisitBinaryOperator(const BinaryOperator *E);
7663 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007664 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007665
John McCallb1fb0d32010-05-07 22:08:54 +00007666 bool VisitUnaryReal(const UnaryOperator *E);
7667 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007668
Richard Smithfddd3842011-12-30 21:15:51 +00007669 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007670};
7671} // end anonymous namespace
7672
7673static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007674 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007675 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007676}
7677
Jay Foad39c79802011-01-12 09:06:06 +00007678static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007679 QualType ResultTy,
7680 const Expr *Arg,
7681 bool SNaN,
7682 llvm::APFloat &Result) {
7683 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7684 if (!S) return false;
7685
7686 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7687
7688 llvm::APInt fill;
7689
7690 // Treat empty strings as if they were zero.
7691 if (S->getString().empty())
7692 fill = llvm::APInt(32, 0);
7693 else if (S->getString().getAsInteger(0, fill))
7694 return false;
7695
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007696 if (Context.getTargetInfo().isNan2008()) {
7697 if (SNaN)
7698 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7699 else
7700 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7701 } else {
7702 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7703 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7704 // a different encoding to what became a standard in 2008, and for pre-
7705 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7706 // sNaN. This is now known as "legacy NaN" encoding.
7707 if (SNaN)
7708 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7709 else
7710 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7711 }
7712
John McCall16291492010-02-28 13:00:19 +00007713 return true;
7714}
7715
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007716bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007717 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007718 default:
7719 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7720
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007721 case Builtin::BI__builtin_huge_val:
7722 case Builtin::BI__builtin_huge_valf:
7723 case Builtin::BI__builtin_huge_vall:
7724 case Builtin::BI__builtin_inf:
7725 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007726 case Builtin::BI__builtin_infl: {
7727 const llvm::fltSemantics &Sem =
7728 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007729 Result = llvm::APFloat::getInf(Sem);
7730 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007731 }
Mike Stump11289f42009-09-09 15:08:12 +00007732
John McCall16291492010-02-28 13:00:19 +00007733 case Builtin::BI__builtin_nans:
7734 case Builtin::BI__builtin_nansf:
7735 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007736 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7737 true, Result))
7738 return Error(E);
7739 return true;
John McCall16291492010-02-28 13:00:19 +00007740
Chris Lattner0b7282e2008-10-06 06:31:58 +00007741 case Builtin::BI__builtin_nan:
7742 case Builtin::BI__builtin_nanf:
7743 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007744 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007745 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007746 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7747 false, Result))
7748 return Error(E);
7749 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007750
7751 case Builtin::BI__builtin_fabs:
7752 case Builtin::BI__builtin_fabsf:
7753 case Builtin::BI__builtin_fabsl:
7754 if (!EvaluateFloat(E->getArg(0), Result, Info))
7755 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007756
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007757 if (Result.isNegative())
7758 Result.changeSign();
7759 return true;
7760
Richard Smith8889a3d2013-06-13 06:26:32 +00007761 // FIXME: Builtin::BI__builtin_powi
7762 // FIXME: Builtin::BI__builtin_powif
7763 // FIXME: Builtin::BI__builtin_powil
7764
Mike Stump11289f42009-09-09 15:08:12 +00007765 case Builtin::BI__builtin_copysign:
7766 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007767 case Builtin::BI__builtin_copysignl: {
7768 APFloat RHS(0.);
7769 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7770 !EvaluateFloat(E->getArg(1), RHS, Info))
7771 return false;
7772 Result.copySign(RHS);
7773 return true;
7774 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007775 }
7776}
7777
John McCallb1fb0d32010-05-07 22:08:54 +00007778bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007779 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7780 ComplexValue CV;
7781 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7782 return false;
7783 Result = CV.FloatReal;
7784 return true;
7785 }
7786
7787 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007788}
7789
7790bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007791 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7792 ComplexValue CV;
7793 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7794 return false;
7795 Result = CV.FloatImag;
7796 return true;
7797 }
7798
Richard Smith4a678122011-10-24 18:44:57 +00007799 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007800 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7801 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007802 return true;
7803}
7804
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007805bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007806 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007807 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007808 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007809 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007810 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007811 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7812 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007813 Result.changeSign();
7814 return true;
7815 }
7816}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007817
Eli Friedman24c01542008-08-22 00:06:13 +00007818bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007819 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7820 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007821
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007822 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007823 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7824 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007825 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007826 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7827 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007828}
7829
7830bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7831 Result = E->getValue();
7832 return true;
7833}
7834
Peter Collingbournee9200682011-05-13 03:29:01 +00007835bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7836 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007837
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007838 switch (E->getCastKind()) {
7839 default:
Richard Smith11562c52011-10-28 17:51:58 +00007840 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007841
7842 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007843 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007844 return EvaluateInteger(SubExpr, IntResult, Info) &&
7845 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7846 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007847 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007848
7849 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007850 if (!Visit(SubExpr))
7851 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007852 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7853 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007854 }
John McCalld7646252010-11-14 08:17:51 +00007855
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007856 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007857 ComplexValue V;
7858 if (!EvaluateComplex(SubExpr, V, Info))
7859 return false;
7860 Result = V.getComplexFloatReal();
7861 return true;
7862 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007863 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007864}
7865
Eli Friedman24c01542008-08-22 00:06:13 +00007866//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007867// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007868//===----------------------------------------------------------------------===//
7869
7870namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007871class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007872 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007873 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007874
Anders Carlsson537969c2008-11-16 20:27:53 +00007875public:
John McCall93d91dc2010-05-07 17:22:02 +00007876 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007877 : ExprEvaluatorBaseTy(info), Result(Result) {}
7878
Richard Smith2e312c82012-03-03 22:46:17 +00007879 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007880 Result.setFrom(V);
7881 return true;
7882 }
Mike Stump11289f42009-09-09 15:08:12 +00007883
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007884 bool ZeroInitialization(const Expr *E);
7885
Anders Carlsson537969c2008-11-16 20:27:53 +00007886 //===--------------------------------------------------------------------===//
7887 // Visitor Methods
7888 //===--------------------------------------------------------------------===//
7889
Peter Collingbournee9200682011-05-13 03:29:01 +00007890 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007891 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007892 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007893 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007894 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007895};
7896} // end anonymous namespace
7897
John McCall93d91dc2010-05-07 17:22:02 +00007898static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7899 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007900 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007901 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007902}
7903
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007904bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007905 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007906 if (ElemTy->isRealFloatingType()) {
7907 Result.makeComplexFloat();
7908 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7909 Result.FloatReal = Zero;
7910 Result.FloatImag = Zero;
7911 } else {
7912 Result.makeComplexInt();
7913 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7914 Result.IntReal = Zero;
7915 Result.IntImag = Zero;
7916 }
7917 return true;
7918}
7919
Peter Collingbournee9200682011-05-13 03:29:01 +00007920bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7921 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007922
7923 if (SubExpr->getType()->isRealFloatingType()) {
7924 Result.makeComplexFloat();
7925 APFloat &Imag = Result.FloatImag;
7926 if (!EvaluateFloat(SubExpr, Imag, Info))
7927 return false;
7928
7929 Result.FloatReal = APFloat(Imag.getSemantics());
7930 return true;
7931 } else {
7932 assert(SubExpr->getType()->isIntegerType() &&
7933 "Unexpected imaginary literal.");
7934
7935 Result.makeComplexInt();
7936 APSInt &Imag = Result.IntImag;
7937 if (!EvaluateInteger(SubExpr, Imag, Info))
7938 return false;
7939
7940 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7941 return true;
7942 }
7943}
7944
Peter Collingbournee9200682011-05-13 03:29:01 +00007945bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007946
John McCallfcef3cf2010-12-14 17:51:41 +00007947 switch (E->getCastKind()) {
7948 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007949 case CK_BaseToDerived:
7950 case CK_DerivedToBase:
7951 case CK_UncheckedDerivedToBase:
7952 case CK_Dynamic:
7953 case CK_ToUnion:
7954 case CK_ArrayToPointerDecay:
7955 case CK_FunctionToPointerDecay:
7956 case CK_NullToPointer:
7957 case CK_NullToMemberPointer:
7958 case CK_BaseToDerivedMemberPointer:
7959 case CK_DerivedToBaseMemberPointer:
7960 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007961 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007962 case CK_ConstructorConversion:
7963 case CK_IntegralToPointer:
7964 case CK_PointerToIntegral:
7965 case CK_PointerToBoolean:
7966 case CK_ToVoid:
7967 case CK_VectorSplat:
7968 case CK_IntegralCast:
7969 case CK_IntegralToBoolean:
7970 case CK_IntegralToFloating:
7971 case CK_FloatingToIntegral:
7972 case CK_FloatingToBoolean:
7973 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007974 case CK_CPointerToObjCPointerCast:
7975 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007976 case CK_AnyPointerToBlockPointerCast:
7977 case CK_ObjCObjectLValueCast:
7978 case CK_FloatingComplexToReal:
7979 case CK_FloatingComplexToBoolean:
7980 case CK_IntegralComplexToReal:
7981 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007982 case CK_ARCProduceObject:
7983 case CK_ARCConsumeObject:
7984 case CK_ARCReclaimReturnedObject:
7985 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007986 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007987 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007988 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007989 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007990 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007991 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007992
John McCallfcef3cf2010-12-14 17:51:41 +00007993 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007994 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007995 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007996 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007997
7998 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007999 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008000 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008001 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008002
8003 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008004 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008005 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008006 return false;
8007
John McCallfcef3cf2010-12-14 17:51:41 +00008008 Result.makeComplexFloat();
8009 Result.FloatImag = APFloat(Real.getSemantics());
8010 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008011 }
8012
John McCallfcef3cf2010-12-14 17:51:41 +00008013 case CK_FloatingComplexCast: {
8014 if (!Visit(E->getSubExpr()))
8015 return false;
8016
8017 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8018 QualType From
8019 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8020
Richard Smith357362d2011-12-13 06:39:58 +00008021 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8022 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008023 }
8024
8025 case CK_FloatingComplexToIntegralComplex: {
8026 if (!Visit(E->getSubExpr()))
8027 return false;
8028
8029 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8030 QualType From
8031 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8032 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008033 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8034 To, Result.IntReal) &&
8035 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8036 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008037 }
8038
8039 case CK_IntegralRealToComplex: {
8040 APSInt &Real = Result.IntReal;
8041 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8042 return false;
8043
8044 Result.makeComplexInt();
8045 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8046 return true;
8047 }
8048
8049 case CK_IntegralComplexCast: {
8050 if (!Visit(E->getSubExpr()))
8051 return false;
8052
8053 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8054 QualType From
8055 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8056
Richard Smith911e1422012-01-30 22:27:01 +00008057 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8058 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008059 return true;
8060 }
8061
8062 case CK_IntegralComplexToFloatingComplex: {
8063 if (!Visit(E->getSubExpr()))
8064 return false;
8065
Ted Kremenek28831752012-08-23 20:46:57 +00008066 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008067 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008068 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008069 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008070 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8071 To, Result.FloatReal) &&
8072 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8073 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008074 }
8075 }
8076
8077 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008078}
8079
John McCall93d91dc2010-05-07 17:22:02 +00008080bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008081 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008082 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8083
Chandler Carrutha216cad2014-10-11 00:57:18 +00008084 // Track whether the LHS or RHS is real at the type system level. When this is
8085 // the case we can simplify our evaluation strategy.
8086 bool LHSReal = false, RHSReal = false;
8087
8088 bool LHSOK;
8089 if (E->getLHS()->getType()->isRealFloatingType()) {
8090 LHSReal = true;
8091 APFloat &Real = Result.FloatReal;
8092 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8093 if (LHSOK) {
8094 Result.makeComplexFloat();
8095 Result.FloatImag = APFloat(Real.getSemantics());
8096 }
8097 } else {
8098 LHSOK = Visit(E->getLHS());
8099 }
Richard Smith253c2a32012-01-27 01:14:48 +00008100 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008101 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008102
John McCall93d91dc2010-05-07 17:22:02 +00008103 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008104 if (E->getRHS()->getType()->isRealFloatingType()) {
8105 RHSReal = true;
8106 APFloat &Real = RHS.FloatReal;
8107 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8108 return false;
8109 RHS.makeComplexFloat();
8110 RHS.FloatImag = APFloat(Real.getSemantics());
8111 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008112 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008113
Chandler Carrutha216cad2014-10-11 00:57:18 +00008114 assert(!(LHSReal && RHSReal) &&
8115 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008116 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008117 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008118 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008119 if (Result.isComplexFloat()) {
8120 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8121 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008122 if (LHSReal)
8123 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8124 else if (!RHSReal)
8125 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8126 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008127 } else {
8128 Result.getComplexIntReal() += RHS.getComplexIntReal();
8129 Result.getComplexIntImag() += RHS.getComplexIntImag();
8130 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008131 break;
John McCalle3027922010-08-25 11:45:40 +00008132 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008133 if (Result.isComplexFloat()) {
8134 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8135 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008136 if (LHSReal) {
8137 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8138 Result.getComplexFloatImag().changeSign();
8139 } else if (!RHSReal) {
8140 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8141 APFloat::rmNearestTiesToEven);
8142 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008143 } else {
8144 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8145 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8146 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008147 break;
John McCalle3027922010-08-25 11:45:40 +00008148 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008149 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008150 // This is an implementation of complex multiplication according to the
8151 // constraints laid out in C11 Annex G. The implemantion uses the
8152 // following naming scheme:
8153 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008154 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008155 APFloat &A = LHS.getComplexFloatReal();
8156 APFloat &B = LHS.getComplexFloatImag();
8157 APFloat &C = RHS.getComplexFloatReal();
8158 APFloat &D = RHS.getComplexFloatImag();
8159 APFloat &ResR = Result.getComplexFloatReal();
8160 APFloat &ResI = Result.getComplexFloatImag();
8161 if (LHSReal) {
8162 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8163 ResR = A * C;
8164 ResI = A * D;
8165 } else if (RHSReal) {
8166 ResR = C * A;
8167 ResI = C * B;
8168 } else {
8169 // In the fully general case, we need to handle NaNs and infinities
8170 // robustly.
8171 APFloat AC = A * C;
8172 APFloat BD = B * D;
8173 APFloat AD = A * D;
8174 APFloat BC = B * C;
8175 ResR = AC - BD;
8176 ResI = AD + BC;
8177 if (ResR.isNaN() && ResI.isNaN()) {
8178 bool Recalc = false;
8179 if (A.isInfinity() || B.isInfinity()) {
8180 A = APFloat::copySign(
8181 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8182 B = APFloat::copySign(
8183 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8184 if (C.isNaN())
8185 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8186 if (D.isNaN())
8187 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8188 Recalc = true;
8189 }
8190 if (C.isInfinity() || D.isInfinity()) {
8191 C = APFloat::copySign(
8192 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8193 D = APFloat::copySign(
8194 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8195 if (A.isNaN())
8196 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8197 if (B.isNaN())
8198 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8199 Recalc = true;
8200 }
8201 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8202 AD.isInfinity() || BC.isInfinity())) {
8203 if (A.isNaN())
8204 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8205 if (B.isNaN())
8206 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8207 if (C.isNaN())
8208 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8209 if (D.isNaN())
8210 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8211 Recalc = true;
8212 }
8213 if (Recalc) {
8214 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8215 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8216 }
8217 }
8218 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008219 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008220 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008221 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008222 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8223 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008224 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008225 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8226 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8227 }
8228 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008229 case BO_Div:
8230 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008231 // This is an implementation of complex division according to the
8232 // constraints laid out in C11 Annex G. The implemantion uses the
8233 // following naming scheme:
8234 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008235 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008236 APFloat &A = LHS.getComplexFloatReal();
8237 APFloat &B = LHS.getComplexFloatImag();
8238 APFloat &C = RHS.getComplexFloatReal();
8239 APFloat &D = RHS.getComplexFloatImag();
8240 APFloat &ResR = Result.getComplexFloatReal();
8241 APFloat &ResI = Result.getComplexFloatImag();
8242 if (RHSReal) {
8243 ResR = A / C;
8244 ResI = B / C;
8245 } else {
8246 if (LHSReal) {
8247 // No real optimizations we can do here, stub out with zero.
8248 B = APFloat::getZero(A.getSemantics());
8249 }
8250 int DenomLogB = 0;
8251 APFloat MaxCD = maxnum(abs(C), abs(D));
8252 if (MaxCD.isFinite()) {
8253 DenomLogB = ilogb(MaxCD);
8254 C = scalbn(C, -DenomLogB);
8255 D = scalbn(D, -DenomLogB);
8256 }
8257 APFloat Denom = C * C + D * D;
8258 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8259 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8260 if (ResR.isNaN() && ResI.isNaN()) {
8261 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8262 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8263 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8264 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8265 D.isFinite()) {
8266 A = APFloat::copySign(
8267 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8268 B = APFloat::copySign(
8269 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8270 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8271 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8272 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8273 C = APFloat::copySign(
8274 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8275 D = APFloat::copySign(
8276 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8277 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8278 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8279 }
8280 }
8281 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008282 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008283 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8284 return Error(E, diag::note_expr_divide_by_zero);
8285
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008286 ComplexValue LHS = Result;
8287 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8288 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8289 Result.getComplexIntReal() =
8290 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8291 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8292 Result.getComplexIntImag() =
8293 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8294 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8295 }
8296 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008297 }
8298
John McCall93d91dc2010-05-07 17:22:02 +00008299 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008300}
8301
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008302bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8303 // Get the operand value into 'Result'.
8304 if (!Visit(E->getSubExpr()))
8305 return false;
8306
8307 switch (E->getOpcode()) {
8308 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008309 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008310 case UO_Extension:
8311 return true;
8312 case UO_Plus:
8313 // The result is always just the subexpr.
8314 return true;
8315 case UO_Minus:
8316 if (Result.isComplexFloat()) {
8317 Result.getComplexFloatReal().changeSign();
8318 Result.getComplexFloatImag().changeSign();
8319 }
8320 else {
8321 Result.getComplexIntReal() = -Result.getComplexIntReal();
8322 Result.getComplexIntImag() = -Result.getComplexIntImag();
8323 }
8324 return true;
8325 case UO_Not:
8326 if (Result.isComplexFloat())
8327 Result.getComplexFloatImag().changeSign();
8328 else
8329 Result.getComplexIntImag() = -Result.getComplexIntImag();
8330 return true;
8331 }
8332}
8333
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008334bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8335 if (E->getNumInits() == 2) {
8336 if (E->getType()->isComplexType()) {
8337 Result.makeComplexFloat();
8338 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8339 return false;
8340 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8341 return false;
8342 } else {
8343 Result.makeComplexInt();
8344 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8345 return false;
8346 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8347 return false;
8348 }
8349 return true;
8350 }
8351 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8352}
8353
Anders Carlsson537969c2008-11-16 20:27:53 +00008354//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008355// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8356// implicit conversion.
8357//===----------------------------------------------------------------------===//
8358
8359namespace {
8360class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008361 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008362 APValue &Result;
8363public:
8364 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8365 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8366
8367 bool Success(const APValue &V, const Expr *E) {
8368 Result = V;
8369 return true;
8370 }
8371
8372 bool ZeroInitialization(const Expr *E) {
8373 ImplicitValueInitExpr VIE(
8374 E->getType()->castAs<AtomicType>()->getValueType());
8375 return Evaluate(Result, Info, &VIE);
8376 }
8377
8378 bool VisitCastExpr(const CastExpr *E) {
8379 switch (E->getCastKind()) {
8380 default:
8381 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8382 case CK_NonAtomicToAtomic:
8383 return Evaluate(Result, Info, E->getSubExpr());
8384 }
8385 }
8386};
8387} // end anonymous namespace
8388
8389static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8390 assert(E->isRValue() && E->getType()->isAtomicType());
8391 return AtomicExprEvaluator(Info, Result).Visit(E);
8392}
8393
8394//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008395// Void expression evaluation, primarily for a cast to void on the LHS of a
8396// comma operator
8397//===----------------------------------------------------------------------===//
8398
8399namespace {
8400class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008401 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008402public:
8403 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8404
Richard Smith2e312c82012-03-03 22:46:17 +00008405 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008406
8407 bool VisitCastExpr(const CastExpr *E) {
8408 switch (E->getCastKind()) {
8409 default:
8410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8411 case CK_ToVoid:
8412 VisitIgnoredValue(E->getSubExpr());
8413 return true;
8414 }
8415 }
Hal Finkela8443c32014-07-17 14:49:58 +00008416
8417 bool VisitCallExpr(const CallExpr *E) {
8418 switch (E->getBuiltinCallee()) {
8419 default:
8420 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8421 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008422 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008423 // The argument is not evaluated!
8424 return true;
8425 }
8426 }
Richard Smith42d3af92011-12-07 00:43:50 +00008427};
8428} // end anonymous namespace
8429
8430static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8431 assert(E->isRValue() && E->getType()->isVoidType());
8432 return VoidExprEvaluator(Info).Visit(E);
8433}
8434
8435//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008436// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008437//===----------------------------------------------------------------------===//
8438
Richard Smith2e312c82012-03-03 22:46:17 +00008439static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008440 // In C, function designators are not lvalues, but we evaluate them as if they
8441 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008442 QualType T = E->getType();
8443 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008444 LValue LV;
8445 if (!EvaluateLValue(E, LV, Info))
8446 return false;
8447 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008448 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008449 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008450 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008451 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008452 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008453 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008454 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008455 LValue LV;
8456 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008457 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008458 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008459 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008460 llvm::APFloat F(0.0);
8461 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008462 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008463 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008464 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008465 ComplexValue C;
8466 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008467 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008468 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008469 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008470 MemberPtr P;
8471 if (!EvaluateMemberPointer(E, P, Info))
8472 return false;
8473 P.moveInto(Result);
8474 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008475 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008476 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008477 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008478 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8479 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008480 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008481 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008482 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008483 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008484 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008485 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8486 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008487 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008488 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008489 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008490 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008491 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008492 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008493 if (!EvaluateVoid(E, Info))
8494 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008495 } else if (T->isAtomicType()) {
8496 if (!EvaluateAtomic(E, Result, Info))
8497 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008498 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008499 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008500 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008501 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008502 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008503 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008504 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008505
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008506 return true;
8507}
8508
Richard Smithb228a862012-02-15 02:18:13 +00008509/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8510/// cases, the in-place evaluation is essential, since later initializers for
8511/// an object can indirectly refer to subobjects which were initialized earlier.
8512static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008513 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008514 assert(!E->isValueDependent());
8515
Richard Smith7525ff62013-05-09 07:14:00 +00008516 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008517 return false;
8518
8519 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008520 // Evaluate arrays and record types in-place, so that later initializers can
8521 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008522 if (E->getType()->isArrayType())
8523 return EvaluateArray(E, This, Result, Info);
8524 else if (E->getType()->isRecordType())
8525 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008526 }
8527
8528 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008529 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008530}
8531
Richard Smithf57d8cb2011-12-09 22:58:01 +00008532/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8533/// lvalue-to-rvalue cast if it is an lvalue.
8534static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008535 if (E->getType().isNull())
8536 return false;
8537
Richard Smithfddd3842011-12-30 21:15:51 +00008538 if (!CheckLiteralType(Info, E))
8539 return false;
8540
Richard Smith2e312c82012-03-03 22:46:17 +00008541 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008542 return false;
8543
8544 if (E->isGLValue()) {
8545 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008546 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008547 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008548 return false;
8549 }
8550
Richard Smith2e312c82012-03-03 22:46:17 +00008551 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008552 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008553}
Richard Smith11562c52011-10-28 17:51:58 +00008554
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008555static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8556 const ASTContext &Ctx, bool &IsConst) {
8557 // Fast-path evaluations of integer literals, since we sometimes see files
8558 // containing vast quantities of these.
8559 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8560 Result.Val = APValue(APSInt(L->getValue(),
8561 L->getType()->isUnsignedIntegerType()));
8562 IsConst = true;
8563 return true;
8564 }
James Dennett0492ef02014-03-14 17:44:10 +00008565
8566 // This case should be rare, but we need to check it before we check on
8567 // the type below.
8568 if (Exp->getType().isNull()) {
8569 IsConst = false;
8570 return true;
8571 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008572
8573 // FIXME: Evaluating values of large array and record types can cause
8574 // performance problems. Only do so in C++11 for now.
8575 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8576 Exp->getType()->isRecordType()) &&
8577 !Ctx.getLangOpts().CPlusPlus11) {
8578 IsConst = false;
8579 return true;
8580 }
8581 return false;
8582}
8583
8584
Richard Smith7b553f12011-10-29 00:50:52 +00008585/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008586/// any crazy technique (that has nothing to do with language standards) that
8587/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008588/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8589/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008590bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008591 bool IsConst;
8592 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8593 return IsConst;
8594
Richard Smith6d4c6582013-11-05 22:18:15 +00008595 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008596 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008597}
8598
Jay Foad39c79802011-01-12 09:06:06 +00008599bool Expr::EvaluateAsBooleanCondition(bool &Result,
8600 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008601 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008602 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008603 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008604}
8605
Richard Smith5fab0c92011-12-28 19:48:30 +00008606bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8607 SideEffectsKind AllowSideEffects) const {
8608 if (!getType()->isIntegralOrEnumerationType())
8609 return false;
8610
Richard Smith11562c52011-10-28 17:51:58 +00008611 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008612 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8613 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008614 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008615
Richard Smith11562c52011-10-28 17:51:58 +00008616 Result = ExprResult.Val.getInt();
8617 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008618}
8619
Jay Foad39c79802011-01-12 09:06:06 +00008620bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008621 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008622
John McCall45d55e42010-05-07 21:00:08 +00008623 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008624 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8625 !CheckLValueConstantExpression(Info, getExprLoc(),
8626 Ctx.getLValueReferenceType(getType()), LV))
8627 return false;
8628
Richard Smith2e312c82012-03-03 22:46:17 +00008629 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008630 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008631}
8632
Richard Smithd0b4dd62011-12-19 06:19:21 +00008633bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8634 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008635 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008636 // FIXME: Evaluating initializers for large array and record types can cause
8637 // performance problems. Only do so in C++11 for now.
8638 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008639 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008640 return false;
8641
Richard Smithd0b4dd62011-12-19 06:19:21 +00008642 Expr::EvalStatus EStatus;
8643 EStatus.Diag = &Notes;
8644
Richard Smith6d4c6582013-11-05 22:18:15 +00008645 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008646 InitInfo.setEvaluatingDecl(VD, Value);
8647
8648 LValue LVal;
8649 LVal.set(VD);
8650
Richard Smithfddd3842011-12-30 21:15:51 +00008651 // C++11 [basic.start.init]p2:
8652 // Variables with static storage duration or thread storage duration shall be
8653 // zero-initialized before any other initialization takes place.
8654 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008655 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008656 !VD->getType()->isReferenceType()) {
8657 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008658 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008659 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008660 return false;
8661 }
8662
Richard Smith7525ff62013-05-09 07:14:00 +00008663 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8664 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008665 EStatus.HasSideEffects)
8666 return false;
8667
8668 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8669 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008670}
8671
Richard Smith7b553f12011-10-29 00:50:52 +00008672/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8673/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008674bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008675 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008676 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008677}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008678
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008679APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008680 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008681 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008682 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008683 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008684 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008685 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008686 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008687
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008688 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008689}
John McCall864e3962010-05-07 05:32:02 +00008690
Richard Smithe9ff7702013-11-05 22:23:30 +00008691void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008692 bool IsConst;
8693 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008694 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008695 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008696 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8697 }
8698}
8699
Richard Smithe6c01442013-06-05 00:46:14 +00008700bool Expr::EvalResult::isGlobalLValue() const {
8701 assert(Val.isLValue());
8702 return IsGlobalLValue(Val.getLValueBase());
8703}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008704
8705
John McCall864e3962010-05-07 05:32:02 +00008706/// isIntegerConstantExpr - this recursive routine will test if an expression is
8707/// an integer constant expression.
8708
8709/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8710/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008711
8712// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008713// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8714// and a (possibly null) SourceLocation indicating the location of the problem.
8715//
John McCall864e3962010-05-07 05:32:02 +00008716// Note that to reduce code duplication, this helper does no evaluation
8717// itself; the caller checks whether the expression is evaluatable, and
8718// in the rare cases where CheckICE actually cares about the evaluated
8719// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008720
Dan Gohman28ade552010-07-26 21:25:24 +00008721namespace {
8722
Richard Smith9e575da2012-12-28 13:25:52 +00008723enum ICEKind {
8724 /// This expression is an ICE.
8725 IK_ICE,
8726 /// This expression is not an ICE, but if it isn't evaluated, it's
8727 /// a legal subexpression for an ICE. This return value is used to handle
8728 /// the comma operator in C99 mode, and non-constant subexpressions.
8729 IK_ICEIfUnevaluated,
8730 /// This expression is not an ICE, and is not a legal subexpression for one.
8731 IK_NotICE
8732};
8733
John McCall864e3962010-05-07 05:32:02 +00008734struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008735 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008736 SourceLocation Loc;
8737
Richard Smith9e575da2012-12-28 13:25:52 +00008738 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008739};
8740
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008741}
Dan Gohman28ade552010-07-26 21:25:24 +00008742
Richard Smith9e575da2012-12-28 13:25:52 +00008743static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8744
8745static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008746
Craig Toppera31a8822013-08-22 07:09:37 +00008747static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008748 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008749 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008750 !EVResult.Val.isInt())
8751 return ICEDiag(IK_NotICE, E->getLocStart());
8752
John McCall864e3962010-05-07 05:32:02 +00008753 return NoDiag();
8754}
8755
Craig Toppera31a8822013-08-22 07:09:37 +00008756static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008757 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008758 if (!E->getType()->isIntegralOrEnumerationType())
8759 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008760
8761 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008762#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008763#define STMT(Node, Base) case Expr::Node##Class:
8764#define EXPR(Node, Base)
8765#include "clang/AST/StmtNodes.inc"
8766 case Expr::PredefinedExprClass:
8767 case Expr::FloatingLiteralClass:
8768 case Expr::ImaginaryLiteralClass:
8769 case Expr::StringLiteralClass:
8770 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008771 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00008772 case Expr::MemberExprClass:
8773 case Expr::CompoundAssignOperatorClass:
8774 case Expr::CompoundLiteralExprClass:
8775 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008776 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00008777 case Expr::NoInitExprClass:
8778 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00008779 case Expr::ImplicitValueInitExprClass:
8780 case Expr::ParenListExprClass:
8781 case Expr::VAArgExprClass:
8782 case Expr::AddrLabelExprClass:
8783 case Expr::StmtExprClass:
8784 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008785 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008786 case Expr::CXXDynamicCastExprClass:
8787 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008788 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008789 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008790 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008791 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008792 case Expr::CXXThisExprClass:
8793 case Expr::CXXThrowExprClass:
8794 case Expr::CXXNewExprClass:
8795 case Expr::CXXDeleteExprClass:
8796 case Expr::CXXPseudoDestructorExprClass:
8797 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00008798 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00008799 case Expr::DependentScopeDeclRefExprClass:
8800 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008801 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008802 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008803 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008804 case Expr::CXXTemporaryObjectExprClass:
8805 case Expr::CXXUnresolvedConstructExprClass:
8806 case Expr::CXXDependentScopeMemberExprClass:
8807 case Expr::UnresolvedMemberExprClass:
8808 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008809 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008810 case Expr::ObjCArrayLiteralClass:
8811 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008812 case Expr::ObjCEncodeExprClass:
8813 case Expr::ObjCMessageExprClass:
8814 case Expr::ObjCSelectorExprClass:
8815 case Expr::ObjCProtocolExprClass:
8816 case Expr::ObjCIvarRefExprClass:
8817 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008818 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008819 case Expr::ObjCIsaExprClass:
8820 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008821 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008822 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008823 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008824 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008825 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008826 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008827 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008828 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008829 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008830 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008831 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008832 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008833 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00008834 case Expr::CXXFoldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008835 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008836
Richard Smithf137f932014-01-25 20:50:08 +00008837 case Expr::InitListExprClass: {
8838 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8839 // form "T x = { a };" is equivalent to "T x = a;".
8840 // Unless we're initializing a reference, T is a scalar as it is known to be
8841 // of integral or enumeration type.
8842 if (E->isRValue())
8843 if (cast<InitListExpr>(E)->getNumInits() == 1)
8844 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8845 return ICEDiag(IK_NotICE, E->getLocStart());
8846 }
8847
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008848 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008849 case Expr::GNUNullExprClass:
8850 // GCC considers the GNU __null value to be an integral constant expression.
8851 return NoDiag();
8852
John McCall7c454bb2011-07-15 05:09:51 +00008853 case Expr::SubstNonTypeTemplateParmExprClass:
8854 return
8855 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8856
John McCall864e3962010-05-07 05:32:02 +00008857 case Expr::ParenExprClass:
8858 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008859 case Expr::GenericSelectionExprClass:
8860 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008861 case Expr::IntegerLiteralClass:
8862 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008863 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008864 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008865 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008866 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008867 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008868 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008869 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008870 return NoDiag();
8871 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008872 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008873 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8874 // constant expressions, but they can never be ICEs because an ICE cannot
8875 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008876 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008877 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008878 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008879 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008880 }
Richard Smith6365c912012-02-24 22:12:32 +00008881 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008882 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8883 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008884 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008885 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008886 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008887 // Parameter variables are never constants. Without this check,
8888 // getAnyInitializer() can find a default argument, which leads
8889 // to chaos.
8890 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008891 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008892
8893 // C++ 7.1.5.1p2
8894 // A variable of non-volatile const-qualified integral or enumeration
8895 // type initialized by an ICE can be used in ICEs.
8896 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008897 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008898 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008899
Richard Smithd0b4dd62011-12-19 06:19:21 +00008900 const VarDecl *VD;
8901 // Look for a declaration of this variable that has an initializer, and
8902 // check whether it is an ICE.
8903 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8904 return NoDiag();
8905 else
Richard Smith9e575da2012-12-28 13:25:52 +00008906 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008907 }
8908 }
Richard Smith9e575da2012-12-28 13:25:52 +00008909 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008910 }
John McCall864e3962010-05-07 05:32:02 +00008911 case Expr::UnaryOperatorClass: {
8912 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8913 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008914 case UO_PostInc:
8915 case UO_PostDec:
8916 case UO_PreInc:
8917 case UO_PreDec:
8918 case UO_AddrOf:
8919 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008920 // C99 6.6/3 allows increment and decrement within unevaluated
8921 // subexpressions of constant expressions, but they can never be ICEs
8922 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008923 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008924 case UO_Extension:
8925 case UO_LNot:
8926 case UO_Plus:
8927 case UO_Minus:
8928 case UO_Not:
8929 case UO_Real:
8930 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008931 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008932 }
Richard Smith9e575da2012-12-28 13:25:52 +00008933
John McCall864e3962010-05-07 05:32:02 +00008934 // OffsetOf falls through here.
8935 }
8936 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008937 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8938 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8939 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8940 // compliance: we should warn earlier for offsetof expressions with
8941 // array subscripts that aren't ICEs, and if the array subscripts
8942 // are ICEs, the value of the offsetof must be an integer constant.
8943 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008944 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008945 case Expr::UnaryExprOrTypeTraitExprClass: {
8946 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8947 if ((Exp->getKind() == UETT_SizeOf) &&
8948 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008949 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008950 return NoDiag();
8951 }
8952 case Expr::BinaryOperatorClass: {
8953 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8954 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008955 case BO_PtrMemD:
8956 case BO_PtrMemI:
8957 case BO_Assign:
8958 case BO_MulAssign:
8959 case BO_DivAssign:
8960 case BO_RemAssign:
8961 case BO_AddAssign:
8962 case BO_SubAssign:
8963 case BO_ShlAssign:
8964 case BO_ShrAssign:
8965 case BO_AndAssign:
8966 case BO_XorAssign:
8967 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008968 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8969 // constant expressions, but they can never be ICEs because an ICE cannot
8970 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008971 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008972
John McCalle3027922010-08-25 11:45:40 +00008973 case BO_Mul:
8974 case BO_Div:
8975 case BO_Rem:
8976 case BO_Add:
8977 case BO_Sub:
8978 case BO_Shl:
8979 case BO_Shr:
8980 case BO_LT:
8981 case BO_GT:
8982 case BO_LE:
8983 case BO_GE:
8984 case BO_EQ:
8985 case BO_NE:
8986 case BO_And:
8987 case BO_Xor:
8988 case BO_Or:
8989 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008990 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8991 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008992 if (Exp->getOpcode() == BO_Div ||
8993 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008994 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008995 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008996 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008997 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008998 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008999 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009000 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009001 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009002 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009003 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009004 }
9005 }
9006 }
John McCalle3027922010-08-25 11:45:40 +00009007 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009008 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009009 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9010 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009011 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9012 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009013 } else {
9014 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009015 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009016 }
9017 }
Richard Smith9e575da2012-12-28 13:25:52 +00009018 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009019 }
John McCalle3027922010-08-25 11:45:40 +00009020 case BO_LAnd:
9021 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009022 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9023 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009024 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009025 // Rare case where the RHS has a comma "side-effect"; we need
9026 // to actually check the condition to see whether the side
9027 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009028 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009029 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009030 return RHSResult;
9031 return NoDiag();
9032 }
9033
Richard Smith9e575da2012-12-28 13:25:52 +00009034 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009035 }
9036 }
9037 }
9038 case Expr::ImplicitCastExprClass:
9039 case Expr::CStyleCastExprClass:
9040 case Expr::CXXFunctionalCastExprClass:
9041 case Expr::CXXStaticCastExprClass:
9042 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009043 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009044 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009045 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009046 if (isa<ExplicitCastExpr>(E)) {
9047 if (const FloatingLiteral *FL
9048 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9049 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9050 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9051 APSInt IgnoredVal(DestWidth, !DestSigned);
9052 bool Ignored;
9053 // If the value does not fit in the destination type, the behavior is
9054 // undefined, so we are not required to treat it as a constant
9055 // expression.
9056 if (FL->getValue().convertToInteger(IgnoredVal,
9057 llvm::APFloat::rmTowardZero,
9058 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009059 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009060 return NoDiag();
9061 }
9062 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009063 switch (cast<CastExpr>(E)->getCastKind()) {
9064 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009065 case CK_AtomicToNonAtomic:
9066 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009067 case CK_NoOp:
9068 case CK_IntegralToBoolean:
9069 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009070 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009071 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009072 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009073 }
John McCall864e3962010-05-07 05:32:02 +00009074 }
John McCallc07a0c72011-02-17 10:25:35 +00009075 case Expr::BinaryConditionalOperatorClass: {
9076 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9077 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009078 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009079 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009080 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9081 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9082 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009083 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009084 return FalseResult;
9085 }
John McCall864e3962010-05-07 05:32:02 +00009086 case Expr::ConditionalOperatorClass: {
9087 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9088 // If the condition (ignoring parens) is a __builtin_constant_p call,
9089 // then only the true side is actually considered in an integer constant
9090 // expression, and it is fully evaluated. This is an important GNU
9091 // extension. See GCC PR38377 for discussion.
9092 if (const CallExpr *CallCE
9093 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009094 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009095 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009096 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009097 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009098 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009099
Richard Smithf57d8cb2011-12-09 22:58:01 +00009100 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9101 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009102
Richard Smith9e575da2012-12-28 13:25:52 +00009103 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009104 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009105 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009106 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009107 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009108 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009109 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009110 return NoDiag();
9111 // Rare case where the diagnostics depend on which side is evaluated
9112 // Note that if we get here, CondResult is 0, and at least one of
9113 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009114 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009115 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009116 return TrueResult;
9117 }
9118 case Expr::CXXDefaultArgExprClass:
9119 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009120 case Expr::CXXDefaultInitExprClass:
9121 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009122 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009123 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009124 }
9125 }
9126
David Blaikiee4d798f2012-01-20 21:50:17 +00009127 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009128}
9129
Richard Smithf57d8cb2011-12-09 22:58:01 +00009130/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009131static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009132 const Expr *E,
9133 llvm::APSInt *Value,
9134 SourceLocation *Loc) {
9135 if (!E->getType()->isIntegralOrEnumerationType()) {
9136 if (Loc) *Loc = E->getExprLoc();
9137 return false;
9138 }
9139
Richard Smith66e05fe2012-01-18 05:21:49 +00009140 APValue Result;
9141 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009142 return false;
9143
Richard Smith98710fc2014-11-13 23:03:19 +00009144 if (!Result.isInt()) {
9145 if (Loc) *Loc = E->getExprLoc();
9146 return false;
9147 }
9148
Richard Smith66e05fe2012-01-18 05:21:49 +00009149 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009150 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009151}
9152
Craig Toppera31a8822013-08-22 07:09:37 +00009153bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9154 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009155 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009156 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009157
Richard Smith9e575da2012-12-28 13:25:52 +00009158 ICEDiag D = CheckICE(this, Ctx);
9159 if (D.Kind != IK_ICE) {
9160 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009161 return false;
9162 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009163 return true;
9164}
9165
Craig Toppera31a8822013-08-22 07:09:37 +00009166bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009167 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009168 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009169 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9170
9171 if (!isIntegerConstantExpr(Ctx, Loc))
9172 return false;
9173 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009174 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009175 return true;
9176}
Richard Smith66e05fe2012-01-18 05:21:49 +00009177
Craig Toppera31a8822013-08-22 07:09:37 +00009178bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009179 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009180}
9181
Craig Toppera31a8822013-08-22 07:09:37 +00009182bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009183 SourceLocation *Loc) const {
9184 // We support this checking in C++98 mode in order to diagnose compatibility
9185 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009186 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009187
Richard Smith98a0a492012-02-14 21:38:30 +00009188 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009189 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009190 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009191 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009192 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009193
9194 APValue Scratch;
9195 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9196
9197 if (!Diags.empty()) {
9198 IsConstExpr = false;
9199 if (Loc) *Loc = Diags[0].first;
9200 } else if (!IsConstExpr) {
9201 // FIXME: This shouldn't happen.
9202 if (Loc) *Loc = getExprLoc();
9203 }
9204
9205 return IsConstExpr;
9206}
Richard Smith253c2a32012-01-27 01:14:48 +00009207
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009208bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9209 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009210 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009211 Expr::EvalStatus Status;
9212 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9213
9214 ArgVector ArgValues(Args.size());
9215 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9216 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009217 if ((*I)->isValueDependent() ||
9218 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009219 // If evaluation fails, throw away the argument entirely.
9220 ArgValues[I - Args.begin()] = APValue();
9221 if (Info.EvalStatus.HasSideEffects)
9222 return false;
9223 }
9224
9225 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009226 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009227 ArgValues.data());
9228 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9229}
9230
Richard Smith253c2a32012-01-27 01:14:48 +00009231bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009232 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009233 PartialDiagnosticAt> &Diags) {
9234 // FIXME: It would be useful to check constexpr function templates, but at the
9235 // moment the constant expression evaluator cannot cope with the non-rigorous
9236 // ASTs which we build for dependent expressions.
9237 if (FD->isDependentContext())
9238 return true;
9239
9240 Expr::EvalStatus Status;
9241 Status.Diag = &Diags;
9242
Richard Smith6d4c6582013-11-05 22:18:15 +00009243 EvalInfo Info(FD->getASTContext(), Status,
9244 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009245
9246 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009247 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009248
Richard Smith7525ff62013-05-09 07:14:00 +00009249 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009250 // is a temporary being used as the 'this' pointer.
9251 LValue This;
9252 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009253 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009254
Richard Smith253c2a32012-01-27 01:14:48 +00009255 ArrayRef<const Expr*> Args;
9256
9257 SourceLocation Loc = FD->getLocation();
9258
Richard Smith2e312c82012-03-03 22:46:17 +00009259 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009260 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9261 // Evaluate the call as a constant initializer, to allow the construction
9262 // of objects of non-literal types.
9263 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009264 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009265 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009266 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009267 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009268
9269 return Diags.empty();
9270}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009271
9272bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9273 const FunctionDecl *FD,
9274 SmallVectorImpl<
9275 PartialDiagnosticAt> &Diags) {
9276 Expr::EvalStatus Status;
9277 Status.Diag = &Diags;
9278
9279 EvalInfo Info(FD->getASTContext(), Status,
9280 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9281
9282 // Fabricate a call stack frame to give the arguments a plausible cover story.
9283 ArrayRef<const Expr*> Args;
9284 ArgVector ArgValues(0);
9285 bool Success = EvaluateArgs(Args, ArgValues, Info);
9286 (void)Success;
9287 assert(Success &&
9288 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009289 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009290
9291 APValue ResultScratch;
9292 Evaluate(ResultScratch, Info, E);
9293 return Diags.empty();
9294}