1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
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 //
12 // 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
26 // (under the C++11 rules only, at the moment), or, if folding failed too,
27 // why the expression could not be folded.
28 //
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 //
34 //===----------------------------------------------------------------------===//
35
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/CharUnits.h"
39 #include "clang/AST/RecordLayout.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TypeLoc.h"
42 #include "clang/AST/ASTDiagnostic.h"
43 #include "clang/AST/Expr.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include <cstring>
48 #include <functional>
49
50 using namespace clang;
51 using llvm::APSInt;
52 using llvm::APFloat;
53
54 static bool IsGlobalLValue(APValue::LValueBase B);
55
56 namespace {
57 struct LValue;
58 struct CallStackFrame;
59 struct EvalInfo;
60
getType(APValue::LValueBase B)61 static QualType getType(APValue::LValueBase B) {
62 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
68 /// Get an LValue path entry, which is known to not be an array index, as a
69 /// field or base class.
70 static
getAsBaseOrMember(APValue::LValuePathEntry E)71 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
72 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
74 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
getAsField(APValue::LValuePathEntry E)79 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
80 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
81 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
getAsBaseClass(APValue::LValuePathEntry E)84 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
85 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
86 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
isVirtualBaseClass(APValue::LValuePathEntry E)89 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
90 return getAsBaseOrMember(E).getInt();
91 }
92
93 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
findMostDerivedSubobject(ASTContext & Ctx,QualType Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type)96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
118 // Path[I] describes a base class.
119 ArraySize = 0;
120 }
121 }
122 return MostDerivedLength;
123 }
124
125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
128 CSK_This, CSK_Real, CSK_Imag
129 };
130
131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
140
141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
151
152 typedef APValue::LValuePathEntry PathEntry;
153
154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
SubobjectDesignator__anon39b33ae20111::SubobjectDesignator157 SubobjectDesignator() : Invalid(true) {}
158
SubobjectDesignator__anon39b33ae20111::SubobjectDesignator159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
SubobjectDesignator__anon39b33ae20111::SubobjectDesignator163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
166 if (!Invalid) {
167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
175 }
176 }
177
setInvalid__anon39b33ae20111::SubobjectDesignator178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
182
183 /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anon39b33ae20111::SubobjectDesignator184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
isValidSubobject__anon39b33ae20111::SubobjectDesignator194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anon39b33ae20111::SubobjectDesignator204 void addArrayUnchecked(const ConstantArrayType *CAT) {
205 PathEntry Entry;
206 Entry.ArrayIndex = 0;
207 Entries.push_back(Entry);
208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
addDeclUnchecked__anon39b33ae20111::SubobjectDesignator216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
217 PathEntry Entry;
218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
220 Entries.push_back(Entry);
221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
228 }
229 /// Update this designator to refer to the given complex component.
addComplexUnchecked__anon39b33ae20111::SubobjectDesignator230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
242 /// Add N to the address of this subobject.
adjustIndex__anon39b33ae20111::SubobjectDesignator243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
244 if (Invalid) return;
245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
246 Entries.back().ArrayIndex += N;
247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
251 return;
252 }
253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
262 setInvalid();
263 }
264 }
265 };
266
267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
272 CallStackFrame *Caller;
273
274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
280 /// Index - The call index of this call.
281 unsigned Index;
282
283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
288 const APValue *Arguments;
289
290 // Note that we intentionally use std::map here so that references to
291 // values are stable.
292 typedef std::map<const Expr*, APValue> MapTy;
293 typedef MapTy::const_iterator temp_iterator;
294 /// Temporaries - Temporary lvalues materialized within this stack frame.
295 MapTy Temporaries;
296
297 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
298 const FunctionDecl *Callee, const LValue *This,
299 const APValue *Arguments);
300 ~CallStackFrame();
301 };
302
303 /// A partial diagnostic which we might know in advance that we are not going
304 /// to emit.
305 class OptionalDiagnostic {
306 PartialDiagnostic *Diag;
307
308 public:
OptionalDiagnostic(PartialDiagnostic * Diag=0)309 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
310
311 template<typename T>
operator <<(const T & v)312 OptionalDiagnostic &operator<<(const T &v) {
313 if (Diag)
314 *Diag << v;
315 return *this;
316 }
317
operator <<(const APSInt & I)318 OptionalDiagnostic &operator<<(const APSInt &I) {
319 if (Diag) {
320 llvm::SmallVector<char, 32> Buffer;
321 I.toString(Buffer);
322 *Diag << StringRef(Buffer.data(), Buffer.size());
323 }
324 return *this;
325 }
326
operator <<(const APFloat & F)327 OptionalDiagnostic &operator<<(const APFloat &F) {
328 if (Diag) {
329 llvm::SmallVector<char, 32> Buffer;
330 F.toString(Buffer);
331 *Diag << StringRef(Buffer.data(), Buffer.size());
332 }
333 return *this;
334 }
335 };
336
337 /// EvalInfo - This is a private struct used by the evaluator to capture
338 /// information about a subexpression as it is folded. It retains information
339 /// about the AST context, but also maintains information about the folded
340 /// expression.
341 ///
342 /// If an expression could be evaluated, it is still possible it is not a C
343 /// "integer constant expression" or constant expression. If not, this struct
344 /// captures information about how and why not.
345 ///
346 /// One bit of information passed *into* the request for constant folding
347 /// indicates whether the subexpression is "evaluated" or not according to C
348 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
349 /// evaluate the expression regardless of what the RHS is, but C only allows
350 /// certain things in certain situations.
351 struct EvalInfo {
352 ASTContext &Ctx;
353
354 /// EvalStatus - Contains information about the evaluation.
355 Expr::EvalStatus &EvalStatus;
356
357 /// CurrentCall - The top of the constexpr call stack.
358 CallStackFrame *CurrentCall;
359
360 /// CallStackDepth - The number of calls in the call stack right now.
361 unsigned CallStackDepth;
362
363 /// NextCallIndex - The next call index to assign.
364 unsigned NextCallIndex;
365
366 /// BottomFrame - The frame in which evaluation started. This must be
367 /// initialized after CurrentCall and CallStackDepth.
368 CallStackFrame BottomFrame;
369
370 /// EvaluatingDecl - This is the declaration whose initializer is being
371 /// evaluated, if any.
372 const VarDecl *EvaluatingDecl;
373
374 /// EvaluatingDeclValue - This is the value being constructed for the
375 /// declaration whose initializer is being evaluated, if any.
376 APValue *EvaluatingDeclValue;
377
378 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
379 /// notes attached to it will also be stored, otherwise they will not be.
380 bool HasActiveDiagnostic;
381
382 /// CheckingPotentialConstantExpression - Are we checking whether the
383 /// expression is a potential constant expression? If so, some diagnostics
384 /// are suppressed.
385 bool CheckingPotentialConstantExpression;
386
EvalInfo__anon39b33ae20111::EvalInfo387 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
388 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
389 CallStackDepth(0), NextCallIndex(1),
390 BottomFrame(*this, SourceLocation(), 0, 0, 0),
391 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
392 CheckingPotentialConstantExpression(false) {}
393
setEvaluatingDecl__anon39b33ae20111::EvalInfo394 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
395 EvaluatingDecl = VD;
396 EvaluatingDeclValue = &Value;
397 }
398
getLangOpts__anon39b33ae20111::EvalInfo399 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
400
CheckCallLimit__anon39b33ae20111::EvalInfo401 bool CheckCallLimit(SourceLocation Loc) {
402 // Don't perform any constexpr calls (other than the call we're checking)
403 // when checking a potential constant expression.
404 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
405 return false;
406 if (NextCallIndex == 0) {
407 // NextCallIndex has wrapped around.
408 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
409 return false;
410 }
411 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
412 return true;
413 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
414 << getLangOpts().ConstexprCallDepth;
415 return false;
416 }
417
getCallFrame__anon39b33ae20111::EvalInfo418 CallStackFrame *getCallFrame(unsigned CallIndex) {
419 assert(CallIndex && "no call index in getCallFrame");
420 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
421 // be null in this loop.
422 CallStackFrame *Frame = CurrentCall;
423 while (Frame->Index > CallIndex)
424 Frame = Frame->Caller;
425 return (Frame->Index == CallIndex) ? Frame : 0;
426 }
427
428 private:
429 /// Add a diagnostic to the diagnostics list.
addDiag__anon39b33ae20111::EvalInfo430 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
431 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
432 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
433 return EvalStatus.Diag->back().second;
434 }
435
436 /// Add notes containing a call stack to the current point of evaluation.
437 void addCallStack(unsigned Limit);
438
439 public:
440 /// Diagnose that the evaluation cannot be folded.
Diag__anon39b33ae20111::EvalInfo441 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
442 = diag::note_invalid_subexpr_in_const_expr,
443 unsigned ExtraNotes = 0) {
444 // If we have a prior diagnostic, it will be noting that the expression
445 // isn't a constant expression. This diagnostic is more important.
446 // FIXME: We might want to show both diagnostics to the user.
447 if (EvalStatus.Diag) {
448 unsigned CallStackNotes = CallStackDepth - 1;
449 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
450 if (Limit)
451 CallStackNotes = std::min(CallStackNotes, Limit + 1);
452 if (CheckingPotentialConstantExpression)
453 CallStackNotes = 0;
454
455 HasActiveDiagnostic = true;
456 EvalStatus.Diag->clear();
457 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
458 addDiag(Loc, DiagId);
459 if (!CheckingPotentialConstantExpression)
460 addCallStack(Limit);
461 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
462 }
463 HasActiveDiagnostic = false;
464 return OptionalDiagnostic();
465 }
466
Diag__anon39b33ae20111::EvalInfo467 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
468 = diag::note_invalid_subexpr_in_const_expr,
469 unsigned ExtraNotes = 0) {
470 if (EvalStatus.Diag)
471 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
474 }
475
476 /// Diagnose that the evaluation does not produce a C++11 core constant
477 /// expression.
478 template<typename LocArg>
CCEDiag__anon39b33ae20111::EvalInfo479 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
480 = diag::note_invalid_subexpr_in_const_expr,
481 unsigned ExtraNotes = 0) {
482 // Don't override a previous diagnostic.
483 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
484 HasActiveDiagnostic = false;
485 return OptionalDiagnostic();
486 }
487 return Diag(Loc, DiagId, ExtraNotes);
488 }
489
490 /// Add a note to a prior diagnostic.
Note__anon39b33ae20111::EvalInfo491 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
492 if (!HasActiveDiagnostic)
493 return OptionalDiagnostic();
494 return OptionalDiagnostic(&addDiag(Loc, DiagId));
495 }
496
497 /// Add a stack of notes to a prior diagnostic.
addNotes__anon39b33ae20111::EvalInfo498 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
499 if (HasActiveDiagnostic) {
500 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
501 Diags.begin(), Diags.end());
502 }
503 }
504
505 /// Should we continue evaluation as much as possible after encountering a
506 /// construct which can't be folded?
keepEvaluatingAfterFailure__anon39b33ae20111::EvalInfo507 bool keepEvaluatingAfterFailure() {
508 return CheckingPotentialConstantExpression &&
509 EvalStatus.Diag && EvalStatus.Diag->empty();
510 }
511 };
512
513 /// Object used to treat all foldable expressions as constant expressions.
514 struct FoldConstant {
515 bool Enabled;
516
FoldConstant__anon39b33ae20111::FoldConstant517 explicit FoldConstant(EvalInfo &Info)
518 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
519 !Info.EvalStatus.HasSideEffects) {
520 }
521 // Treat the value we've computed since this object was created as constant.
Fold__anon39b33ae20111::FoldConstant522 void Fold(EvalInfo &Info) {
523 if (Enabled && !Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects)
525 Info.EvalStatus.Diag->clear();
526 }
527 };
528
529 /// RAII object used to suppress diagnostics and side-effects from a
530 /// speculative evaluation.
531 class SpeculativeEvaluationRAII {
532 EvalInfo &Info;
533 Expr::EvalStatus Old;
534
535 public:
SpeculativeEvaluationRAII(EvalInfo & Info,llvm::SmallVectorImpl<PartialDiagnosticAt> * NewDiag=0)536 SpeculativeEvaluationRAII(EvalInfo &Info,
537 llvm::SmallVectorImpl<PartialDiagnosticAt>
538 *NewDiag = 0)
539 : Info(Info), Old(Info.EvalStatus) {
540 Info.EvalStatus.Diag = NewDiag;
541 }
~SpeculativeEvaluationRAII()542 ~SpeculativeEvaluationRAII() {
543 Info.EvalStatus = Old;
544 }
545 };
546 }
547
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)548 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
549 CheckSubobjectKind CSK) {
550 if (Invalid)
551 return false;
552 if (isOnePastTheEnd()) {
553 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
554 << CSK;
555 setInvalid();
556 return false;
557 }
558 return true;
559 }
560
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,uint64_t N)561 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
562 const Expr *E, uint64_t N) {
563 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
564 Info.CCEDiag(E, diag::note_constexpr_array_index)
565 << static_cast<int>(N) << /*array*/ 0
566 << static_cast<unsigned>(MostDerivedArraySize);
567 else
568 Info.CCEDiag(E, diag::note_constexpr_array_index)
569 << static_cast<int>(N) << /*non-array*/ 1;
570 setInvalid();
571 }
572
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,const APValue * Arguments)573 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
574 const FunctionDecl *Callee, const LValue *This,
575 const APValue *Arguments)
576 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
577 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
578 Info.CurrentCall = this;
579 ++Info.CallStackDepth;
580 }
581
~CallStackFrame()582 CallStackFrame::~CallStackFrame() {
583 assert(Info.CurrentCall == this && "calls retired out of order");
584 --Info.CallStackDepth;
585 Info.CurrentCall = Caller;
586 }
587
588 /// Produce a string describing the given constexpr call.
describeCall(CallStackFrame * Frame,llvm::raw_ostream & Out)589 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
590 unsigned ArgIndex = 0;
591 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
592 !isa<CXXConstructorDecl>(Frame->Callee) &&
593 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
594
595 if (!IsMemberCall)
596 Out << *Frame->Callee << '(';
597
598 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
599 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
600 if (ArgIndex > (unsigned)IsMemberCall)
601 Out << ", ";
602
603 const ParmVarDecl *Param = *I;
604 const APValue &Arg = Frame->Arguments[ArgIndex];
605 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
606
607 if (ArgIndex == 0 && IsMemberCall)
608 Out << "->" << *Frame->Callee << '(';
609 }
610
611 Out << ')';
612 }
613
addCallStack(unsigned Limit)614 void EvalInfo::addCallStack(unsigned Limit) {
615 // Determine which calls to skip, if any.
616 unsigned ActiveCalls = CallStackDepth - 1;
617 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
618 if (Limit && Limit < ActiveCalls) {
619 SkipStart = Limit / 2 + Limit % 2;
620 SkipEnd = ActiveCalls - Limit / 2;
621 }
622
623 // Walk the call stack and add the diagnostics.
624 unsigned CallIdx = 0;
625 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
626 Frame = Frame->Caller, ++CallIdx) {
627 // Skip this call?
628 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
629 if (CallIdx == SkipStart) {
630 // Note that we're skipping calls.
631 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
632 << unsigned(ActiveCalls - Limit);
633 }
634 continue;
635 }
636
637 llvm::SmallVector<char, 128> Buffer;
638 llvm::raw_svector_ostream Out(Buffer);
639 describeCall(Frame, Out);
640 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
641 }
642 }
643
644 namespace {
645 struct ComplexValue {
646 private:
647 bool IsInt;
648
649 public:
650 APSInt IntReal, IntImag;
651 APFloat FloatReal, FloatImag;
652
ComplexValue__anon39b33ae20211::ComplexValue653 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
654
makeComplexFloat__anon39b33ae20211::ComplexValue655 void makeComplexFloat() { IsInt = false; }
isComplexFloat__anon39b33ae20211::ComplexValue656 bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anon39b33ae20211::ComplexValue657 APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anon39b33ae20211::ComplexValue658 APFloat &getComplexFloatImag() { return FloatImag; }
659
makeComplexInt__anon39b33ae20211::ComplexValue660 void makeComplexInt() { IsInt = true; }
isComplexInt__anon39b33ae20211::ComplexValue661 bool isComplexInt() const { return IsInt; }
getComplexIntReal__anon39b33ae20211::ComplexValue662 APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anon39b33ae20211::ComplexValue663 APSInt &getComplexIntImag() { return IntImag; }
664
moveInto__anon39b33ae20211::ComplexValue665 void moveInto(APValue &v) const {
666 if (isComplexFloat())
667 v = APValue(FloatReal, FloatImag);
668 else
669 v = APValue(IntReal, IntImag);
670 }
setFrom__anon39b33ae20211::ComplexValue671 void setFrom(const APValue &v) {
672 assert(v.isComplexFloat() || v.isComplexInt());
673 if (v.isComplexFloat()) {
674 makeComplexFloat();
675 FloatReal = v.getComplexFloatReal();
676 FloatImag = v.getComplexFloatImag();
677 } else {
678 makeComplexInt();
679 IntReal = v.getComplexIntReal();
680 IntImag = v.getComplexIntImag();
681 }
682 }
683 };
684
685 struct LValue {
686 APValue::LValueBase Base;
687 CharUnits Offset;
688 unsigned CallIndex;
689 SubobjectDesignator Designator;
690
getLValueBase__anon39b33ae20211::LValue691 const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anon39b33ae20211::LValue692 CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anon39b33ae20211::LValue693 const CharUnits &getLValueOffset() const { return Offset; }
getLValueCallIndex__anon39b33ae20211::LValue694 unsigned getLValueCallIndex() const { return CallIndex; }
getLValueDesignator__anon39b33ae20211::LValue695 SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anon39b33ae20211::LValue696 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
697
moveInto__anon39b33ae20211::LValue698 void moveInto(APValue &V) const {
699 if (Designator.Invalid)
700 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
701 else
702 V = APValue(Base, Offset, Designator.Entries,
703 Designator.IsOnePastTheEnd, CallIndex);
704 }
setFrom__anon39b33ae20211::LValue705 void setFrom(ASTContext &Ctx, const APValue &V) {
706 assert(V.isLValue());
707 Base = V.getLValueBase();
708 Offset = V.getLValueOffset();
709 CallIndex = V.getLValueCallIndex();
710 Designator = SubobjectDesignator(Ctx, V);
711 }
712
set__anon39b33ae20211::LValue713 void set(APValue::LValueBase B, unsigned I = 0) {
714 Base = B;
715 Offset = CharUnits::Zero();
716 CallIndex = I;
717 Designator = SubobjectDesignator(getType(B));
718 }
719
720 // Check that this LValue is not based on a null pointer. If it is, produce
721 // a diagnostic and mark the designator as invalid.
checkNullPointer__anon39b33ae20211::LValue722 bool checkNullPointer(EvalInfo &Info, const Expr *E,
723 CheckSubobjectKind CSK) {
724 if (Designator.Invalid)
725 return false;
726 if (!Base) {
727 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
728 << CSK;
729 Designator.setInvalid();
730 return false;
731 }
732 return true;
733 }
734
735 // Check this LValue refers to an object. If not, set the designator to be
736 // invalid and emit a diagnostic.
checkSubobject__anon39b33ae20211::LValue737 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
738 // Outside C++11, do not build a designator referring to a subobject of
739 // any object: we won't use such a designator for anything.
740 if (!Info.getLangOpts().CPlusPlus0x)
741 Designator.setInvalid();
742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
744 }
745
addDecl__anon39b33ae20211::LValue746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
750 }
addArray__anon39b33ae20211::LValue751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
754 }
addComplex__anon39b33ae20211::LValue755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
758 }
adjustIndex__anon39b33ae20211::LValue759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
762 }
763 };
764
765 struct MemberPtr {
MemberPtr__anon39b33ae20211::MemberPtr766 MemberPtr() {}
MemberPtr__anon39b33ae20211::MemberPtr767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
769
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
getDecl__anon39b33ae20211::MemberPtr772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
774 }
775 /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anon39b33ae20211::MemberPtr776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
778 }
779 /// Get the class which the declaration actually lives in.
getContainingRecord__anon39b33ae20211::MemberPtr780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
783 }
784
moveInto__anon39b33ae20211::MemberPtr785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
787 }
setFrom__anon39b33ae20211::MemberPtr788 void setFrom(const APValue &V) {
789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
792 Path.clear();
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
795 }
796
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
804
805 /// Perform a cast towards the class of the Decl (either up or down the
806 /// hierarchy).
castBack__anon39b33ae20211::MemberPtr807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
812 else
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
821 return false;
822 }
823 Path.pop_back();
824 return true;
825 }
826 /// Perform a base-to-derived member pointer cast.
castToDerived__anon39b33ae20211::MemberPtr827 bool castToDerived(const CXXRecordDecl *Derived) {
828 if (!getDecl())
829 return true;
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
832 return true;
833 }
834 if (!castBack(Derived))
835 return false;
836 if (Path.empty())
837 DeclAndIsDerivedMember.setInt(false);
838 return true;
839 }
840 /// Perform a derived-to-base member pointer cast.
castToBase__anon39b33ae20211::MemberPtr841 bool castToBase(const CXXRecordDecl *Base) {
842 if (!getDecl())
843 return true;
844 if (Path.empty())
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
848 return true;
849 }
850 return castBack(Base);
851 }
852 };
853
854 /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
859 return false;
860 return LHS.Path == RHS.Path;
861 }
862
863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
868 };
869 }
870
871 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
872 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
876 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
878 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
879 EvalInfo &Info);
880 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
881 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
882 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
883 EvalInfo &Info);
884 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
885 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
886
887 //===----------------------------------------------------------------------===//
888 // Misc utilities
889 //===----------------------------------------------------------------------===//
890
891 /// Should this call expression be treated as a string literal?
IsStringLiteralCall(const CallExpr * E)892 static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
896 }
897
IsGlobalLValue(APValue::LValueBase B)898 static bool IsGlobalLValue(APValue::LValueBase B) {
899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
901
902 // ... a null pointer value, or a prvalue core constant expression of type
903 // std::nullptr_t.
904 if (!B) return true;
905
906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
912 }
913
914 const Expr *E = B.get<const Expr*>();
915 switch (E->getStmtClass()) {
916 default:
917 return false;
918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
921 }
922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
927 case Expr::CXXTypeidExprClass:
928 case Expr::CXXUuidofExprClass:
929 return true;
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
934 return true;
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
939 case Expr::ImplicitValueInitExprClass:
940 // FIXME:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
946 return true;
947 }
948 }
949
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)950 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
953 if (VD)
954 Info.Note(VD->getLocation(), diag::note_declared_at);
955 else
956 Info.Note(Base.get<const Expr*>()->getExprLoc(),
957 diag::note_constexpr_temporary_here);
958 }
959
960 /// Check that this reference or pointer core constant expression is a valid
961 /// value for an address or reference constant expression. Return true if we
962 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal)963 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
966
967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
969
970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
973 if (!IsGlobalLValue(Base)) {
974 if (Info.getLangOpts().CPlusPlus0x) {
975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
978 << !!VD << VD;
979 NoteLValueLocation(Info, Base);
980 } else {
981 Info.Diag(Loc);
982 }
983 // Don't allow references to temporaries to escape.
984 return false;
985 }
986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
989
990 // Check if this is a thread-local variable.
991 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
992 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
993 if (Var->isThreadSpecified())
994 return false;
995 }
996 }
997
998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
1006 Info.CCEDiag(Loc);
1007 return true;
1008 }
1009
1010 // Does this refer one past the end of some object?
1011 if (Designator.isOnePastTheEnd()) {
1012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1014 << !Designator.Entries.empty() << !!VD << VD;
1015 NoteLValueLocation(Info, Base);
1016 }
1017
1018 return true;
1019 }
1020
1021 /// Check that this core constant expression is of literal type, and if not,
1022 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E)1023 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
1029 Info.Diag(E, diag::note_constexpr_nonliteral)
1030 << E->getType();
1031 else
1032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1033 return false;
1034 }
1035
1036 /// Check that this core constant expression value is a valid value for a
1037 /// constant expression. If not, report an appropriate diagnostic. Does not
1038 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)1039 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
1055 }
1056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
1074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075 Value.getStructField(I->getFieldIndex())))
1076 return false;
1077 }
1078 }
1079
1080 if (Value.isLValue()) {
1081 LValue LVal;
1082 LVal.setFrom(Info.Ctx, Value);
1083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1084 }
1085
1086 // Everything else is fine.
1087 return true;
1088 }
1089
GetLValueBaseDecl(const LValue & LVal)1090 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1091 return LVal.Base.dyn_cast<const ValueDecl*>();
1092 }
1093
IsLiteralLValue(const LValue & Value)1094 static bool IsLiteralLValue(const LValue &Value) {
1095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
1096 }
1097
IsWeakLValue(const LValue & Value)1098 static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1100 return Decl && Decl->isWeak();
1101 }
1102
EvalPointerValueAsBool(const APValue & Value,bool & Result)1103 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
1106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
1108 return true;
1109 }
1110
1111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
1113 Result = true;
1114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1115 return !Decl || !Decl->isWeak();
1116 }
1117
HandleConversionToBool(const APValue & Val,bool & Result)1118 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1121 return false;
1122 case APValue::Int:
1123 Result = Val.getInt().getBoolValue();
1124 return true;
1125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
1127 return true;
1128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1131 return true;
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1135 return true;
1136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1140 return true;
1141 case APValue::Vector:
1142 case APValue::Array:
1143 case APValue::Struct:
1144 case APValue::Union:
1145 case APValue::AddrLabelDiff:
1146 return false;
1147 }
1148
1149 llvm_unreachable("unknown APValue kind");
1150 }
1151
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)1152 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1153 EvalInfo &Info) {
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1155 APValue Val;
1156 if (!Evaluate(Val, Info, E))
1157 return false;
1158 return HandleConversionToBool(Val, Result);
1159 }
1160
1161 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)1162 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1163 const T &SrcValue, QualType DestType) {
1164 Info.CCEDiag(E, diag::note_constexpr_overflow)
1165 << SrcValue << DestType;
1166 }
1167
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)1168 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1169 QualType SrcType, const APFloat &Value,
1170 QualType DestType, APSInt &Result) {
1171 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1172 // Determine whether we are converting to unsigned or signed.
1173 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1174
1175 Result = APSInt(DestWidth, !DestSigned);
1176 bool ignored;
1177 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1178 & APFloat::opInvalidOp)
1179 HandleOverflow(Info, E, Value, DestType);
1180 return true;
1181 }
1182
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)1183 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1184 QualType SrcType, QualType DestType,
1185 APFloat &Result) {
1186 APFloat Value = Result;
1187 bool ignored;
1188 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1189 APFloat::rmNearestTiesToEven, &ignored)
1190 & APFloat::opOverflow)
1191 HandleOverflow(Info, E, Value, DestType);
1192 return true;
1193 }
1194
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,APSInt & Value)1195 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1196 QualType DestType, QualType SrcType,
1197 APSInt &Value) {
1198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1199 APSInt Result = Value;
1200 // Figure out if this is a truncate, extend or noop cast.
1201 // If the input is signed, do a sign extend, noop, or truncate.
1202 Result = Result.extOrTrunc(DestWidth);
1203 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1204 return Result;
1205 }
1206
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)1207 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1208 QualType SrcType, const APSInt &Value,
1209 QualType DestType, APFloat &Result) {
1210 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1211 if (Result.convertFromAPInt(Value, Value.isSigned(),
1212 APFloat::rmNearestTiesToEven)
1213 & APFloat::opOverflow)
1214 HandleOverflow(Info, E, Value, DestType);
1215 return true;
1216 }
1217
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)1218 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1219 llvm::APInt &Res) {
1220 APValue SVal;
1221 if (!Evaluate(SVal, Info, E))
1222 return false;
1223 if (SVal.isInt()) {
1224 Res = SVal.getInt();
1225 return true;
1226 }
1227 if (SVal.isFloat()) {
1228 Res = SVal.getFloat().bitcastToAPInt();
1229 return true;
1230 }
1231 if (SVal.isVector()) {
1232 QualType VecTy = E->getType();
1233 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1234 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1235 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1236 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1237 Res = llvm::APInt::getNullValue(VecSize);
1238 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1239 APValue &Elt = SVal.getVectorElt(i);
1240 llvm::APInt EltAsInt;
1241 if (Elt.isInt()) {
1242 EltAsInt = Elt.getInt();
1243 } else if (Elt.isFloat()) {
1244 EltAsInt = Elt.getFloat().bitcastToAPInt();
1245 } else {
1246 // Don't try to handle vectors of anything other than int or float
1247 // (not sure if it's possible to hit this case).
1248 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1249 return false;
1250 }
1251 unsigned BaseEltSize = EltAsInt.getBitWidth();
1252 if (BigEndian)
1253 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1254 else
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1256 }
1257 return true;
1258 }
1259 // Give up if the input isn't an int, float, or vector. For example, we
1260 // reject "(v4i16)(intptr_t)&a".
1261 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1262 return false;
1263 }
1264
1265 /// Cast an lvalue referring to a base subobject to a derived class, by
1266 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)1267 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1268 const RecordDecl *TruncatedType,
1269 unsigned TruncatedElements) {
1270 SubobjectDesignator &D = Result.Designator;
1271
1272 // Check we actually point to a derived class object.
1273 if (TruncatedElements == D.Entries.size())
1274 return true;
1275 assert(TruncatedElements >= D.MostDerivedPathLength &&
1276 "not casting to a derived class");
1277 if (!Result.checkSubobject(Info, E, CSK_Derived))
1278 return false;
1279
1280 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1281 const RecordDecl *RD = TruncatedType;
1282 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1283 if (RD->isInvalidDecl()) return false;
1284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1286 if (isVirtualBaseClass(D.Entries[I]))
1287 Result.Offset -= Layout.getVBaseClassOffset(Base);
1288 else
1289 Result.Offset -= Layout.getBaseClassOffset(Base);
1290 RD = Base;
1291 }
1292 D.Entries.resize(TruncatedElements);
1293 return true;
1294 }
1295
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=0)1296 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
1300 if (!RL) {
1301 if (Derived->isInvalidDecl()) return false;
1302 RL = &Info.Ctx.getASTRecordLayout(Derived);
1303 }
1304
1305 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1306 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1307 return true;
1308 }
1309
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)1310 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1311 const CXXRecordDecl *DerivedDecl,
1312 const CXXBaseSpecifier *Base) {
1313 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1314
1315 if (!Base->isVirtual())
1316 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1317
1318 SubobjectDesignator &D = Obj.Designator;
1319 if (D.Invalid)
1320 return false;
1321
1322 // Extract most-derived object and corresponding type.
1323 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1324 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1325 return false;
1326
1327 // Find the virtual base class.
1328 if (DerivedDecl->isInvalidDecl()) return false;
1329 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1330 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1331 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1332 return true;
1333 }
1334
1335 /// Update LVal to refer to the given field, which must be a member of the type
1336 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=0)1337 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1338 const FieldDecl *FD,
1339 const ASTRecordLayout *RL = 0) {
1340 if (!RL) {
1341 if (FD->getParent()->isInvalidDecl()) return false;
1342 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1343 }
1344
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1347 LVal.addDecl(Info, E, FD);
1348 return true;
1349 }
1350
1351 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)1352 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1353 LValue &LVal,
1354 const IndirectFieldDecl *IFD) {
1355 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356 CE = IFD->chain_end(); C != CE; ++C)
1357 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1358 return false;
1359 return true;
1360 }
1361
1362 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)1363 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1364 QualType Type, CharUnits &Size) {
1365 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1366 // extension.
1367 if (Type->isVoidType() || Type->isFunctionType()) {
1368 Size = CharUnits::One();
1369 return true;
1370 }
1371
1372 if (!Type->isConstantSizeType()) {
1373 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1374 // FIXME: Better diagnostic.
1375 Info.Diag(Loc);
1376 return false;
1377 }
1378
1379 Size = Info.Ctx.getTypeSizeInChars(Type);
1380 return true;
1381 }
1382
1383 /// Update a pointer value to model pointer arithmetic.
1384 /// \param Info - Information about the ongoing evaluation.
1385 /// \param E - The expression being evaluated, for diagnostic purposes.
1386 /// \param LVal - The pointer value to be updated.
1387 /// \param EltTy - The pointee type represented by LVal.
1388 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)1389 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1390 LValue &LVal, QualType EltTy,
1391 int64_t Adjustment) {
1392 CharUnits SizeOfPointee;
1393 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1394 return false;
1395
1396 // Compute the new offset in the appropriate width.
1397 LVal.Offset += Adjustment * SizeOfPointee;
1398 LVal.adjustIndex(Info, E, Adjustment);
1399 return true;
1400 }
1401
1402 /// Update an lvalue to refer to a component of a complex number.
1403 /// \param Info - Information about the ongoing evaluation.
1404 /// \param LVal - The lvalue to be updated.
1405 /// \param EltTy - The complex number's component type.
1406 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)1407 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1408 LValue &LVal, QualType EltTy,
1409 bool Imag) {
1410 if (Imag) {
1411 CharUnits SizeOfComponent;
1412 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1413 return false;
1414 LVal.Offset += SizeOfComponent;
1415 }
1416 LVal.addComplex(Info, E, EltTy, Imag);
1417 return true;
1418 }
1419
1420 /// Try to evaluate the initializer for a variable declaration.
EvaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,APValue & Result)1421 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1422 const VarDecl *VD,
1423 CallStackFrame *Frame, APValue &Result) {
1424 // If this is a parameter to an active constexpr function call, perform
1425 // argument substitution.
1426 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1427 // Assume arguments of a potential constant expression are unknown
1428 // constant expressions.
1429 if (Info.CheckingPotentialConstantExpression)
1430 return false;
1431 if (!Frame || !Frame->Arguments) {
1432 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1433 return false;
1434 }
1435 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1436 return true;
1437 }
1438
1439 // Dig out the initializer, and use the declaration which it's attached to.
1440 const Expr *Init = VD->getAnyInitializer(VD);
1441 if (!Init || Init->isValueDependent()) {
1442 // If we're checking a potential constant expression, the variable could be
1443 // initialized later.
1444 if (!Info.CheckingPotentialConstantExpression)
1445 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1446 return false;
1447 }
1448
1449 // If we're currently evaluating the initializer of this declaration, use that
1450 // in-flight value.
1451 if (Info.EvaluatingDecl == VD) {
1452 Result = *Info.EvaluatingDeclValue;
1453 return !Result.isUninit();
1454 }
1455
1456 // Never evaluate the initializer of a weak variable. We can't be sure that
1457 // this is the definition which will be used.
1458 if (VD->isWeak()) {
1459 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1460 return false;
1461 }
1462
1463 // Check that we can fold the initializer. In C++, we will have already done
1464 // this in the cases where it matters for conformance.
1465 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1466 if (!VD->evaluateValue(Notes)) {
1467 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1468 Notes.size() + 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 Info.addNotes(Notes);
1471 return false;
1472 } else if (!VD->checkInitIsICE()) {
1473 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1474 Notes.size() + 1) << VD;
1475 Info.Note(VD->getLocation(), diag::note_declared_at);
1476 Info.addNotes(Notes);
1477 }
1478
1479 Result = *VD->getEvaluatedValue();
1480 return true;
1481 }
1482
IsConstNonVolatile(QualType T)1483 static bool IsConstNonVolatile(QualType T) {
1484 Qualifiers Quals = T.getQualifiers();
1485 return Quals.hasConst() && !Quals.hasVolatile();
1486 }
1487
1488 /// Get the base index of the given base class within an APValue representing
1489 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)1490 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1491 const CXXRecordDecl *Base) {
1492 Base = Base->getCanonicalDecl();
1493 unsigned Index = 0;
1494 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1495 E = Derived->bases_end(); I != E; ++I, ++Index) {
1496 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1497 return Index;
1498 }
1499
1500 llvm_unreachable("base class missing from derived class's bases list");
1501 }
1502
1503 /// Extract the value of a character from a string literal. CharType is used to
1504 /// determine the expected signedness of the result -- a string literal used to
1505 /// initialize an array of 'signed char' or 'unsigned char' might contain chars
1506 /// of the wrong signedness.
ExtractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index,QualType CharType)1507 static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1508 uint64_t Index, QualType CharType) {
1509 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1510 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1511 assert(S && "unexpected string literal expression kind");
1512 assert(CharType->isIntegerType() && "unexpected character type");
1513
1514 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1515 CharType->isUnsignedIntegerType());
1516 if (Index < S->getLength())
1517 Value = S->getCodeUnit(Index);
1518 return Value;
1519 }
1520
1521 /// Extract the designated sub-object of an rvalue.
ExtractSubobject(EvalInfo & Info,const Expr * E,APValue & Obj,QualType ObjType,const SubobjectDesignator & Sub,QualType SubType)1522 static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1523 APValue &Obj, QualType ObjType,
1524 const SubobjectDesignator &Sub, QualType SubType) {
1525 if (Sub.Invalid)
1526 // A diagnostic will have already been produced.
1527 return false;
1528 if (Sub.isOnePastTheEnd()) {
1529 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1530 (unsigned)diag::note_constexpr_read_past_end :
1531 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1532 return false;
1533 }
1534 if (Sub.Entries.empty())
1535 return true;
1536 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1537 // This object might be initialized later.
1538 return false;
1539
1540 APValue *O = &Obj;
1541 // Walk the designator's path to find the subobject.
1542 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1543 if (ObjType->isArrayType()) {
1544 // Next subobject is an array element.
1545 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1546 assert(CAT && "vla in literal type?");
1547 uint64_t Index = Sub.Entries[I].ArrayIndex;
1548 if (CAT->getSize().ule(Index)) {
1549 // Note, it should not be possible to form a pointer with a valid
1550 // designator which points more than one past the end of the array.
1551 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1552 (unsigned)diag::note_constexpr_read_past_end :
1553 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1554 return false;
1555 }
1556 // An array object is represented as either an Array APValue or as an
1557 // LValue which refers to a string literal.
1558 if (O->isLValue()) {
1559 assert(I == N - 1 && "extracting subobject of character?");
1560 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1561 Obj = APValue(ExtractStringLiteralCharacter(
1562 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
1563 return true;
1564 } else if (O->getArrayInitializedElts() > Index)
1565 O = &O->getArrayInitializedElt(Index);
1566 else
1567 O = &O->getArrayFiller();
1568 ObjType = CAT->getElementType();
1569 } else if (ObjType->isAnyComplexType()) {
1570 // Next subobject is a complex number.
1571 uint64_t Index = Sub.Entries[I].ArrayIndex;
1572 if (Index > 1) {
1573 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1574 (unsigned)diag::note_constexpr_read_past_end :
1575 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1576 return false;
1577 }
1578 assert(I == N - 1 && "extracting subobject of scalar?");
1579 if (O->isComplexInt()) {
1580 Obj = APValue(Index ? O->getComplexIntImag()
1581 : O->getComplexIntReal());
1582 } else {
1583 assert(O->isComplexFloat());
1584 Obj = APValue(Index ? O->getComplexFloatImag()
1585 : O->getComplexFloatReal());
1586 }
1587 return true;
1588 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1589 if (Field->isMutable()) {
1590 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
1591 << Field;
1592 Info.Note(Field->getLocation(), diag::note_declared_at);
1593 return false;
1594 }
1595
1596 // Next subobject is a class, struct or union field.
1597 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1598 if (RD->isUnion()) {
1599 const FieldDecl *UnionField = O->getUnionField();
1600 if (!UnionField ||
1601 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1602 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
1603 << Field << !UnionField << UnionField;
1604 return false;
1605 }
1606 O = &O->getUnionValue();
1607 } else
1608 O = &O->getStructField(Field->getFieldIndex());
1609 ObjType = Field->getType();
1610
1611 if (ObjType.isVolatileQualified()) {
1612 if (Info.getLangOpts().CPlusPlus) {
1613 // FIXME: Include a description of the path to the volatile subobject.
1614 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
1615 << 2 << Field;
1616 Info.Note(Field->getLocation(), diag::note_declared_at);
1617 } else {
1618 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1619 }
1620 return false;
1621 }
1622 } else {
1623 // Next subobject is a base class.
1624 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1625 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1626 O = &O->getStructBase(getBaseIndex(Derived, Base));
1627 ObjType = Info.Ctx.getRecordType(Base);
1628 }
1629
1630 if (O->isUninit()) {
1631 if (!Info.CheckingPotentialConstantExpression)
1632 Info.Diag(E, diag::note_constexpr_read_uninit);
1633 return false;
1634 }
1635 }
1636
1637 // This may look super-stupid, but it serves an important purpose: if we just
1638 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1639 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1640 // object, which is destroyed by Tmp's destructor.
1641 APValue Tmp;
1642 O->swap(Tmp);
1643 Obj.swap(Tmp);
1644 return true;
1645 }
1646
1647 /// Find the position where two subobject designators diverge, or equivalently
1648 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)1649 static unsigned FindDesignatorMismatch(QualType ObjType,
1650 const SubobjectDesignator &A,
1651 const SubobjectDesignator &B,
1652 bool &WasArrayIndex) {
1653 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1654 for (/**/; I != N; ++I) {
1655 if (!ObjType.isNull() &&
1656 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
1657 // Next subobject is an array element.
1658 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1659 WasArrayIndex = true;
1660 return I;
1661 }
1662 if (ObjType->isAnyComplexType())
1663 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1664 else
1665 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1666 } else {
1667 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1668 WasArrayIndex = false;
1669 return I;
1670 }
1671 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1672 // Next subobject is a field.
1673 ObjType = FD->getType();
1674 else
1675 // Next subobject is a base class.
1676 ObjType = QualType();
1677 }
1678 }
1679 WasArrayIndex = false;
1680 return I;
1681 }
1682
1683 /// Determine whether the given subobject designators refer to elements of the
1684 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)1685 static bool AreElementsOfSameArray(QualType ObjType,
1686 const SubobjectDesignator &A,
1687 const SubobjectDesignator &B) {
1688 if (A.Entries.size() != B.Entries.size())
1689 return false;
1690
1691 bool IsArray = A.MostDerivedArraySize != 0;
1692 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1693 // A is a subobject of the array element.
1694 return false;
1695
1696 // If A (and B) designates an array element, the last entry will be the array
1697 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1698 // of length 1' case, and the entire path must match.
1699 bool WasArrayIndex;
1700 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1701 return CommonLength >= A.Entries.size() - IsArray;
1702 }
1703
1704 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1705 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1706 /// for looking up the glvalue referred to by an entity of reference type.
1707 ///
1708 /// \param Info - Information about the ongoing evaluation.
1709 /// \param Conv - The expression for which we are performing the conversion.
1710 /// Used for diagnostics.
1711 /// \param Type - The type we expect this conversion to produce, before
1712 /// stripping cv-qualifiers in the case of a non-clas type.
1713 /// \param LVal - The glvalue on which we are attempting to perform this action.
1714 /// \param RVal - The produced value will be placed here.
HandleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal)1715 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1716 QualType Type,
1717 const LValue &LVal, APValue &RVal) {
1718 if (LVal.Designator.Invalid)
1719 // A diagnostic will have already been produced.
1720 return false;
1721
1722 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1723
1724 if (!LVal.Base) {
1725 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1726 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1727 return false;
1728 }
1729
1730 CallStackFrame *Frame = 0;
1731 if (LVal.CallIndex) {
1732 Frame = Info.getCallFrame(LVal.CallIndex);
1733 if (!Frame) {
1734 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1735 NoteLValueLocation(Info, LVal.Base);
1736 return false;
1737 }
1738 }
1739
1740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1741 // is not a constant expression (even if the object is non-volatile). We also
1742 // apply this rule to C++98, in order to conform to the expected 'volatile'
1743 // semantics.
1744 if (Type.isVolatileQualified()) {
1745 if (Info.getLangOpts().CPlusPlus)
1746 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
1747 else
1748 Info.Diag(Conv);
1749 return false;
1750 }
1751
1752 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1753 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1754 // In C++11, constexpr, non-volatile variables initialized with constant
1755 // expressions are constant expressions too. Inside constexpr functions,
1756 // parameters are constant expressions even if they're non-const.
1757 // In C, such things can also be folded, although they are not ICEs.
1758 const VarDecl *VD = dyn_cast<VarDecl>(D);
1759 if (VD) {
1760 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1761 VD = VDef;
1762 }
1763 if (!VD || VD->isInvalidDecl()) {
1764 Info.Diag(Conv);
1765 return false;
1766 }
1767
1768 // DR1313: If the object is volatile-qualified but the glvalue was not,
1769 // behavior is undefined so the result is not a constant expression.
1770 QualType VT = VD->getType();
1771 if (VT.isVolatileQualified()) {
1772 if (Info.getLangOpts().CPlusPlus) {
1773 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1774 Info.Note(VD->getLocation(), diag::note_declared_at);
1775 } else {
1776 Info.Diag(Conv);
1777 }
1778 return false;
1779 }
1780
1781 if (!isa<ParmVarDecl>(VD)) {
1782 if (VD->isConstexpr()) {
1783 // OK, we can read this variable.
1784 } else if (VT->isIntegralOrEnumerationType()) {
1785 if (!VT.isConstQualified()) {
1786 if (Info.getLangOpts().CPlusPlus) {
1787 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1788 Info.Note(VD->getLocation(), diag::note_declared_at);
1789 } else {
1790 Info.Diag(Conv);
1791 }
1792 return false;
1793 }
1794 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1795 // We support folding of const floating-point types, in order to make
1796 // static const data members of such types (supported as an extension)
1797 // more useful.
1798 if (Info.getLangOpts().CPlusPlus0x) {
1799 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
1802 Info.CCEDiag(Conv);
1803 }
1804 } else {
1805 // FIXME: Allow folding of values of any literal type in all languages.
1806 if (Info.getLangOpts().CPlusPlus0x) {
1807 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1808 Info.Note(VD->getLocation(), diag::note_declared_at);
1809 } else {
1810 Info.Diag(Conv);
1811 }
1812 return false;
1813 }
1814 }
1815
1816 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1817 return false;
1818
1819 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1820 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1821
1822 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1823 // conversion. This happens when the declaration and the lvalue should be
1824 // considered synonymous, for instance when initializing an array of char
1825 // from a string literal. Continue as if the initializer lvalue was the
1826 // value we were originally given.
1827 assert(RVal.getLValueOffset().isZero() &&
1828 "offset for lvalue init of non-reference");
1829 Base = RVal.getLValueBase().get<const Expr*>();
1830
1831 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1832 Frame = Info.getCallFrame(CallIndex);
1833 if (!Frame) {
1834 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1835 NoteLValueLocation(Info, RVal.getLValueBase());
1836 return false;
1837 }
1838 } else {
1839 Frame = 0;
1840 }
1841 }
1842
1843 // Volatile temporary objects cannot be read in constant expressions.
1844 if (Base->getType().isVolatileQualified()) {
1845 if (Info.getLangOpts().CPlusPlus) {
1846 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1847 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1848 } else {
1849 Info.Diag(Conv);
1850 }
1851 return false;
1852 }
1853
1854 if (Frame) {
1855 // If this is a temporary expression with a nontrivial initializer, grab the
1856 // value from the relevant stack frame.
1857 RVal = Frame->Temporaries[Base];
1858 } else if (const CompoundLiteralExpr *CLE
1859 = dyn_cast<CompoundLiteralExpr>(Base)) {
1860 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1861 // initializer until now for such expressions. Such an expression can't be
1862 // an ICE in C, so this only matters for fold.
1863 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1864 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1865 return false;
1866 } else if (isa<StringLiteral>(Base)) {
1867 // We represent a string literal array as an lvalue pointing at the
1868 // corresponding expression, rather than building an array of chars.
1869 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1870 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
1871 } else {
1872 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1873 return false;
1874 }
1875
1876 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1877 Type);
1878 }
1879
1880 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)1881 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1882 LValue &This) {
1883 if (Object->getType()->isPointerType())
1884 return EvaluatePointer(Object, This, Info);
1885
1886 if (Object->isGLValue())
1887 return EvaluateLValue(Object, This, Info);
1888
1889 if (Object->getType()->isLiteralType())
1890 return EvaluateTemporary(Object, This, Info);
1891
1892 return false;
1893 }
1894
1895 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
1896 /// lvalue referring to the result.
1897 ///
1898 /// \param Info - Information about the ongoing evaluation.
1899 /// \param BO - The member pointer access operation.
1900 /// \param LV - Filled in with a reference to the resulting object.
1901 /// \param IncludeMember - Specifies whether the member itself is included in
1902 /// the resulting LValue subobject designator. This is not possible when
1903 /// creating a bound member function.
1904 /// \return The field or method declaration to which the member pointer refers,
1905 /// or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)1906 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1907 const BinaryOperator *BO,
1908 LValue &LV,
1909 bool IncludeMember = true) {
1910 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1911
1912 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1913 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1914 return 0;
1915
1916 MemberPtr MemPtr;
1917 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1918 return 0;
1919
1920 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1921 // member value, the behavior is undefined.
1922 if (!MemPtr.getDecl())
1923 return 0;
1924
1925 if (!EvalObjOK)
1926 return 0;
1927
1928 if (MemPtr.isDerivedMember()) {
1929 // This is a member of some derived class. Truncate LV appropriately.
1930 // The end of the derived-to-base path for the base object must match the
1931 // derived-to-base path for the member pointer.
1932 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1933 LV.Designator.Entries.size())
1934 return 0;
1935 unsigned PathLengthToMember =
1936 LV.Designator.Entries.size() - MemPtr.Path.size();
1937 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1938 const CXXRecordDecl *LVDecl = getAsBaseClass(
1939 LV.Designator.Entries[PathLengthToMember + I]);
1940 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1941 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1942 return 0;
1943 }
1944
1945 // Truncate the lvalue to the appropriate derived class.
1946 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1947 PathLengthToMember))
1948 return 0;
1949 } else if (!MemPtr.Path.empty()) {
1950 // Extend the LValue path with the member pointer's path.
1951 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1952 MemPtr.Path.size() + IncludeMember);
1953
1954 // Walk down to the appropriate base class.
1955 QualType LVType = BO->getLHS()->getType();
1956 if (const PointerType *PT = LVType->getAs<PointerType>())
1957 LVType = PT->getPointeeType();
1958 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1959 assert(RD && "member pointer access on non-class-type expression");
1960 // The first class in the path is that of the lvalue.
1961 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1962 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1963 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1964 return 0;
1965 RD = Base;
1966 }
1967 // Finally cast to the class containing the member.
1968 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1969 return 0;
1970 }
1971
1972 // Add the member. Note that we cannot build bound member functions here.
1973 if (IncludeMember) {
1974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1975 if (!HandleLValueMember(Info, BO, LV, FD))
1976 return 0;
1977 } else if (const IndirectFieldDecl *IFD =
1978 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1979 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1980 return 0;
1981 } else {
1982 llvm_unreachable("can't construct reference to bound member function");
1983 }
1984 }
1985
1986 return MemPtr.getDecl();
1987 }
1988
1989 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1990 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)1991 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1992 LValue &Result) {
1993 SubobjectDesignator &D = Result.Designator;
1994 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1995 return false;
1996
1997 QualType TargetQT = E->getType();
1998 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1999 TargetQT = PT->getPointeeType();
2000
2001 // Check this cast lands within the final derived-to-base subobject path.
2002 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2003 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2004 << D.MostDerivedType << TargetQT;
2005 return false;
2006 }
2007
2008 // Check the type of the final cast. We don't need to check the path,
2009 // since a cast can only be formed if the path is unique.
2010 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
2011 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2012 const CXXRecordDecl *FinalType;
2013 if (NewEntriesSize == D.MostDerivedPathLength)
2014 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2015 else
2016 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
2017 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2018 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2019 << D.MostDerivedType << TargetQT;
2020 return false;
2021 }
2022
2023 // Truncate the lvalue to the appropriate derived class.
2024 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
2025 }
2026
2027 namespace {
2028 enum EvalStmtResult {
2029 /// Evaluation failed.
2030 ESR_Failed,
2031 /// Hit a 'return' statement.
2032 ESR_Returned,
2033 /// Evaluation succeeded.
2034 ESR_Succeeded
2035 };
2036 }
2037
2038 // Evaluate a statement.
EvaluateStmt(APValue & Result,EvalInfo & Info,const Stmt * S)2039 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2040 const Stmt *S) {
2041 switch (S->getStmtClass()) {
2042 default:
2043 return ESR_Failed;
2044
2045 case Stmt::NullStmtClass:
2046 case Stmt::DeclStmtClass:
2047 return ESR_Succeeded;
2048
2049 case Stmt::ReturnStmtClass: {
2050 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
2051 if (!Evaluate(Result, Info, RetExpr))
2052 return ESR_Failed;
2053 return ESR_Returned;
2054 }
2055
2056 case Stmt::CompoundStmtClass: {
2057 const CompoundStmt *CS = cast<CompoundStmt>(S);
2058 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2059 BE = CS->body_end(); BI != BE; ++BI) {
2060 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2061 if (ESR != ESR_Succeeded)
2062 return ESR;
2063 }
2064 return ESR_Succeeded;
2065 }
2066 }
2067 }
2068
2069 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2070 /// default constructor. If so, we'll fold it whether or not it's marked as
2071 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
2072 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)2073 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
2074 const CXXConstructorDecl *CD,
2075 bool IsValueInitialization) {
2076 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2077 return false;
2078
2079 // Value-initialization does not call a trivial default constructor, so such a
2080 // call is a core constant expression whether or not the constructor is
2081 // constexpr.
2082 if (!CD->isConstexpr() && !IsValueInitialization) {
2083 if (Info.getLangOpts().CPlusPlus0x) {
2084 // FIXME: If DiagDecl is an implicitly-declared special member function,
2085 // we should be much more explicit about why it's not constexpr.
2086 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2087 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2088 Info.Note(CD->getLocation(), diag::note_declared_at);
2089 } else {
2090 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2091 }
2092 }
2093 return true;
2094 }
2095
2096 /// CheckConstexprFunction - Check that a function can be called in a constant
2097 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition)2098 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2099 const FunctionDecl *Declaration,
2100 const FunctionDecl *Definition) {
2101 // Potential constant expressions can contain calls to declared, but not yet
2102 // defined, constexpr functions.
2103 if (Info.CheckingPotentialConstantExpression && !Definition &&
2104 Declaration->isConstexpr())
2105 return false;
2106
2107 // Can we evaluate this function call?
2108 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2109 return true;
2110
2111 if (Info.getLangOpts().CPlusPlus0x) {
2112 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
2113 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2114 // should be much more explicit about why it's not constexpr.
2115 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2116 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2117 << DiagDecl;
2118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2119 } else {
2120 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2121 }
2122 return false;
2123 }
2124
2125 namespace {
2126 typedef SmallVector<APValue, 8> ArgVector;
2127 }
2128
2129 /// EvaluateArgs - Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,ArgVector & ArgValues,EvalInfo & Info)2130 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2131 EvalInfo &Info) {
2132 bool Success = true;
2133 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
2134 I != E; ++I) {
2135 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2136 // If we're checking for a potential constant expression, evaluate all
2137 // initializers even if some of them fail.
2138 if (!Info.keepEvaluatingAfterFailure())
2139 return false;
2140 Success = false;
2141 }
2142 }
2143 return Success;
2144 }
2145
2146 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,ArrayRef<const Expr * > Args,const Stmt * Body,EvalInfo & Info,APValue & Result)2147 static bool HandleFunctionCall(SourceLocation CallLoc,
2148 const FunctionDecl *Callee, const LValue *This,
2149 ArrayRef<const Expr*> Args, const Stmt *Body,
2150 EvalInfo &Info, APValue &Result) {
2151 ArgVector ArgValues(Args.size());
2152 if (!EvaluateArgs(Args, ArgValues, Info))
2153 return false;
2154
2155 if (!Info.CheckCallLimit(CallLoc))
2156 return false;
2157
2158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2159 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2160 }
2161
2162 /// Evaluate a constructor call.
HandleConstructorCall(SourceLocation CallLoc,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)2163 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2164 ArrayRef<const Expr*> Args,
2165 const CXXConstructorDecl *Definition,
2166 EvalInfo &Info, APValue &Result) {
2167 ArgVector ArgValues(Args.size());
2168 if (!EvaluateArgs(Args, ArgValues, Info))
2169 return false;
2170
2171 if (!Info.CheckCallLimit(CallLoc))
2172 return false;
2173
2174 const CXXRecordDecl *RD = Definition->getParent();
2175 if (RD->getNumVBases()) {
2176 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2177 return false;
2178 }
2179
2180 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2181
2182 // If it's a delegating constructor, just delegate.
2183 if (Definition->isDelegatingConstructor()) {
2184 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2185 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
2186 }
2187
2188 // For a trivial copy or move constructor, perform an APValue copy. This is
2189 // essential for unions, where the operations performed by the constructor
2190 // cannot be represented by ctor-initializers.
2191 if (Definition->isDefaulted() &&
2192 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2193 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
2194 LValue RHS;
2195 RHS.setFrom(Info.Ctx, ArgValues[0]);
2196 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2197 RHS, Result);
2198 }
2199
2200 // Reserve space for the struct members.
2201 if (!RD->isUnion() && Result.isUninit())
2202 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2203 std::distance(RD->field_begin(), RD->field_end()));
2204
2205 if (RD->isInvalidDecl()) return false;
2206 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2207
2208 bool Success = true;
2209 unsigned BasesSeen = 0;
2210 #ifndef NDEBUG
2211 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2212 #endif
2213 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2214 E = Definition->init_end(); I != E; ++I) {
2215 LValue Subobject = This;
2216 APValue *Value = &Result;
2217
2218 // Determine the subobject to initialize.
2219 if ((*I)->isBaseInitializer()) {
2220 QualType BaseType((*I)->getBaseClass(), 0);
2221 #ifndef NDEBUG
2222 // Non-virtual base classes are initialized in the order in the class
2223 // definition. We have already checked for virtual base classes.
2224 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2225 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2226 "base class initializers not in expected order");
2227 ++BaseIt;
2228 #endif
2229 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2230 BaseType->getAsCXXRecordDecl(), &Layout))
2231 return false;
2232 Value = &Result.getStructBase(BasesSeen++);
2233 } else if (FieldDecl *FD = (*I)->getMember()) {
2234 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2235 return false;
2236 if (RD->isUnion()) {
2237 Result = APValue(FD);
2238 Value = &Result.getUnionValue();
2239 } else {
2240 Value = &Result.getStructField(FD->getFieldIndex());
2241 }
2242 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2243 // Walk the indirect field decl's chain to find the object to initialize,
2244 // and make sure we've initialized every step along it.
2245 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2246 CE = IFD->chain_end();
2247 C != CE; ++C) {
2248 FieldDecl *FD = cast<FieldDecl>(*C);
2249 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2250 // Switch the union field if it differs. This happens if we had
2251 // preceding zero-initialization, and we're now initializing a union
2252 // subobject other than the first.
2253 // FIXME: In this case, the values of the other subobjects are
2254 // specified, since zero-initialization sets all padding bits to zero.
2255 if (Value->isUninit() ||
2256 (Value->isUnion() && Value->getUnionField() != FD)) {
2257 if (CD->isUnion())
2258 *Value = APValue(FD);
2259 else
2260 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2261 std::distance(CD->field_begin(), CD->field_end()));
2262 }
2263 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2264 return false;
2265 if (CD->isUnion())
2266 Value = &Value->getUnionValue();
2267 else
2268 Value = &Value->getStructField(FD->getFieldIndex());
2269 }
2270 } else {
2271 llvm_unreachable("unknown base initializer kind");
2272 }
2273
2274 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2275 (*I)->isBaseInitializer()
2276 ? CCEK_Constant : CCEK_MemberInit)) {
2277 // If we're checking for a potential constant expression, evaluate all
2278 // initializers even if some of them fail.
2279 if (!Info.keepEvaluatingAfterFailure())
2280 return false;
2281 Success = false;
2282 }
2283 }
2284
2285 return Success;
2286 }
2287
2288 //===----------------------------------------------------------------------===//
2289 // Generic Evaluation
2290 //===----------------------------------------------------------------------===//
2291 namespace {
2292
2293 // FIXME: RetTy is always bool. Remove it.
2294 template <class Derived, typename RetTy=bool>
2295 class ExprEvaluatorBase
2296 : public ConstStmtVisitor<Derived, RetTy> {
2297 private:
DerivedSuccess(const APValue & V,const Expr * E)2298 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
2299 return static_cast<Derived*>(this)->Success(V, E);
2300 }
DerivedZeroInitialization(const Expr * E)2301 RetTy DerivedZeroInitialization(const Expr *E) {
2302 return static_cast<Derived*>(this)->ZeroInitialization(E);
2303 }
2304
2305 // Check whether a conditional operator with a non-constant condition is a
2306 // potential constant expression. If neither arm is a potential constant
2307 // expression, then the conditional operator is not either.
2308 template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)2309 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2310 assert(Info.CheckingPotentialConstantExpression);
2311
2312 // Speculatively evaluate both arms.
2313 {
2314 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2315 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2316
2317 StmtVisitorTy::Visit(E->getFalseExpr());
2318 if (Diag.empty())
2319 return;
2320
2321 Diag.clear();
2322 StmtVisitorTy::Visit(E->getTrueExpr());
2323 if (Diag.empty())
2324 return;
2325 }
2326
2327 Error(E, diag::note_constexpr_conditional_never_const);
2328 }
2329
2330
2331 template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)2332 bool HandleConditionalOperator(const ConditionalOperator *E) {
2333 bool BoolResult;
2334 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2335 if (Info.CheckingPotentialConstantExpression)
2336 CheckPotentialConstantConditional(E);
2337 return false;
2338 }
2339
2340 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2341 return StmtVisitorTy::Visit(EvalExpr);
2342 }
2343
2344 protected:
2345 EvalInfo &Info;
2346 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2347 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2348
CCEDiag(const Expr * E,diag::kind D)2349 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2350 return Info.CCEDiag(E, D);
2351 }
2352
ZeroInitialization(const Expr * E)2353 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2354
2355 public:
ExprEvaluatorBase(EvalInfo & Info)2356 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2357
getEvalInfo()2358 EvalInfo &getEvalInfo() { return Info; }
2359
2360 /// Report an evaluation error. This should only be called when an error is
2361 /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)2362 bool Error(const Expr *E, diag::kind D) {
2363 Info.Diag(E, D);
2364 return false;
2365 }
Error(const Expr * E)2366 bool Error(const Expr *E) {
2367 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2368 }
2369
VisitStmt(const Stmt *)2370 RetTy VisitStmt(const Stmt *) {
2371 llvm_unreachable("Expression evaluator should not be called on stmts");
2372 }
VisitExpr(const Expr * E)2373 RetTy VisitExpr(const Expr *E) {
2374 return Error(E);
2375 }
2376
VisitParenExpr(const ParenExpr * E)2377 RetTy VisitParenExpr(const ParenExpr *E)
2378 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)2379 RetTy VisitUnaryExtension(const UnaryOperator *E)
2380 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)2381 RetTy VisitUnaryPlus(const UnaryOperator *E)
2382 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)2383 RetTy VisitChooseExpr(const ChooseExpr *E)
2384 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)2385 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2386 { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)2387 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2388 { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)2389 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2390 { return StmtVisitorTy::Visit(E->getExpr()); }
2391 // We cannot create any objects for which cleanups are required, so there is
2392 // nothing to do here; all cleanups must come from unevaluated subexpressions.
VisitExprWithCleanups(const ExprWithCleanups * E)2393 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2394 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2395
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)2396 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2397 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2398 return static_cast<Derived*>(this)->VisitCastExpr(E);
2399 }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)2400 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2402 return static_cast<Derived*>(this)->VisitCastExpr(E);
2403 }
2404
VisitBinaryOperator(const BinaryOperator * E)2405 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2406 switch (E->getOpcode()) {
2407 default:
2408 return Error(E);
2409
2410 case BO_Comma:
2411 VisitIgnoredValue(E->getLHS());
2412 return StmtVisitorTy::Visit(E->getRHS());
2413
2414 case BO_PtrMemD:
2415 case BO_PtrMemI: {
2416 LValue Obj;
2417 if (!HandleMemberPointerAccess(Info, E, Obj))
2418 return false;
2419 APValue Result;
2420 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2421 return false;
2422 return DerivedSuccess(Result, E);
2423 }
2424 }
2425 }
2426
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)2427 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2428 // Evaluate and cache the common expression. We treat it as a temporary,
2429 // even though it's not quite the same thing.
2430 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2431 Info, E->getCommon()))
2432 return false;
2433
2434 return HandleConditionalOperator(E);
2435 }
2436
VisitConditionalOperator(const ConditionalOperator * E)2437 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2438 bool IsBcpCall = false;
2439 // If the condition (ignoring parens) is a __builtin_constant_p call,
2440 // the result is a constant expression if it can be folded without
2441 // side-effects. This is an important GNU extension. See GCC PR38377
2442 // for discussion.
2443 if (const CallExpr *CallCE =
2444 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2445 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2446 IsBcpCall = true;
2447
2448 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2449 // constant expression; we can't check whether it's potentially foldable.
2450 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2451 return false;
2452
2453 FoldConstant Fold(Info);
2454
2455 if (!HandleConditionalOperator(E))
2456 return false;
2457
2458 if (IsBcpCall)
2459 Fold.Fold(Info);
2460
2461 return true;
2462 }
2463
VisitOpaqueValueExpr(const OpaqueValueExpr * E)2464 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2465 APValue &Value = Info.CurrentCall->Temporaries[E];
2466 if (Value.isUninit()) {
2467 const Expr *Source = E->getSourceExpr();
2468 if (!Source)
2469 return Error(E);
2470 if (Source == E) { // sanity checking.
2471 assert(0 && "OpaqueValueExpr recursively refers to itself");
2472 return Error(E);
2473 }
2474 return StmtVisitorTy::Visit(Source);
2475 }
2476 return DerivedSuccess(Value, E);
2477 }
2478
VisitCallExpr(const CallExpr * E)2479 RetTy VisitCallExpr(const CallExpr *E) {
2480 const Expr *Callee = E->getCallee()->IgnoreParens();
2481 QualType CalleeType = Callee->getType();
2482
2483 const FunctionDecl *FD = 0;
2484 LValue *This = 0, ThisVal;
2485 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2486 bool HasQualifier = false;
2487
2488 // Extract function decl and 'this' pointer from the callee.
2489 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2490 const ValueDecl *Member = 0;
2491 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2492 // Explicit bound member calls, such as x.f() or p->g();
2493 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2494 return false;
2495 Member = ME->getMemberDecl();
2496 This = &ThisVal;
2497 HasQualifier = ME->hasQualifier();
2498 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2499 // Indirect bound member calls ('.*' or '->*').
2500 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2501 if (!Member) return false;
2502 This = &ThisVal;
2503 } else
2504 return Error(Callee);
2505
2506 FD = dyn_cast<FunctionDecl>(Member);
2507 if (!FD)
2508 return Error(Callee);
2509 } else if (CalleeType->isFunctionPointerType()) {
2510 LValue Call;
2511 if (!EvaluatePointer(Callee, Call, Info))
2512 return false;
2513
2514 if (!Call.getLValueOffset().isZero())
2515 return Error(Callee);
2516 FD = dyn_cast_or_null<FunctionDecl>(
2517 Call.getLValueBase().dyn_cast<const ValueDecl*>());
2518 if (!FD)
2519 return Error(Callee);
2520
2521 // Overloaded operator calls to member functions are represented as normal
2522 // calls with '*this' as the first argument.
2523 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2524 if (MD && !MD->isStatic()) {
2525 // FIXME: When selecting an implicit conversion for an overloaded
2526 // operator delete, we sometimes try to evaluate calls to conversion
2527 // operators without a 'this' parameter!
2528 if (Args.empty())
2529 return Error(E);
2530
2531 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2532 return false;
2533 This = &ThisVal;
2534 Args = Args.slice(1);
2535 }
2536
2537 // Don't call function pointers which have been cast to some other type.
2538 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2539 return Error(E);
2540 } else
2541 return Error(E);
2542
2543 if (This && !This->checkSubobject(Info, E, CSK_This))
2544 return false;
2545
2546 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2547 // calls to such functions in constant expressions.
2548 if (This && !HasQualifier &&
2549 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2550 return Error(E, diag::note_constexpr_virtual_call);
2551
2552 const FunctionDecl *Definition = 0;
2553 Stmt *Body = FD->getBody(Definition);
2554 APValue Result;
2555
2556 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2557 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2558 Info, Result))
2559 return false;
2560
2561 return DerivedSuccess(Result, E);
2562 }
2563
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)2564 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2565 return StmtVisitorTy::Visit(E->getInitializer());
2566 }
VisitInitListExpr(const InitListExpr * E)2567 RetTy VisitInitListExpr(const InitListExpr *E) {
2568 if (E->getNumInits() == 0)
2569 return DerivedZeroInitialization(E);
2570 if (E->getNumInits() == 1)
2571 return StmtVisitorTy::Visit(E->getInit(0));
2572 return Error(E);
2573 }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)2574 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2575 return DerivedZeroInitialization(E);
2576 }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)2577 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2578 return DerivedZeroInitialization(E);
2579 }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)2580 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2581 return DerivedZeroInitialization(E);
2582 }
2583
2584 /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)2585 RetTy VisitMemberExpr(const MemberExpr *E) {
2586 assert(!E->isArrow() && "missing call to bound member function?");
2587
2588 APValue Val;
2589 if (!Evaluate(Val, Info, E->getBase()))
2590 return false;
2591
2592 QualType BaseTy = E->getBase()->getType();
2593
2594 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2595 if (!FD) return Error(E);
2596 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2597 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2598 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2599
2600 SubobjectDesignator Designator(BaseTy);
2601 Designator.addDeclUnchecked(FD);
2602
2603 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2604 DerivedSuccess(Val, E);
2605 }
2606
VisitCastExpr(const CastExpr * E)2607 RetTy VisitCastExpr(const CastExpr *E) {
2608 switch (E->getCastKind()) {
2609 default:
2610 break;
2611
2612 case CK_AtomicToNonAtomic:
2613 case CK_NonAtomicToAtomic:
2614 case CK_NoOp:
2615 case CK_UserDefinedConversion:
2616 return StmtVisitorTy::Visit(E->getSubExpr());
2617
2618 case CK_LValueToRValue: {
2619 LValue LVal;
2620 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2621 return false;
2622 APValue RVal;
2623 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2624 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2625 LVal, RVal))
2626 return false;
2627 return DerivedSuccess(RVal, E);
2628 }
2629 }
2630
2631 return Error(E);
2632 }
2633
2634 /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)2635 void VisitIgnoredValue(const Expr *E) {
2636 APValue Scratch;
2637 if (!Evaluate(Scratch, Info, E))
2638 Info.EvalStatus.HasSideEffects = true;
2639 }
2640 };
2641
2642 }
2643
2644 //===----------------------------------------------------------------------===//
2645 // Common base class for lvalue and temporary evaluation.
2646 //===----------------------------------------------------------------------===//
2647 namespace {
2648 template<class Derived>
2649 class LValueExprEvaluatorBase
2650 : public ExprEvaluatorBase<Derived, bool> {
2651 protected:
2652 LValue &Result;
2653 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2654 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2655
Success(APValue::LValueBase B)2656 bool Success(APValue::LValueBase B) {
2657 Result.set(B);
2658 return true;
2659 }
2660
2661 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result)2662 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2663 ExprEvaluatorBaseTy(Info), Result(Result) {}
2664
Success(const APValue & V,const Expr * E)2665 bool Success(const APValue &V, const Expr *E) {
2666 Result.setFrom(this->Info.Ctx, V);
2667 return true;
2668 }
2669
VisitMemberExpr(const MemberExpr * E)2670 bool VisitMemberExpr(const MemberExpr *E) {
2671 // Handle non-static data members.
2672 QualType BaseTy;
2673 if (E->isArrow()) {
2674 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2675 return false;
2676 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
2677 } else if (E->getBase()->isRValue()) {
2678 assert(E->getBase()->getType()->isRecordType());
2679 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2680 return false;
2681 BaseTy = E->getBase()->getType();
2682 } else {
2683 if (!this->Visit(E->getBase()))
2684 return false;
2685 BaseTy = E->getBase()->getType();
2686 }
2687
2688 const ValueDecl *MD = E->getMemberDecl();
2689 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2690 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2691 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2692 (void)BaseTy;
2693 if (!HandleLValueMember(this->Info, E, Result, FD))
2694 return false;
2695 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2696 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2697 return false;
2698 } else
2699 return this->Error(E);
2700
2701 if (MD->getType()->isReferenceType()) {
2702 APValue RefValue;
2703 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2704 RefValue))
2705 return false;
2706 return Success(RefValue, E);
2707 }
2708 return true;
2709 }
2710
VisitBinaryOperator(const BinaryOperator * E)2711 bool VisitBinaryOperator(const BinaryOperator *E) {
2712 switch (E->getOpcode()) {
2713 default:
2714 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2715
2716 case BO_PtrMemD:
2717 case BO_PtrMemI:
2718 return HandleMemberPointerAccess(this->Info, E, Result);
2719 }
2720 }
2721
VisitCastExpr(const CastExpr * E)2722 bool VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2724 default:
2725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2726
2727 case CK_DerivedToBase:
2728 case CK_UncheckedDerivedToBase: {
2729 if (!this->Visit(E->getSubExpr()))
2730 return false;
2731
2732 // Now figure out the necessary offset to add to the base LV to get from
2733 // the derived class to the base class.
2734 QualType Type = E->getSubExpr()->getType();
2735
2736 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2737 PathE = E->path_end(); PathI != PathE; ++PathI) {
2738 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2739 *PathI))
2740 return false;
2741 Type = (*PathI)->getType();
2742 }
2743
2744 return true;
2745 }
2746 }
2747 }
2748 };
2749 }
2750
2751 //===----------------------------------------------------------------------===//
2752 // LValue Evaluation
2753 //
2754 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2755 // function designators (in C), decl references to void objects (in C), and
2756 // temporaries (if building with -Wno-address-of-temporary).
2757 //
2758 // LValue evaluation produces values comprising a base expression of one of the
2759 // following types:
2760 // - Declarations
2761 // * VarDecl
2762 // * FunctionDecl
2763 // - Literals
2764 // * CompoundLiteralExpr in C
2765 // * StringLiteral
2766 // * CXXTypeidExpr
2767 // * PredefinedExpr
2768 // * ObjCStringLiteralExpr
2769 // * ObjCEncodeExpr
2770 // * AddrLabelExpr
2771 // * BlockExpr
2772 // * CallExpr for a MakeStringConstant builtin
2773 // - Locals and temporaries
2774 // * Any Expr, with a CallIndex indicating the function in which the temporary
2775 // was evaluated.
2776 // plus an offset in bytes.
2777 //===----------------------------------------------------------------------===//
2778 namespace {
2779 class LValueExprEvaluator
2780 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2781 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result)2782 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2783 LValueExprEvaluatorBaseTy(Info, Result) {}
2784
2785 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2786
2787 bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)2788 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2789 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2790 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2791 bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)2792 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)2793 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2794 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2795 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2796 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2797 bool VisitUnaryDeref(const UnaryOperator *E);
2798 bool VisitUnaryReal(const UnaryOperator *E);
2799 bool VisitUnaryImag(const UnaryOperator *E);
2800
VisitCastExpr(const CastExpr * E)2801 bool VisitCastExpr(const CastExpr *E) {
2802 switch (E->getCastKind()) {
2803 default:
2804 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2805
2806 case CK_LValueBitCast:
2807 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2808 if (!Visit(E->getSubExpr()))
2809 return false;
2810 Result.Designator.setInvalid();
2811 return true;
2812
2813 case CK_BaseToDerived:
2814 if (!Visit(E->getSubExpr()))
2815 return false;
2816 return HandleBaseToDerivedCast(Info, E, Result);
2817 }
2818 }
2819 };
2820 } // end anonymous namespace
2821
2822 /// Evaluate an expression as an lvalue. This can be legitimately called on
2823 /// expressions which are not glvalues, in a few cases:
2824 /// * function designators in C,
2825 /// * "extern void" objects,
2826 /// * temporaries, if building with -Wno-address-of-temporary.
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info)2827 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2828 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2829 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2830 "can't evaluate expression as an lvalue");
2831 return LValueExprEvaluator(Info, Result).Visit(E);
2832 }
2833
VisitDeclRefExpr(const DeclRefExpr * E)2834 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2835 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2836 return Success(FD);
2837 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2838 return VisitVarDecl(E, VD);
2839 return Error(E);
2840 }
2841
VisitVarDecl(const Expr * E,const VarDecl * VD)2842 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2843 if (!VD->getType()->isReferenceType()) {
2844 if (isa<ParmVarDecl>(VD)) {
2845 Result.set(VD, Info.CurrentCall->Index);
2846 return true;
2847 }
2848 return Success(VD);
2849 }
2850
2851 APValue V;
2852 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2853 return false;
2854 return Success(V, E);
2855 }
2856
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)2857 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2858 const MaterializeTemporaryExpr *E) {
2859 if (E->GetTemporaryExpr()->isRValue()) {
2860 if (E->getType()->isRecordType())
2861 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2862
2863 Result.set(E, Info.CurrentCall->Index);
2864 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2865 Result, E->GetTemporaryExpr());
2866 }
2867
2868 // Materialization of an lvalue temporary occurs when we need to force a copy
2869 // (for instance, if it's a bitfield).
2870 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2871 if (!Visit(E->GetTemporaryExpr()))
2872 return false;
2873 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2874 Info.CurrentCall->Temporaries[E]))
2875 return false;
2876 Result.set(E, Info.CurrentCall->Index);
2877 return true;
2878 }
2879
2880 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)2881 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2882 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2883 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2884 // only see this when folding in C, so there's no standard to follow here.
2885 return Success(E);
2886 }
2887
VisitCXXTypeidExpr(const CXXTypeidExpr * E)2888 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2889 if (E->isTypeOperand())
2890 return Success(E);
2891 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2892 // FIXME: The standard says "a typeid expression whose operand is of a
2893 // polymorphic class type" is not a constant expression, but it probably
2894 // means "a typeid expression whose operand is potentially evaluated".
2895 if (RD && RD->isPolymorphic()) {
2896 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2897 << E->getExprOperand()->getType()
2898 << E->getExprOperand()->getSourceRange();
2899 return false;
2900 }
2901 return Success(E);
2902 }
2903
VisitCXXUuidofExpr(const CXXUuidofExpr * E)2904 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2905 return Success(E);
2906 }
2907
VisitMemberExpr(const MemberExpr * E)2908 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2909 // Handle static data members.
2910 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2911 VisitIgnoredValue(E->getBase());
2912 return VisitVarDecl(E, VD);
2913 }
2914
2915 // Handle static member functions.
2916 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2917 if (MD->isStatic()) {
2918 VisitIgnoredValue(E->getBase());
2919 return Success(MD);
2920 }
2921 }
2922
2923 // Handle non-static data members.
2924 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
2925 }
2926
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)2927 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2928 // FIXME: Deal with vectors as array subscript bases.
2929 if (E->getBase()->getType()->isVectorType())
2930 return Error(E);
2931
2932 if (!EvaluatePointer(E->getBase(), Result, Info))
2933 return false;
2934
2935 APSInt Index;
2936 if (!EvaluateInteger(E->getIdx(), Index, Info))
2937 return false;
2938 int64_t IndexValue
2939 = Index.isSigned() ? Index.getSExtValue()
2940 : static_cast<int64_t>(Index.getZExtValue());
2941
2942 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
2943 }
2944
VisitUnaryDeref(const UnaryOperator * E)2945 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
2946 return EvaluatePointer(E->getSubExpr(), Result, Info);
2947 }
2948
VisitUnaryReal(const UnaryOperator * E)2949 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2950 if (!Visit(E->getSubExpr()))
2951 return false;
2952 // __real is a no-op on scalar lvalues.
2953 if (E->getSubExpr()->getType()->isAnyComplexType())
2954 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2955 return true;
2956 }
2957
VisitUnaryImag(const UnaryOperator * E)2958 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2959 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2960 "lvalue __imag__ on scalar?");
2961 if (!Visit(E->getSubExpr()))
2962 return false;
2963 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2964 return true;
2965 }
2966
2967 //===----------------------------------------------------------------------===//
2968 // Pointer Evaluation
2969 //===----------------------------------------------------------------------===//
2970
2971 namespace {
2972 class PointerExprEvaluator
2973 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
2974 LValue &Result;
2975
Success(const Expr * E)2976 bool Success(const Expr *E) {
2977 Result.set(E);
2978 return true;
2979 }
2980 public:
2981
PointerExprEvaluator(EvalInfo & info,LValue & Result)2982 PointerExprEvaluator(EvalInfo &info, LValue &Result)
2983 : ExprEvaluatorBaseTy(info), Result(Result) {}
2984
Success(const APValue & V,const Expr * E)2985 bool Success(const APValue &V, const Expr *E) {
2986 Result.setFrom(Info.Ctx, V);
2987 return true;
2988 }
ZeroInitialization(const Expr * E)2989 bool ZeroInitialization(const Expr *E) {
2990 return Success((Expr*)0);
2991 }
2992
2993 bool VisitBinaryOperator(const BinaryOperator *E);
2994 bool VisitCastExpr(const CastExpr* E);
2995 bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)2996 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
2997 { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)2998 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
2999 { return Success(E); }
VisitAddrLabelExpr(const AddrLabelExpr * E)3000 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
3001 { return Success(E); }
3002 bool VisitCallExpr(const CallExpr *E);
VisitBlockExpr(const BlockExpr * E)3003 bool VisitBlockExpr(const BlockExpr *E) {
3004 if (!E->getBlockDecl()->hasCaptures())
3005 return Success(E);
3006 return Error(E);
3007 }
VisitCXXThisExpr(const CXXThisExpr * E)3008 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3009 if (!Info.CurrentCall->This)
3010 return Error(E);
3011 Result = *Info.CurrentCall->This;
3012 return true;
3013 }
3014
3015 // FIXME: Missing: @protocol, @selector
3016 };
3017 } // end anonymous namespace
3018
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info)3019 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
3020 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
3021 return PointerExprEvaluator(Info, Result).Visit(E);
3022 }
3023
VisitBinaryOperator(const BinaryOperator * E)3024 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3025 if (E->getOpcode() != BO_Add &&
3026 E->getOpcode() != BO_Sub)
3027 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3028
3029 const Expr *PExp = E->getLHS();
3030 const Expr *IExp = E->getRHS();
3031 if (IExp->getType()->isPointerType())
3032 std::swap(PExp, IExp);
3033
3034 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3035 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
3036 return false;
3037
3038 llvm::APSInt Offset;
3039 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
3040 return false;
3041 int64_t AdditionalOffset
3042 = Offset.isSigned() ? Offset.getSExtValue()
3043 : static_cast<int64_t>(Offset.getZExtValue());
3044 if (E->getOpcode() == BO_Sub)
3045 AdditionalOffset = -AdditionalOffset;
3046
3047 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
3048 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3049 AdditionalOffset);
3050 }
3051
VisitUnaryAddrOf(const UnaryOperator * E)3052 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3053 return EvaluateLValue(E->getSubExpr(), Result, Info);
3054 }
3055
VisitCastExpr(const CastExpr * E)3056 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3057 const Expr* SubExpr = E->getSubExpr();
3058
3059 switch (E->getCastKind()) {
3060 default:
3061 break;
3062
3063 case CK_BitCast:
3064 case CK_CPointerToObjCPointerCast:
3065 case CK_BlockPointerToObjCPointerCast:
3066 case CK_AnyPointerToBlockPointerCast:
3067 if (!Visit(SubExpr))
3068 return false;
3069 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3070 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3071 // also static_casts, but we disallow them as a resolution to DR1312.
3072 if (!E->getType()->isVoidPointerType()) {
3073 Result.Designator.setInvalid();
3074 if (SubExpr->getType()->isVoidPointerType())
3075 CCEDiag(E, diag::note_constexpr_invalid_cast)
3076 << 3 << SubExpr->getType();
3077 else
3078 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3079 }
3080 return true;
3081
3082 case CK_DerivedToBase:
3083 case CK_UncheckedDerivedToBase: {
3084 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
3085 return false;
3086 if (!Result.Base && Result.Offset.isZero())
3087 return true;
3088
3089 // Now figure out the necessary offset to add to the base LV to get from
3090 // the derived class to the base class.
3091 QualType Type =
3092 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3093
3094 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3095 PathE = E->path_end(); PathI != PathE; ++PathI) {
3096 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3097 *PathI))
3098 return false;
3099 Type = (*PathI)->getType();
3100 }
3101
3102 return true;
3103 }
3104
3105 case CK_BaseToDerived:
3106 if (!Visit(E->getSubExpr()))
3107 return false;
3108 if (!Result.Base && Result.Offset.isZero())
3109 return true;
3110 return HandleBaseToDerivedCast(Info, E, Result);
3111
3112 case CK_NullToPointer:
3113 VisitIgnoredValue(E->getSubExpr());
3114 return ZeroInitialization(E);
3115
3116 case CK_IntegralToPointer: {
3117 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3118
3119 APValue Value;
3120 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3121 break;
3122
3123 if (Value.isInt()) {
3124 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3125 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3126 Result.Base = (Expr*)0;
3127 Result.Offset = CharUnits::fromQuantity(N);
3128 Result.CallIndex = 0;
3129 Result.Designator.setInvalid();
3130 return true;
3131 } else {
3132 // Cast is of an lvalue, no need to change value.
3133 Result.setFrom(Info.Ctx, Value);
3134 return true;
3135 }
3136 }
3137 case CK_ArrayToPointerDecay:
3138 if (SubExpr->isGLValue()) {
3139 if (!EvaluateLValue(SubExpr, Result, Info))
3140 return false;
3141 } else {
3142 Result.set(SubExpr, Info.CurrentCall->Index);
3143 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3144 Info, Result, SubExpr))
3145 return false;
3146 }
3147 // The result is a pointer to the first element of the array.
3148 if (const ConstantArrayType *CAT
3149 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3150 Result.addArray(Info, E, CAT);
3151 else
3152 Result.Designator.setInvalid();
3153 return true;
3154
3155 case CK_FunctionToPointerDecay:
3156 return EvaluateLValue(SubExpr, Result, Info);
3157 }
3158
3159 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3160 }
3161
VisitCallExpr(const CallExpr * E)3162 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3163 if (IsStringLiteralCall(E))
3164 return Success(E);
3165
3166 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3167 }
3168
3169 //===----------------------------------------------------------------------===//
3170 // Member Pointer Evaluation
3171 //===----------------------------------------------------------------------===//
3172
3173 namespace {
3174 class MemberPointerExprEvaluator
3175 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3176 MemberPtr &Result;
3177
Success(const ValueDecl * D)3178 bool Success(const ValueDecl *D) {
3179 Result = MemberPtr(D);
3180 return true;
3181 }
3182 public:
3183
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)3184 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3185 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3186
Success(const APValue & V,const Expr * E)3187 bool Success(const APValue &V, const Expr *E) {
3188 Result.setFrom(V);
3189 return true;
3190 }
ZeroInitialization(const Expr * E)3191 bool ZeroInitialization(const Expr *E) {
3192 return Success((const ValueDecl*)0);
3193 }
3194
3195 bool VisitCastExpr(const CastExpr *E);
3196 bool VisitUnaryAddrOf(const UnaryOperator *E);
3197 };
3198 } // end anonymous namespace
3199
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)3200 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3201 EvalInfo &Info) {
3202 assert(E->isRValue() && E->getType()->isMemberPointerType());
3203 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3204 }
3205
VisitCastExpr(const CastExpr * E)3206 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3207 switch (E->getCastKind()) {
3208 default:
3209 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3210
3211 case CK_NullToMemberPointer:
3212 VisitIgnoredValue(E->getSubExpr());
3213 return ZeroInitialization(E);
3214
3215 case CK_BaseToDerivedMemberPointer: {
3216 if (!Visit(E->getSubExpr()))
3217 return false;
3218 if (E->path_empty())
3219 return true;
3220 // Base-to-derived member pointer casts store the path in derived-to-base
3221 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3222 // the wrong end of the derived->base arc, so stagger the path by one class.
3223 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3224 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3225 PathI != PathE; ++PathI) {
3226 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3227 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3228 if (!Result.castToDerived(Derived))
3229 return Error(E);
3230 }
3231 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3232 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3233 return Error(E);
3234 return true;
3235 }
3236
3237 case CK_DerivedToBaseMemberPointer:
3238 if (!Visit(E->getSubExpr()))
3239 return false;
3240 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3241 PathE = E->path_end(); PathI != PathE; ++PathI) {
3242 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3243 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3244 if (!Result.castToBase(Base))
3245 return Error(E);
3246 }
3247 return true;
3248 }
3249 }
3250
VisitUnaryAddrOf(const UnaryOperator * E)3251 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3252 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3253 // member can be formed.
3254 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3255 }
3256
3257 //===----------------------------------------------------------------------===//
3258 // Record Evaluation
3259 //===----------------------------------------------------------------------===//
3260
3261 namespace {
3262 class RecordExprEvaluator
3263 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3264 const LValue &This;
3265 APValue &Result;
3266 public:
3267
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)3268 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3269 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3270
Success(const APValue & V,const Expr * E)3271 bool Success(const APValue &V, const Expr *E) {
3272 Result = V;
3273 return true;
3274 }
3275 bool ZeroInitialization(const Expr *E);
3276
3277 bool VisitCastExpr(const CastExpr *E);
3278 bool VisitInitListExpr(const InitListExpr *E);
3279 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3280 };
3281 }
3282
3283 /// Perform zero-initialization on an object of non-union class type.
3284 /// C++11 [dcl.init]p5:
3285 /// To zero-initialize an object or reference of type T means:
3286 /// [...]
3287 /// -- if T is a (possibly cv-qualified) non-union class type,
3288 /// each non-static data member and each base-class subobject is
3289 /// zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)3290 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3291 const RecordDecl *RD,
3292 const LValue &This, APValue &Result) {
3293 assert(!RD->isUnion() && "Expected non-union class type");
3294 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3295 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3296 std::distance(RD->field_begin(), RD->field_end()));
3297
3298 if (RD->isInvalidDecl()) return false;
3299 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3300
3301 if (CD) {
3302 unsigned Index = 0;
3303 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3304 End = CD->bases_end(); I != End; ++I, ++Index) {
3305 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3306 LValue Subobject = This;
3307 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3308 return false;
3309 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3310 Result.getStructBase(Index)))
3311 return false;
3312 }
3313 }
3314
3315 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3316 I != End; ++I) {
3317 // -- if T is a reference type, no initialization is performed.
3318 if (I->getType()->isReferenceType())
3319 continue;
3320
3321 LValue Subobject = This;
3322 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
3323 return false;
3324
3325 ImplicitValueInitExpr VIE(I->getType());
3326 if (!EvaluateInPlace(
3327 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
3328 return false;
3329 }
3330
3331 return true;
3332 }
3333
ZeroInitialization(const Expr * E)3334 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3335 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3336 if (RD->isInvalidDecl()) return false;
3337 if (RD->isUnion()) {
3338 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3339 // object's first non-static named data member is zero-initialized
3340 RecordDecl::field_iterator I = RD->field_begin();
3341 if (I == RD->field_end()) {
3342 Result = APValue((const FieldDecl*)0);
3343 return true;
3344 }
3345
3346 LValue Subobject = This;
3347 if (!HandleLValueMember(Info, E, Subobject, *I))
3348 return false;
3349 Result = APValue(*I);
3350 ImplicitValueInitExpr VIE(I->getType());
3351 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
3352 }
3353
3354 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3355 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
3356 return false;
3357 }
3358
3359 return HandleClassZeroInitialization(Info, E, RD, This, Result);
3360 }
3361
VisitCastExpr(const CastExpr * E)3362 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3363 switch (E->getCastKind()) {
3364 default:
3365 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3366
3367 case CK_ConstructorConversion:
3368 return Visit(E->getSubExpr());
3369
3370 case CK_DerivedToBase:
3371 case CK_UncheckedDerivedToBase: {
3372 APValue DerivedObject;
3373 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3374 return false;
3375 if (!DerivedObject.isStruct())
3376 return Error(E->getSubExpr());
3377
3378 // Derived-to-base rvalue conversion: just slice off the derived part.
3379 APValue *Value = &DerivedObject;
3380 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3381 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3382 PathE = E->path_end(); PathI != PathE; ++PathI) {
3383 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3384 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3385 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3386 RD = Base;
3387 }
3388 Result = *Value;
3389 return true;
3390 }
3391 }
3392 }
3393
VisitInitListExpr(const InitListExpr * E)3394 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3395 // Cannot constant-evaluate std::initializer_list inits.
3396 if (E->initializesStdInitializerList())
3397 return false;
3398
3399 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3400 if (RD->isInvalidDecl()) return false;
3401 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3402
3403 if (RD->isUnion()) {
3404 const FieldDecl *Field = E->getInitializedFieldInUnion();
3405 Result = APValue(Field);
3406 if (!Field)
3407 return true;
3408
3409 // If the initializer list for a union does not contain any elements, the
3410 // first element of the union is value-initialized.
3411 ImplicitValueInitExpr VIE(Field->getType());
3412 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3413
3414 LValue Subobject = This;
3415 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3416 return false;
3417 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
3418 }
3419
3420 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3421 "initializer list for class with base classes");
3422 Result = APValue(APValue::UninitStruct(), 0,
3423 std::distance(RD->field_begin(), RD->field_end()));
3424 unsigned ElementNo = 0;
3425 bool Success = true;
3426 for (RecordDecl::field_iterator Field = RD->field_begin(),
3427 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3428 // Anonymous bit-fields are not considered members of the class for
3429 // purposes of aggregate initialization.
3430 if (Field->isUnnamedBitfield())
3431 continue;
3432
3433 LValue Subobject = This;
3434
3435 bool HaveInit = ElementNo < E->getNumInits();
3436
3437 // FIXME: Diagnostics here should point to the end of the initializer
3438 // list, not the start.
3439 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
3440 Subobject, *Field, &Layout))
3441 return false;
3442
3443 // Perform an implicit value-initialization for members beyond the end of
3444 // the initializer list.
3445 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3446
3447 if (!EvaluateInPlace(
3448 Result.getStructField(Field->getFieldIndex()),
3449 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3450 if (!Info.keepEvaluatingAfterFailure())
3451 return false;
3452 Success = false;
3453 }
3454 }
3455
3456 return Success;
3457 }
3458
VisitCXXConstructExpr(const CXXConstructExpr * E)3459 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3460 const CXXConstructorDecl *FD = E->getConstructor();
3461 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3462
3463 bool ZeroInit = E->requiresZeroInitialization();
3464 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3465 // If we've already performed zero-initialization, we're already done.
3466 if (!Result.isUninit())
3467 return true;
3468
3469 if (ZeroInit)
3470 return ZeroInitialization(E);
3471
3472 const CXXRecordDecl *RD = FD->getParent();
3473 if (RD->isUnion())
3474 Result = APValue((FieldDecl*)0);
3475 else
3476 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3477 std::distance(RD->field_begin(), RD->field_end()));
3478 return true;
3479 }
3480
3481 const FunctionDecl *Definition = 0;
3482 FD->getBody(Definition);
3483
3484 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3485 return false;
3486
3487 // Avoid materializing a temporary for an elidable copy/move constructor.
3488 if (E->isElidable() && !ZeroInit)
3489 if (const MaterializeTemporaryExpr *ME
3490 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3491 return Visit(ME->GetTemporaryExpr());
3492
3493 if (ZeroInit && !ZeroInitialization(E))
3494 return false;
3495
3496 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3497 return HandleConstructorCall(E->getExprLoc(), This, Args,
3498 cast<CXXConstructorDecl>(Definition), Info,
3499 Result);
3500 }
3501
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)3502 static bool EvaluateRecord(const Expr *E, const LValue &This,
3503 APValue &Result, EvalInfo &Info) {
3504 assert(E->isRValue() && E->getType()->isRecordType() &&
3505 "can't evaluate expression as a record rvalue");
3506 return RecordExprEvaluator(Info, This, Result).Visit(E);
3507 }
3508
3509 //===----------------------------------------------------------------------===//
3510 // Temporary Evaluation
3511 //
3512 // Temporaries are represented in the AST as rvalues, but generally behave like
3513 // lvalues. The full-object of which the temporary is a subobject is implicitly
3514 // materialized so that a reference can bind to it.
3515 //===----------------------------------------------------------------------===//
3516 namespace {
3517 class TemporaryExprEvaluator
3518 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3519 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)3520 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3521 LValueExprEvaluatorBaseTy(Info, Result) {}
3522
3523 /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)3524 bool VisitConstructExpr(const Expr *E) {
3525 Result.set(E, Info.CurrentCall->Index);
3526 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
3527 }
3528
VisitCastExpr(const CastExpr * E)3529 bool VisitCastExpr(const CastExpr *E) {
3530 switch (E->getCastKind()) {
3531 default:
3532 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3533
3534 case CK_ConstructorConversion:
3535 return VisitConstructExpr(E->getSubExpr());
3536 }
3537 }
VisitInitListExpr(const InitListExpr * E)3538 bool VisitInitListExpr(const InitListExpr *E) {
3539 return VisitConstructExpr(E);
3540 }
VisitCXXConstructExpr(const CXXConstructExpr * E)3541 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3542 return VisitConstructExpr(E);
3543 }
VisitCallExpr(const CallExpr * E)3544 bool VisitCallExpr(const CallExpr *E) {
3545 return VisitConstructExpr(E);
3546 }
3547 };
3548 } // end anonymous namespace
3549
3550 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)3551 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3552 assert(E->isRValue() && E->getType()->isRecordType());
3553 return TemporaryExprEvaluator(Info, Result).Visit(E);
3554 }
3555
3556 //===----------------------------------------------------------------------===//
3557 // Vector Evaluation
3558 //===----------------------------------------------------------------------===//
3559
3560 namespace {
3561 class VectorExprEvaluator
3562 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3563 APValue &Result;
3564 public:
3565
VectorExprEvaluator(EvalInfo & info,APValue & Result)3566 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3567 : ExprEvaluatorBaseTy(info), Result(Result) {}
3568
Success(const ArrayRef<APValue> & V,const Expr * E)3569 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3570 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3571 // FIXME: remove this APValue copy.
3572 Result = APValue(V.data(), V.size());
3573 return true;
3574 }
Success(const APValue & V,const Expr * E)3575 bool Success(const APValue &V, const Expr *E) {
3576 assert(V.isVector());
3577 Result = V;
3578 return true;
3579 }
3580 bool ZeroInitialization(const Expr *E);
3581
VisitUnaryReal(const UnaryOperator * E)3582 bool VisitUnaryReal(const UnaryOperator *E)
3583 { return Visit(E->getSubExpr()); }
3584 bool VisitCastExpr(const CastExpr* E);
3585 bool VisitInitListExpr(const InitListExpr *E);
3586 bool VisitUnaryImag(const UnaryOperator *E);
3587 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3588 // binary comparisons, binary and/or/xor,
3589 // shufflevector, ExtVectorElementExpr
3590 };
3591 } // end anonymous namespace
3592
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)3593 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3594 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3595 return VectorExprEvaluator(Info, Result).Visit(E);
3596 }
3597
VisitCastExpr(const CastExpr * E)3598 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3599 const VectorType *VTy = E->getType()->castAs<VectorType>();
3600 unsigned NElts = VTy->getNumElements();
3601
3602 const Expr *SE = E->getSubExpr();
3603 QualType SETy = SE->getType();
3604
3605 switch (E->getCastKind()) {
3606 case CK_VectorSplat: {
3607 APValue Val = APValue();
3608 if (SETy->isIntegerType()) {
3609 APSInt IntResult;
3610 if (!EvaluateInteger(SE, IntResult, Info))
3611 return false;
3612 Val = APValue(IntResult);
3613 } else if (SETy->isRealFloatingType()) {
3614 APFloat F(0.0);
3615 if (!EvaluateFloat(SE, F, Info))
3616 return false;
3617 Val = APValue(F);
3618 } else {
3619 return Error(E);
3620 }
3621
3622 // Splat and create vector APValue.
3623 SmallVector<APValue, 4> Elts(NElts, Val);
3624 return Success(Elts, E);
3625 }
3626 case CK_BitCast: {
3627 // Evaluate the operand into an APInt we can extract from.
3628 llvm::APInt SValInt;
3629 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3630 return false;
3631 // Extract the elements
3632 QualType EltTy = VTy->getElementType();
3633 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3634 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3635 SmallVector<APValue, 4> Elts;
3636 if (EltTy->isRealFloatingType()) {
3637 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3638 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3639 unsigned FloatEltSize = EltSize;
3640 if (&Sem == &APFloat::x87DoubleExtended)
3641 FloatEltSize = 80;
3642 for (unsigned i = 0; i < NElts; i++) {
3643 llvm::APInt Elt;
3644 if (BigEndian)
3645 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3646 else
3647 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3648 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3649 }
3650 } else if (EltTy->isIntegerType()) {
3651 for (unsigned i = 0; i < NElts; i++) {
3652 llvm::APInt Elt;
3653 if (BigEndian)
3654 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3655 else
3656 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3657 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3658 }
3659 } else {
3660 return Error(E);
3661 }
3662 return Success(Elts, E);
3663 }
3664 default:
3665 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3666 }
3667 }
3668
3669 bool
VisitInitListExpr(const InitListExpr * E)3670 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3671 const VectorType *VT = E->getType()->castAs<VectorType>();
3672 unsigned NumInits = E->getNumInits();
3673 unsigned NumElements = VT->getNumElements();
3674
3675 QualType EltTy = VT->getElementType();
3676 SmallVector<APValue, 4> Elements;
3677
3678 // The number of initializers can be less than the number of
3679 // vector elements. For OpenCL, this can be due to nested vector
3680 // initialization. For GCC compatibility, missing trailing elements
3681 // should be initialized with zeroes.
3682 unsigned CountInits = 0, CountElts = 0;
3683 while (CountElts < NumElements) {
3684 // Handle nested vector initialization.
3685 if (CountInits < NumInits
3686 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3687 APValue v;
3688 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3689 return Error(E);
3690 unsigned vlen = v.getVectorLength();
3691 for (unsigned j = 0; j < vlen; j++)
3692 Elements.push_back(v.getVectorElt(j));
3693 CountElts += vlen;
3694 } else if (EltTy->isIntegerType()) {
3695 llvm::APSInt sInt(32);
3696 if (CountInits < NumInits) {
3697 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3698 return false;
3699 } else // trailing integer zero.
3700 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3701 Elements.push_back(APValue(sInt));
3702 CountElts++;
3703 } else {
3704 llvm::APFloat f(0.0);
3705 if (CountInits < NumInits) {
3706 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3707 return false;
3708 } else // trailing float zero.
3709 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3710 Elements.push_back(APValue(f));
3711 CountElts++;
3712 }
3713 CountInits++;
3714 }
3715 return Success(Elements, E);
3716 }
3717
3718 bool
ZeroInitialization(const Expr * E)3719 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3720 const VectorType *VT = E->getType()->getAs<VectorType>();
3721 QualType EltTy = VT->getElementType();
3722 APValue ZeroElement;
3723 if (EltTy->isIntegerType())
3724 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3725 else
3726 ZeroElement =
3727 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3728
3729 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3730 return Success(Elements, E);
3731 }
3732
VisitUnaryImag(const UnaryOperator * E)3733 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3734 VisitIgnoredValue(E->getSubExpr());
3735 return ZeroInitialization(E);
3736 }
3737
3738 //===----------------------------------------------------------------------===//
3739 // Array Evaluation
3740 //===----------------------------------------------------------------------===//
3741
3742 namespace {
3743 class ArrayExprEvaluator
3744 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3745 const LValue &This;
3746 APValue &Result;
3747 public:
3748
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)3749 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3750 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3751
Success(const APValue & V,const Expr * E)3752 bool Success(const APValue &V, const Expr *E) {
3753 assert((V.isArray() || V.isLValue()) &&
3754 "expected array or string literal");
3755 Result = V;
3756 return true;
3757 }
3758
ZeroInitialization(const Expr * E)3759 bool ZeroInitialization(const Expr *E) {
3760 const ConstantArrayType *CAT =
3761 Info.Ctx.getAsConstantArrayType(E->getType());
3762 if (!CAT)
3763 return Error(E);
3764
3765 Result = APValue(APValue::UninitArray(), 0,
3766 CAT->getSize().getZExtValue());
3767 if (!Result.hasArrayFiller()) return true;
3768
3769 // Zero-initialize all elements.
3770 LValue Subobject = This;
3771 Subobject.addArray(Info, E, CAT);
3772 ImplicitValueInitExpr VIE(CAT->getElementType());
3773 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3774 }
3775
3776 bool VisitInitListExpr(const InitListExpr *E);
3777 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3778 };
3779 } // end anonymous namespace
3780
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)3781 static bool EvaluateArray(const Expr *E, const LValue &This,
3782 APValue &Result, EvalInfo &Info) {
3783 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3784 return ArrayExprEvaluator(Info, This, Result).Visit(E);
3785 }
3786
VisitInitListExpr(const InitListExpr * E)3787 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3788 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3789 if (!CAT)
3790 return Error(E);
3791
3792 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3793 // an appropriately-typed string literal enclosed in braces.
3794 if (E->isStringLiteralInit()) {
3795 LValue LV;
3796 if (!EvaluateLValue(E->getInit(0), LV, Info))
3797 return false;
3798 APValue Val;
3799 LV.moveInto(Val);
3800 return Success(Val, E);
3801 }
3802
3803 bool Success = true;
3804
3805 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3806 "zero-initialized array shouldn't have any initialized elts");
3807 APValue Filler;
3808 if (Result.isArray() && Result.hasArrayFiller())
3809 Filler = Result.getArrayFiller();
3810
3811 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3812 CAT->getSize().getZExtValue());
3813
3814 // If the array was previously zero-initialized, preserve the
3815 // zero-initialized values.
3816 if (!Filler.isUninit()) {
3817 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3818 Result.getArrayInitializedElt(I) = Filler;
3819 if (Result.hasArrayFiller())
3820 Result.getArrayFiller() = Filler;
3821 }
3822
3823 LValue Subobject = This;
3824 Subobject.addArray(Info, E, CAT);
3825 unsigned Index = 0;
3826 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3827 I != End; ++I, ++Index) {
3828 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3829 Info, Subobject, cast<Expr>(*I)) ||
3830 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3831 CAT->getElementType(), 1)) {
3832 if (!Info.keepEvaluatingAfterFailure())
3833 return false;
3834 Success = false;
3835 }
3836 }
3837
3838 if (!Result.hasArrayFiller()) return Success;
3839 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3840 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3841 // but sometimes does:
3842 // struct S { constexpr S() : p(&p) {} void *p; };
3843 // S s[10] = {};
3844 return EvaluateInPlace(Result.getArrayFiller(), Info,
3845 Subobject, E->getArrayFiller()) && Success;
3846 }
3847
VisitCXXConstructExpr(const CXXConstructExpr * E)3848 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3849 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3850 // but sometimes does:
3851 // struct S { constexpr S() : p(&p) {} void *p; };
3852 // S s[10];
3853 LValue Subobject = This;
3854
3855 APValue *Value = &Result;
3856 bool HadZeroInit = true;
3857 QualType ElemTy = E->getType();
3858 while (const ConstantArrayType *CAT =
3859 Info.Ctx.getAsConstantArrayType(ElemTy)) {
3860 Subobject.addArray(Info, E, CAT);
3861 HadZeroInit &= !Value->isUninit();
3862 if (!HadZeroInit)
3863 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3864 if (!Value->hasArrayFiller())
3865 return true;
3866 Value = &Value->getArrayFiller();
3867 ElemTy = CAT->getElementType();
3868 }
3869
3870 if (!ElemTy->isRecordType())
3871 return Error(E);
3872
3873 const CXXConstructorDecl *FD = E->getConstructor();
3874
3875 bool ZeroInit = E->requiresZeroInitialization();
3876 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3877 if (HadZeroInit)
3878 return true;
3879
3880 if (ZeroInit) {
3881 ImplicitValueInitExpr VIE(ElemTy);
3882 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
3883 }
3884
3885 const CXXRecordDecl *RD = FD->getParent();
3886 if (RD->isUnion())
3887 *Value = APValue((FieldDecl*)0);
3888 else
3889 *Value =
3890 APValue(APValue::UninitStruct(), RD->getNumBases(),
3891 std::distance(RD->field_begin(), RD->field_end()));
3892 return true;
3893 }
3894
3895 const FunctionDecl *Definition = 0;
3896 FD->getBody(Definition);
3897
3898 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3899 return false;
3900
3901 if (ZeroInit && !HadZeroInit) {
3902 ImplicitValueInitExpr VIE(ElemTy);
3903 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
3904 return false;
3905 }
3906
3907 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3908 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3909 cast<CXXConstructorDecl>(Definition),
3910 Info, *Value);
3911 }
3912
3913 //===----------------------------------------------------------------------===//
3914 // Integer Evaluation
3915 //
3916 // As a GNU extension, we support casting pointers to sufficiently-wide integer
3917 // types and back in constant folding. Integer values are thus represented
3918 // either as an integer-valued APValue, or as an lvalue-valued APValue.
3919 //===----------------------------------------------------------------------===//
3920
3921 namespace {
3922 class IntExprEvaluator
3923 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3924 APValue &Result;
3925 public:
IntExprEvaluator(EvalInfo & info,APValue & result)3926 IntExprEvaluator(EvalInfo &info, APValue &result)
3927 : ExprEvaluatorBaseTy(info), Result(result) {}
3928
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)3929 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
3930 assert(E->getType()->isIntegralOrEnumerationType() &&
3931 "Invalid evaluation result.");
3932 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3933 "Invalid evaluation result.");
3934 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3935 "Invalid evaluation result.");
3936 Result = APValue(SI);
3937 return true;
3938 }
Success(const llvm::APSInt & SI,const Expr * E)3939 bool Success(const llvm::APSInt &SI, const Expr *E) {
3940 return Success(SI, E, Result);
3941 }
3942
Success(const llvm::APInt & I,const Expr * E,APValue & Result)3943 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
3944 assert(E->getType()->isIntegralOrEnumerationType() &&
3945 "Invalid evaluation result.");
3946 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3947 "Invalid evaluation result.");
3948 Result = APValue(APSInt(I));
3949 Result.getInt().setIsUnsigned(
3950 E->getType()->isUnsignedIntegerOrEnumerationType());
3951 return true;
3952 }
Success(const llvm::APInt & I,const Expr * E)3953 bool Success(const llvm::APInt &I, const Expr *E) {
3954 return Success(I, E, Result);
3955 }
3956
Success(uint64_t Value,const Expr * E,APValue & Result)3957 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
3958 assert(E->getType()->isIntegralOrEnumerationType() &&
3959 "Invalid evaluation result.");
3960 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
3961 return true;
3962 }
Success(uint64_t Value,const Expr * E)3963 bool Success(uint64_t Value, const Expr *E) {
3964 return Success(Value, E, Result);
3965 }
3966
Success(CharUnits Size,const Expr * E)3967 bool Success(CharUnits Size, const Expr *E) {
3968 return Success(Size.getQuantity(), E);
3969 }
3970
Success(const APValue & V,const Expr * E)3971 bool Success(const APValue &V, const Expr *E) {
3972 if (V.isLValue() || V.isAddrLabelDiff()) {
3973 Result = V;
3974 return true;
3975 }
3976 return Success(V.getInt(), E);
3977 }
3978
ZeroInitialization(const Expr * E)3979 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
3980
3981 //===--------------------------------------------------------------------===//
3982 // Visitor Methods
3983 //===--------------------------------------------------------------------===//
3984
VisitIntegerLiteral(const IntegerLiteral * E)3985 bool VisitIntegerLiteral(const IntegerLiteral *E) {
3986 return Success(E->getValue(), E);
3987 }
VisitCharacterLiteral(const CharacterLiteral * E)3988 bool VisitCharacterLiteral(const CharacterLiteral *E) {
3989 return Success(E->getValue(), E);
3990 }
3991
3992 bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)3993 bool VisitDeclRefExpr(const DeclRefExpr *E) {
3994 if (CheckReferencedDecl(E, E->getDecl()))
3995 return true;
3996
3997 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
3998 }
VisitMemberExpr(const MemberExpr * E)3999 bool VisitMemberExpr(const MemberExpr *E) {
4000 if (CheckReferencedDecl(E, E->getMemberDecl())) {
4001 VisitIgnoredValue(E->getBase());
4002 return true;
4003 }
4004
4005 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
4006 }
4007
4008 bool VisitCallExpr(const CallExpr *E);
4009 bool VisitBinaryOperator(const BinaryOperator *E);
4010 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
4011 bool VisitUnaryOperator(const UnaryOperator *E);
4012
4013 bool VisitCastExpr(const CastExpr* E);
4014 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
4015
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)4016 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4017 return Success(E->getValue(), E);
4018 }
4019
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)4020 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4021 return Success(E->getValue(), E);
4022 }
4023
4024 // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)4025 bool VisitGNUNullExpr(const GNUNullExpr *E) {
4026 return ZeroInitialization(E);
4027 }
4028
VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr * E)4029 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
4030 return Success(E->getValue(), E);
4031 }
4032
VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr * E)4033 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4034 return Success(E->getValue(), E);
4035 }
4036
VisitTypeTraitExpr(const TypeTraitExpr * E)4037 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4038 return Success(E->getValue(), E);
4039 }
4040
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)4041 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4042 return Success(E->getValue(), E);
4043 }
4044
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)4045 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4046 return Success(E->getValue(), E);
4047 }
4048
4049 bool VisitUnaryReal(const UnaryOperator *E);
4050 bool VisitUnaryImag(const UnaryOperator *E);
4051
4052 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
4053 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
4054
4055 private:
4056 CharUnits GetAlignOfExpr(const Expr *E);
4057 CharUnits GetAlignOfType(QualType T);
4058 static QualType GetObjectType(APValue::LValueBase B);
4059 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
4060 // FIXME: Missing: array subscript of vector, member of vector
4061 };
4062 } // end anonymous namespace
4063
4064 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4065 /// produce either the integer value or a pointer.
4066 ///
4067 /// GCC has a heinous extension which folds casts between pointer types and
4068 /// pointer-sized integral types. We support this by allowing the evaluation of
4069 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4070 /// Some simple arithmetic on such values is supported (they are treated much
4071 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)4072 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
4073 EvalInfo &Info) {
4074 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
4075 return IntExprEvaluator(Info, Result).Visit(E);
4076 }
4077
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)4078 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
4079 APValue Val;
4080 if (!EvaluateIntegerOrLValue(E, Val, Info))
4081 return false;
4082 if (!Val.isInt()) {
4083 // FIXME: It would be better to produce the diagnostic for casting
4084 // a pointer to an integer.
4085 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
4086 return false;
4087 }
4088 Result = Val.getInt();
4089 return true;
4090 }
4091
4092 /// Check whether the given declaration can be directly converted to an integral
4093 /// rvalue. If not, no diagnostic is produced; there are other things we can
4094 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)4095 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
4096 // Enums are integer constant exprs.
4097 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
4098 // Check for signedness/width mismatches between E type and ECD value.
4099 bool SameSign = (ECD->getInitVal().isSigned()
4100 == E->getType()->isSignedIntegerOrEnumerationType());
4101 bool SameWidth = (ECD->getInitVal().getBitWidth()
4102 == Info.Ctx.getIntWidth(E->getType()));
4103 if (SameSign && SameWidth)
4104 return Success(ECD->getInitVal(), E);
4105 else {
4106 // Get rid of mismatch (otherwise Success assertions will fail)
4107 // by computing a new value matching the type of E.
4108 llvm::APSInt Val = ECD->getInitVal();
4109 if (!SameSign)
4110 Val.setIsSigned(!ECD->getInitVal().isSigned());
4111 if (!SameWidth)
4112 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4113 return Success(Val, E);
4114 }
4115 }
4116 return false;
4117 }
4118
4119 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4120 /// as GCC.
EvaluateBuiltinClassifyType(const CallExpr * E)4121 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4122 // The following enum mimics the values returned by GCC.
4123 // FIXME: Does GCC differ between lvalue and rvalue references here?
4124 enum gcc_type_class {
4125 no_type_class = -1,
4126 void_type_class, integer_type_class, char_type_class,
4127 enumeral_type_class, boolean_type_class,
4128 pointer_type_class, reference_type_class, offset_type_class,
4129 real_type_class, complex_type_class,
4130 function_type_class, method_type_class,
4131 record_type_class, union_type_class,
4132 array_type_class, string_type_class,
4133 lang_type_class
4134 };
4135
4136 // If no argument was supplied, default to "no_type_class". This isn't
4137 // ideal, however it is what gcc does.
4138 if (E->getNumArgs() == 0)
4139 return no_type_class;
4140
4141 QualType ArgTy = E->getArg(0)->getType();
4142 if (ArgTy->isVoidType())
4143 return void_type_class;
4144 else if (ArgTy->isEnumeralType())
4145 return enumeral_type_class;
4146 else if (ArgTy->isBooleanType())
4147 return boolean_type_class;
4148 else if (ArgTy->isCharType())
4149 return string_type_class; // gcc doesn't appear to use char_type_class
4150 else if (ArgTy->isIntegerType())
4151 return integer_type_class;
4152 else if (ArgTy->isPointerType())
4153 return pointer_type_class;
4154 else if (ArgTy->isReferenceType())
4155 return reference_type_class;
4156 else if (ArgTy->isRealType())
4157 return real_type_class;
4158 else if (ArgTy->isComplexType())
4159 return complex_type_class;
4160 else if (ArgTy->isFunctionType())
4161 return function_type_class;
4162 else if (ArgTy->isStructureOrClassType())
4163 return record_type_class;
4164 else if (ArgTy->isUnionType())
4165 return union_type_class;
4166 else if (ArgTy->isArrayType())
4167 return array_type_class;
4168 else if (ArgTy->isUnionType())
4169 return union_type_class;
4170 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
4171 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4172 }
4173
4174 /// EvaluateBuiltinConstantPForLValue - Determine the result of
4175 /// __builtin_constant_p when applied to the given lvalue.
4176 ///
4177 /// An lvalue is only "constant" if it is a pointer or reference to the first
4178 /// character of a string literal.
4179 template<typename LValue>
EvaluateBuiltinConstantPForLValue(const LValue & LV)4180 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4181 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
4182 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4183 }
4184
4185 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4186 /// GCC as we can manage.
EvaluateBuiltinConstantP(ASTContext & Ctx,const Expr * Arg)4187 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4188 QualType ArgType = Arg->getType();
4189
4190 // __builtin_constant_p always has one operand. The rules which gcc follows
4191 // are not precisely documented, but are as follows:
4192 //
4193 // - If the operand is of integral, floating, complex or enumeration type,
4194 // and can be folded to a known value of that type, it returns 1.
4195 // - If the operand and can be folded to a pointer to the first character
4196 // of a string literal (or such a pointer cast to an integral type), it
4197 // returns 1.
4198 //
4199 // Otherwise, it returns 0.
4200 //
4201 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4202 // its support for this does not currently work.
4203 if (ArgType->isIntegralOrEnumerationType()) {
4204 Expr::EvalResult Result;
4205 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4206 return false;
4207
4208 APValue &V = Result.Val;
4209 if (V.getKind() == APValue::Int)
4210 return true;
4211
4212 return EvaluateBuiltinConstantPForLValue(V);
4213 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4214 return Arg->isEvaluatable(Ctx);
4215 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4216 LValue LV;
4217 Expr::EvalStatus Status;
4218 EvalInfo Info(Ctx, Status);
4219 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4220 : EvaluatePointer(Arg, LV, Info)) &&
4221 !Status.HasSideEffects)
4222 return EvaluateBuiltinConstantPForLValue(LV);
4223 }
4224
4225 // Anything else isn't considered to be sufficiently constant.
4226 return false;
4227 }
4228
4229 /// Retrieves the "underlying object type" of the given expression,
4230 /// as used by __builtin_object_size.
GetObjectType(APValue::LValueBase B)4231 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4232 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4233 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4234 return VD->getType();
4235 } else if (const Expr *E = B.get<const Expr*>()) {
4236 if (isa<CompoundLiteralExpr>(E))
4237 return E->getType();
4238 }
4239
4240 return QualType();
4241 }
4242
TryEvaluateBuiltinObjectSize(const CallExpr * E)4243 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4244 LValue Base;
4245
4246 {
4247 // The operand of __builtin_object_size is never evaluated for side-effects.
4248 // If there are any, but we can determine the pointed-to object anyway, then
4249 // ignore the side-effects.
4250 SpeculativeEvaluationRAII SpeculativeEval(Info);
4251 if (!EvaluatePointer(E->getArg(0), Base, Info))
4252 return false;
4253 }
4254
4255 // If we can prove the base is null, lower to zero now.
4256 if (!Base.getLValueBase()) return Success(0, E);
4257
4258 QualType T = GetObjectType(Base.getLValueBase());
4259 if (T.isNull() ||
4260 T->isIncompleteType() ||
4261 T->isFunctionType() ||
4262 T->isVariablyModifiedType() ||
4263 T->isDependentType())
4264 return Error(E);
4265
4266 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4267 CharUnits Offset = Base.getLValueOffset();
4268
4269 if (!Offset.isNegative() && Offset <= Size)
4270 Size -= Offset;
4271 else
4272 Size = CharUnits::Zero();
4273 return Success(Size, E);
4274 }
4275
VisitCallExpr(const CallExpr * E)4276 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
4277 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
4278 default:
4279 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4280
4281 case Builtin::BI__builtin_object_size: {
4282 if (TryEvaluateBuiltinObjectSize(E))
4283 return true;
4284
4285 // If evaluating the argument has side-effects, we can't determine the size
4286 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4287 // handle all cases where the expression has side-effects.
4288 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
4289 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
4290 return Success(-1ULL, E);
4291 return Success(0, E);
4292 }
4293
4294 // Expression had no side effects, but we couldn't statically determine the
4295 // size of the referenced object.
4296 return Error(E);
4297 }
4298
4299 case Builtin::BI__builtin_classify_type:
4300 return Success(EvaluateBuiltinClassifyType(E), E);
4301
4302 case Builtin::BI__builtin_constant_p:
4303 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4304
4305 case Builtin::BI__builtin_eh_return_data_regno: {
4306 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4307 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4308 return Success(Operand, E);
4309 }
4310
4311 case Builtin::BI__builtin_expect:
4312 return Visit(E->getArg(0));
4313
4314 case Builtin::BIstrlen:
4315 // A call to strlen is not a constant expression.
4316 if (Info.getLangOpts().CPlusPlus0x)
4317 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
4318 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4319 else
4320 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
4321 // Fall through.
4322 case Builtin::BI__builtin_strlen:
4323 // As an extension, we support strlen() and __builtin_strlen() as constant
4324 // expressions when the argument is a string literal.
4325 if (const StringLiteral *S
4326 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4327 // The string literal may have embedded null characters. Find the first
4328 // one and truncate there.
4329 StringRef Str = S->getString();
4330 StringRef::size_type Pos = Str.find(0);
4331 if (Pos != StringRef::npos)
4332 Str = Str.substr(0, Pos);
4333
4334 return Success(Str.size(), E);
4335 }
4336
4337 return Error(E);
4338
4339 case Builtin::BI__atomic_always_lock_free:
4340 case Builtin::BI__atomic_is_lock_free:
4341 case Builtin::BI__c11_atomic_is_lock_free: {
4342 APSInt SizeVal;
4343 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4344 return false;
4345
4346 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4347 // of two less than the maximum inline atomic width, we know it is
4348 // lock-free. If the size isn't a power of two, or greater than the
4349 // maximum alignment where we promote atomics, we know it is not lock-free
4350 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4351 // the answer can only be determined at runtime; for example, 16-byte
4352 // atomics have lock-free implementations on some, but not all,
4353 // x86-64 processors.
4354
4355 // Check power-of-two.
4356 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4357 if (Size.isPowerOfTwo()) {
4358 // Check against inlining width.
4359 unsigned InlineWidthBits =
4360 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4361 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4362 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4363 Size == CharUnits::One() ||
4364 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4365 Expr::NPC_NeverValueDependent))
4366 // OK, we will inline appropriately-aligned operations of this size,
4367 // and _Atomic(T) is appropriately-aligned.
4368 return Success(1, E);
4369
4370 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4371 castAs<PointerType>()->getPointeeType();
4372 if (!PointeeType->isIncompleteType() &&
4373 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4374 // OK, we will inline operations on this object.
4375 return Success(1, E);
4376 }
4377 }
4378 }
4379
4380 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4381 Success(0, E) : Error(E);
4382 }
4383 }
4384 }
4385
HasSameBase(const LValue & A,const LValue & B)4386 static bool HasSameBase(const LValue &A, const LValue &B) {
4387 if (!A.getLValueBase())
4388 return !B.getLValueBase();
4389 if (!B.getLValueBase())
4390 return false;
4391
4392 if (A.getLValueBase().getOpaqueValue() !=
4393 B.getLValueBase().getOpaqueValue()) {
4394 const Decl *ADecl = GetLValueBaseDecl(A);
4395 if (!ADecl)
4396 return false;
4397 const Decl *BDecl = GetLValueBaseDecl(B);
4398 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4399 return false;
4400 }
4401
4402 return IsGlobalLValue(A.getLValueBase()) ||
4403 A.getLValueCallIndex() == B.getLValueCallIndex();
4404 }
4405
4406 /// Perform the given integer operation, which is known to need at most BitWidth
4407 /// bits, and check for overflow in the original type (if that type was not an
4408 /// unsigned type).
4409 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op)4410 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4411 const APSInt &LHS, const APSInt &RHS,
4412 unsigned BitWidth, Operation Op) {
4413 if (LHS.isUnsigned())
4414 return Op(LHS, RHS);
4415
4416 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4417 APSInt Result = Value.trunc(LHS.getBitWidth());
4418 if (Result.extend(BitWidth) != Value)
4419 HandleOverflow(Info, E, Value, E->getType());
4420 return Result;
4421 }
4422
4423 namespace {
4424
4425 /// \brief Data recursive integer evaluator of certain binary operators.
4426 ///
4427 /// We use a data recursive algorithm for binary operators so that we are able
4428 /// to handle extreme cases of chained binary operators without causing stack
4429 /// overflow.
4430 class DataRecursiveIntBinOpEvaluator {
4431 struct EvalResult {
4432 APValue Val;
4433 bool Failed;
4434
EvalResult__anon39b33ae20f11::DataRecursiveIntBinOpEvaluator::EvalResult4435 EvalResult() : Failed(false) { }
4436
swap__anon39b33ae20f11::DataRecursiveIntBinOpEvaluator::EvalResult4437 void swap(EvalResult &RHS) {
4438 Val.swap(RHS.Val);
4439 Failed = RHS.Failed;
4440 RHS.Failed = false;
4441 }
4442 };
4443
4444 struct Job {
4445 const Expr *E;
4446 EvalResult LHSResult; // meaningful only for binary operator expression.
4447 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4448
Job__anon39b33ae20f11::DataRecursiveIntBinOpEvaluator::Job4449 Job() : StoredInfo(0) { }
startSpeculativeEval__anon39b33ae20f11::DataRecursiveIntBinOpEvaluator::Job4450 void startSpeculativeEval(EvalInfo &Info) {
4451 OldEvalStatus = Info.EvalStatus;
4452 Info.EvalStatus.Diag = 0;
4453 StoredInfo = &Info;
4454 }
~Job__anon39b33ae20f11::DataRecursiveIntBinOpEvaluator::Job4455 ~Job() {
4456 if (StoredInfo) {
4457 StoredInfo->EvalStatus = OldEvalStatus;
4458 }
4459 }
4460 private:
4461 EvalInfo *StoredInfo; // non-null if status changed.
4462 Expr::EvalStatus OldEvalStatus;
4463 };
4464
4465 SmallVector<Job, 16> Queue;
4466
4467 IntExprEvaluator &IntEval;
4468 EvalInfo &Info;
4469 APValue &FinalResult;
4470
4471 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)4472 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4473 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4474
4475 /// \brief True if \param E is a binary operator that we are going to handle
4476 /// data recursively.
4477 /// We handle binary operators that are comma, logical, or that have operands
4478 /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)4479 static bool shouldEnqueue(const BinaryOperator *E) {
4480 return E->getOpcode() == BO_Comma ||
4481 E->isLogicalOp() ||
4482 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4483 E->getRHS()->getType()->isIntegralOrEnumerationType());
4484 }
4485
Traverse(const BinaryOperator * E)4486 bool Traverse(const BinaryOperator *E) {
4487 enqueue(E);
4488 EvalResult PrevResult;
4489 while (!Queue.empty())
4490 process(PrevResult);
4491
4492 if (PrevResult.Failed) return false;
4493
4494 FinalResult.swap(PrevResult.Val);
4495 return true;
4496 }
4497
4498 private:
Success(uint64_t Value,const Expr * E,APValue & Result)4499 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4500 return IntEval.Success(Value, E, Result);
4501 }
Success(const APSInt & Value,const Expr * E,APValue & Result)4502 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4503 return IntEval.Success(Value, E, Result);
4504 }
Error(const Expr * E)4505 bool Error(const Expr *E) {
4506 return IntEval.Error(E);
4507 }
Error(const Expr * E,diag::kind D)4508 bool Error(const Expr *E, diag::kind D) {
4509 return IntEval.Error(E, D);
4510 }
4511
CCEDiag(const Expr * E,diag::kind D)4512 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4513 return Info.CCEDiag(E, D);
4514 }
4515
4516 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4517 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4518 bool &SuppressRHSDiags);
4519
4520 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4521 const BinaryOperator *E, APValue &Result);
4522
EvaluateExpr(const Expr * E,EvalResult & Result)4523 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4524 Result.Failed = !Evaluate(Result.Val, Info, E);
4525 if (Result.Failed)
4526 Result.Val = APValue();
4527 }
4528
4529 void process(EvalResult &Result);
4530
enqueue(const Expr * E)4531 void enqueue(const Expr *E) {
4532 E = E->IgnoreParens();
4533 Queue.resize(Queue.size()+1);
4534 Queue.back().E = E;
4535 Queue.back().Kind = Job::AnyExprKind;
4536 }
4537 };
4538
4539 }
4540
4541 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)4542 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4543 bool &SuppressRHSDiags) {
4544 if (E->getOpcode() == BO_Comma) {
4545 // Ignore LHS but note if we could not evaluate it.
4546 if (LHSResult.Failed)
4547 Info.EvalStatus.HasSideEffects = true;
4548 return true;
4549 }
4550
4551 if (E->isLogicalOp()) {
4552 bool lhsResult;
4553 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
4554 // We were able to evaluate the LHS, see if we can get away with not
4555 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4556 if (lhsResult == (E->getOpcode() == BO_LOr)) {
4557 Success(lhsResult, E, LHSResult.Val);
4558 return false; // Ignore RHS
4559 }
4560 } else {
4561 // Since we weren't able to evaluate the left hand side, it
4562 // must have had side effects.
4563 Info.EvalStatus.HasSideEffects = true;
4564
4565 // We can't evaluate the LHS; however, sometimes the result
4566 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4567 // Don't ignore RHS and suppress diagnostics from this arm.
4568 SuppressRHSDiags = true;
4569 }
4570
4571 return true;
4572 }
4573
4574 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4575 E->getRHS()->getType()->isIntegralOrEnumerationType());
4576
4577 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
4578 return false; // Ignore RHS;
4579
4580 return true;
4581 }
4582
4583 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)4584 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4585 const BinaryOperator *E, APValue &Result) {
4586 if (E->getOpcode() == BO_Comma) {
4587 if (RHSResult.Failed)
4588 return false;
4589 Result = RHSResult.Val;
4590 return true;
4591 }
4592
4593 if (E->isLogicalOp()) {
4594 bool lhsResult, rhsResult;
4595 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4596 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4597
4598 if (LHSIsOK) {
4599 if (RHSIsOK) {
4600 if (E->getOpcode() == BO_LOr)
4601 return Success(lhsResult || rhsResult, E, Result);
4602 else
4603 return Success(lhsResult && rhsResult, E, Result);
4604 }
4605 } else {
4606 if (RHSIsOK) {
4607 // We can't evaluate the LHS; however, sometimes the result
4608 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4609 if (rhsResult == (E->getOpcode() == BO_LOr))
4610 return Success(rhsResult, E, Result);
4611 }
4612 }
4613
4614 return false;
4615 }
4616
4617 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4618 E->getRHS()->getType()->isIntegralOrEnumerationType());
4619
4620 if (LHSResult.Failed || RHSResult.Failed)
4621 return false;
4622
4623 const APValue &LHSVal = LHSResult.Val;
4624 const APValue &RHSVal = RHSResult.Val;
4625
4626 // Handle cases like (unsigned long)&a + 4.
4627 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4628 Result = LHSVal;
4629 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4630 RHSVal.getInt().getZExtValue());
4631 if (E->getOpcode() == BO_Add)
4632 Result.getLValueOffset() += AdditionalOffset;
4633 else
4634 Result.getLValueOffset() -= AdditionalOffset;
4635 return true;
4636 }
4637
4638 // Handle cases like 4 + (unsigned long)&a
4639 if (E->getOpcode() == BO_Add &&
4640 RHSVal.isLValue() && LHSVal.isInt()) {
4641 Result = RHSVal;
4642 Result.getLValueOffset() += CharUnits::fromQuantity(
4643 LHSVal.getInt().getZExtValue());
4644 return true;
4645 }
4646
4647 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4648 // Handle (intptr_t)&&A - (intptr_t)&&B.
4649 if (!LHSVal.getLValueOffset().isZero() ||
4650 !RHSVal.getLValueOffset().isZero())
4651 return false;
4652 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4653 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4654 if (!LHSExpr || !RHSExpr)
4655 return false;
4656 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4657 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4658 if (!LHSAddrExpr || !RHSAddrExpr)
4659 return false;
4660 // Make sure both labels come from the same function.
4661 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4662 RHSAddrExpr->getLabel()->getDeclContext())
4663 return false;
4664 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4665 return true;
4666 }
4667
4668 // All the following cases expect both operands to be an integer
4669 if (!LHSVal.isInt() || !RHSVal.isInt())
4670 return Error(E);
4671
4672 const APSInt &LHS = LHSVal.getInt();
4673 APSInt RHS = RHSVal.getInt();
4674
4675 switch (E->getOpcode()) {
4676 default:
4677 return Error(E);
4678 case BO_Mul:
4679 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4680 LHS.getBitWidth() * 2,
4681 std::multiplies<APSInt>()), E,
4682 Result);
4683 case BO_Add:
4684 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4685 LHS.getBitWidth() + 1,
4686 std::plus<APSInt>()), E, Result);
4687 case BO_Sub:
4688 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4689 LHS.getBitWidth() + 1,
4690 std::minus<APSInt>()), E, Result);
4691 case BO_And: return Success(LHS & RHS, E, Result);
4692 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4693 case BO_Or: return Success(LHS | RHS, E, Result);
4694 case BO_Div:
4695 case BO_Rem:
4696 if (RHS == 0)
4697 return Error(E, diag::note_expr_divide_by_zero);
4698 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4699 // not actually undefined behavior in C++11 due to a language defect.
4700 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4701 LHS.isSigned() && LHS.isMinSignedValue())
4702 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4703 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4704 Result);
4705 case BO_Shl: {
4706 // During constant-folding, a negative shift is an opposite shift. Such
4707 // a shift is not a constant expression.
4708 if (RHS.isSigned() && RHS.isNegative()) {
4709 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4710 RHS = -RHS;
4711 goto shift_right;
4712 }
4713
4714 shift_left:
4715 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4716 // the shifted type.
4717 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4718 if (SA != RHS) {
4719 CCEDiag(E, diag::note_constexpr_large_shift)
4720 << RHS << E->getType() << LHS.getBitWidth();
4721 } else if (LHS.isSigned()) {
4722 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4723 // operand, and must not overflow the corresponding unsigned type.
4724 if (LHS.isNegative())
4725 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4726 else if (LHS.countLeadingZeros() < SA)
4727 CCEDiag(E, diag::note_constexpr_lshift_discards);
4728 }
4729
4730 return Success(LHS << SA, E, Result);
4731 }
4732 case BO_Shr: {
4733 // During constant-folding, a negative shift is an opposite shift. Such a
4734 // shift is not a constant expression.
4735 if (RHS.isSigned() && RHS.isNegative()) {
4736 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4737 RHS = -RHS;
4738 goto shift_left;
4739 }
4740
4741 shift_right:
4742 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4743 // shifted type.
4744 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4745 if (SA != RHS)
4746 CCEDiag(E, diag::note_constexpr_large_shift)
4747 << RHS << E->getType() << LHS.getBitWidth();
4748
4749 return Success(LHS >> SA, E, Result);
4750 }
4751
4752 case BO_LT: return Success(LHS < RHS, E, Result);
4753 case BO_GT: return Success(LHS > RHS, E, Result);
4754 case BO_LE: return Success(LHS <= RHS, E, Result);
4755 case BO_GE: return Success(LHS >= RHS, E, Result);
4756 case BO_EQ: return Success(LHS == RHS, E, Result);
4757 case BO_NE: return Success(LHS != RHS, E, Result);
4758 }
4759 }
4760
process(EvalResult & Result)4761 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
4762 Job &job = Queue.back();
4763
4764 switch (job.Kind) {
4765 case Job::AnyExprKind: {
4766 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4767 if (shouldEnqueue(Bop)) {
4768 job.Kind = Job::BinOpKind;
4769 enqueue(Bop->getLHS());
4770 return;
4771 }
4772 }
4773
4774 EvaluateExpr(job.E, Result);
4775 Queue.pop_back();
4776 return;
4777 }
4778
4779 case Job::BinOpKind: {
4780 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4781 bool SuppressRHSDiags = false;
4782 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
4783 Queue.pop_back();
4784 return;
4785 }
4786 if (SuppressRHSDiags)
4787 job.startSpeculativeEval(Info);
4788 job.LHSResult.swap(Result);
4789 job.Kind = Job::BinOpVisitedLHSKind;
4790 enqueue(Bop->getRHS());
4791 return;
4792 }
4793
4794 case Job::BinOpVisitedLHSKind: {
4795 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4796 EvalResult RHS;
4797 RHS.swap(Result);
4798 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
4799 Queue.pop_back();
4800 return;
4801 }
4802 }
4803
4804 llvm_unreachable("Invalid Job::Kind!");
4805 }
4806
VisitBinaryOperator(const BinaryOperator * E)4807 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4808 if (E->isAssignmentOp())
4809 return Error(E);
4810
4811 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4812 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
4813
4814 QualType LHSTy = E->getLHS()->getType();
4815 QualType RHSTy = E->getRHS()->getType();
4816
4817 if (LHSTy->isAnyComplexType()) {
4818 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4819 ComplexValue LHS, RHS;
4820
4821 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4822 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4823 return false;
4824
4825 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4826 return false;
4827
4828 if (LHS.isComplexFloat()) {
4829 APFloat::cmpResult CR_r =
4830 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4831 APFloat::cmpResult CR_i =
4832 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4833
4834 if (E->getOpcode() == BO_EQ)
4835 return Success((CR_r == APFloat::cmpEqual &&
4836 CR_i == APFloat::cmpEqual), E);
4837 else {
4838 assert(E->getOpcode() == BO_NE &&
4839 "Invalid complex comparison.");
4840 return Success(((CR_r == APFloat::cmpGreaterThan ||
4841 CR_r == APFloat::cmpLessThan ||
4842 CR_r == APFloat::cmpUnordered) ||
4843 (CR_i == APFloat::cmpGreaterThan ||
4844 CR_i == APFloat::cmpLessThan ||
4845 CR_i == APFloat::cmpUnordered)), E);
4846 }
4847 } else {
4848 if (E->getOpcode() == BO_EQ)
4849 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4850 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4851 else {
4852 assert(E->getOpcode() == BO_NE &&
4853 "Invalid compex comparison.");
4854 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4855 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4856 }
4857 }
4858 }
4859
4860 if (LHSTy->isRealFloatingType() &&
4861 RHSTy->isRealFloatingType()) {
4862 APFloat RHS(0.0), LHS(0.0);
4863
4864 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4865 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4866 return false;
4867
4868 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4869 return false;
4870
4871 APFloat::cmpResult CR = LHS.compare(RHS);
4872
4873 switch (E->getOpcode()) {
4874 default:
4875 llvm_unreachable("Invalid binary operator!");
4876 case BO_LT:
4877 return Success(CR == APFloat::cmpLessThan, E);
4878 case BO_GT:
4879 return Success(CR == APFloat::cmpGreaterThan, E);
4880 case BO_LE:
4881 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4882 case BO_GE:
4883 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4884 E);
4885 case BO_EQ:
4886 return Success(CR == APFloat::cmpEqual, E);
4887 case BO_NE:
4888 return Success(CR == APFloat::cmpGreaterThan
4889 || CR == APFloat::cmpLessThan
4890 || CR == APFloat::cmpUnordered, E);
4891 }
4892 }
4893
4894 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4895 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4896 LValue LHSValue, RHSValue;
4897
4898 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4899 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4900 return false;
4901
4902 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4903 return false;
4904
4905 // Reject differing bases from the normal codepath; we special-case
4906 // comparisons to null.
4907 if (!HasSameBase(LHSValue, RHSValue)) {
4908 if (E->getOpcode() == BO_Sub) {
4909 // Handle &&A - &&B.
4910 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4911 return false;
4912 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4913 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4914 if (!LHSExpr || !RHSExpr)
4915 return false;
4916 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4917 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4918 if (!LHSAddrExpr || !RHSAddrExpr)
4919 return false;
4920 // Make sure both labels come from the same function.
4921 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4922 RHSAddrExpr->getLabel()->getDeclContext())
4923 return false;
4924 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4925 return true;
4926 }
4927 // Inequalities and subtractions between unrelated pointers have
4928 // unspecified or undefined behavior.
4929 if (!E->isEqualityOp())
4930 return Error(E);
4931 // A constant address may compare equal to the address of a symbol.
4932 // The one exception is that address of an object cannot compare equal
4933 // to a null pointer constant.
4934 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4935 (!RHSValue.Base && !RHSValue.Offset.isZero()))
4936 return Error(E);
4937 // It's implementation-defined whether distinct literals will have
4938 // distinct addresses. In clang, the result of such a comparison is
4939 // unspecified, so it is not a constant expression. However, we do know
4940 // that the address of a literal will be non-null.
4941 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4942 LHSValue.Base && RHSValue.Base)
4943 return Error(E);
4944 // We can't tell whether weak symbols will end up pointing to the same
4945 // object.
4946 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4947 return Error(E);
4948 // Pointers with different bases cannot represent the same object.
4949 // (Note that clang defaults to -fmerge-all-constants, which can
4950 // lead to inconsistent results for comparisons involving the address
4951 // of a constant; this generally doesn't matter in practice.)
4952 return Success(E->getOpcode() == BO_NE, E);
4953 }
4954
4955 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4956 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4957
4958 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4959 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4960
4961 if (E->getOpcode() == BO_Sub) {
4962 // C++11 [expr.add]p6:
4963 // Unless both pointers point to elements of the same array object, or
4964 // one past the last element of the array object, the behavior is
4965 // undefined.
4966 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4967 !AreElementsOfSameArray(getType(LHSValue.Base),
4968 LHSDesignator, RHSDesignator))
4969 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4970
4971 QualType Type = E->getLHS()->getType();
4972 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
4973
4974 CharUnits ElementSize;
4975 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
4976 return false;
4977
4978 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4979 // and produce incorrect results when it overflows. Such behavior
4980 // appears to be non-conforming, but is common, so perhaps we should
4981 // assume the standard intended for such cases to be undefined behavior
4982 // and check for them.
4983
4984 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4985 // overflow in the final conversion to ptrdiff_t.
4986 APSInt LHS(
4987 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4988 APSInt RHS(
4989 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4990 APSInt ElemSize(
4991 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4992 APSInt TrueResult = (LHS - RHS) / ElemSize;
4993 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4994
4995 if (Result.extend(65) != TrueResult)
4996 HandleOverflow(Info, E, TrueResult, E->getType());
4997 return Success(Result, E);
4998 }
4999
5000 // C++11 [expr.rel]p3:
5001 // Pointers to void (after pointer conversions) can be compared, with a
5002 // result defined as follows: If both pointers represent the same
5003 // address or are both the null pointer value, the result is true if the
5004 // operator is <= or >= and false otherwise; otherwise the result is
5005 // unspecified.
5006 // We interpret this as applying to pointers to *cv* void.
5007 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
5008 E->isRelationalOp())
5009 CCEDiag(E, diag::note_constexpr_void_comparison);
5010
5011 // C++11 [expr.rel]p2:
5012 // - If two pointers point to non-static data members of the same object,
5013 // or to subobjects or array elements fo such members, recursively, the
5014 // pointer to the later declared member compares greater provided the
5015 // two members have the same access control and provided their class is
5016 // not a union.
5017 // [...]
5018 // - Otherwise pointer comparisons are unspecified.
5019 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5020 E->isRelationalOp()) {
5021 bool WasArrayIndex;
5022 unsigned Mismatch =
5023 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5024 RHSDesignator, WasArrayIndex);
5025 // At the point where the designators diverge, the comparison has a
5026 // specified value if:
5027 // - we are comparing array indices
5028 // - we are comparing fields of a union, or fields with the same access
5029 // Otherwise, the result is unspecified and thus the comparison is not a
5030 // constant expression.
5031 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5032 Mismatch < RHSDesignator.Entries.size()) {
5033 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5034 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5035 if (!LF && !RF)
5036 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5037 else if (!LF)
5038 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5039 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5040 << RF->getParent() << RF;
5041 else if (!RF)
5042 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5043 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5044 << LF->getParent() << LF;
5045 else if (!LF->getParent()->isUnion() &&
5046 LF->getAccess() != RF->getAccess())
5047 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5048 << LF << LF->getAccess() << RF << RF->getAccess()
5049 << LF->getParent();
5050 }
5051 }
5052
5053 // The comparison here must be unsigned, and performed with the same
5054 // width as the pointer.
5055 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5056 uint64_t CompareLHS = LHSOffset.getQuantity();
5057 uint64_t CompareRHS = RHSOffset.getQuantity();
5058 assert(PtrSize <= 64 && "Unexpected pointer width");
5059 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5060 CompareLHS &= Mask;
5061 CompareRHS &= Mask;
5062
5063 // If there is a base and this is a relational operator, we can only
5064 // compare pointers within the object in question; otherwise, the result
5065 // depends on where the object is located in memory.
5066 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5067 QualType BaseTy = getType(LHSValue.Base);
5068 if (BaseTy->isIncompleteType())
5069 return Error(E);
5070 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5071 uint64_t OffsetLimit = Size.getQuantity();
5072 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5073 return Error(E);
5074 }
5075
5076 switch (E->getOpcode()) {
5077 default: llvm_unreachable("missing comparison operator");
5078 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5079 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5080 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5081 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5082 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5083 case BO_NE: return Success(CompareLHS != CompareRHS, E);
5084 }
5085 }
5086 }
5087
5088 if (LHSTy->isMemberPointerType()) {
5089 assert(E->isEqualityOp() && "unexpected member pointer operation");
5090 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5091
5092 MemberPtr LHSValue, RHSValue;
5093
5094 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5095 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5096 return false;
5097
5098 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5099 return false;
5100
5101 // C++11 [expr.eq]p2:
5102 // If both operands are null, they compare equal. Otherwise if only one is
5103 // null, they compare unequal.
5104 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5105 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5106 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5107 }
5108
5109 // Otherwise if either is a pointer to a virtual member function, the
5110 // result is unspecified.
5111 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5112 if (MD->isVirtual())
5113 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5115 if (MD->isVirtual())
5116 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5117
5118 // Otherwise they compare equal if and only if they would refer to the
5119 // same member of the same most derived object or the same subobject if
5120 // they were dereferenced with a hypothetical object of the associated
5121 // class type.
5122 bool Equal = LHSValue == RHSValue;
5123 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5124 }
5125
5126 if (LHSTy->isNullPtrType()) {
5127 assert(E->isComparisonOp() && "unexpected nullptr operation");
5128 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5129 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5130 // are compared, the result is true of the operator is <=, >= or ==, and
5131 // false otherwise.
5132 BinaryOperator::Opcode Opcode = E->getOpcode();
5133 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5134 }
5135
5136 assert((!LHSTy->isIntegralOrEnumerationType() ||
5137 !RHSTy->isIntegralOrEnumerationType()) &&
5138 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5139 // We can't continue from here for non-integral types.
5140 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5141 }
5142
GetAlignOfType(QualType T)5143 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
5144 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5145 // result shall be the alignment of the referenced type."
5146 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5147 T = Ref->getPointeeType();
5148
5149 // __alignof is defined to return the preferred alignment.
5150 return Info.Ctx.toCharUnitsFromBits(
5151 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5152 }
5153
GetAlignOfExpr(const Expr * E)5154 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
5155 E = E->IgnoreParens();
5156
5157 // alignof decl is always accepted, even if it doesn't make sense: we default
5158 // to 1 in those cases.
5159 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5160 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5161 /*RefAsPointee*/true);
5162
5163 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5164 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5165 /*RefAsPointee*/true);
5166
5167 return GetAlignOfType(E->getType());
5168 }
5169
5170
5171 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5172 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)5173 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5174 const UnaryExprOrTypeTraitExpr *E) {
5175 switch(E->getKind()) {
5176 case UETT_AlignOf: {
5177 if (E->isArgumentType())
5178 return Success(GetAlignOfType(E->getArgumentType()), E);
5179 else
5180 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
5181 }
5182
5183 case UETT_VecStep: {
5184 QualType Ty = E->getTypeOfArgument();
5185
5186 if (Ty->isVectorType()) {
5187 unsigned n = Ty->castAs<VectorType>()->getNumElements();
5188
5189 // The vec_step built-in functions that take a 3-component
5190 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5191 if (n == 3)
5192 n = 4;
5193
5194 return Success(n, E);
5195 } else
5196 return Success(1, E);
5197 }
5198
5199 case UETT_SizeOf: {
5200 QualType SrcTy = E->getTypeOfArgument();
5201 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5202 // the result is the size of the referenced type."
5203 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5204 SrcTy = Ref->getPointeeType();
5205
5206 CharUnits Sizeof;
5207 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
5208 return false;
5209 return Success(Sizeof, E);
5210 }
5211 }
5212
5213 llvm_unreachable("unknown expr/type trait");
5214 }
5215
VisitOffsetOfExpr(const OffsetOfExpr * OOE)5216 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
5217 CharUnits Result;
5218 unsigned n = OOE->getNumComponents();
5219 if (n == 0)
5220 return Error(OOE);
5221 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
5222 for (unsigned i = 0; i != n; ++i) {
5223 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5224 switch (ON.getKind()) {
5225 case OffsetOfExpr::OffsetOfNode::Array: {
5226 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
5227 APSInt IdxResult;
5228 if (!EvaluateInteger(Idx, IdxResult, Info))
5229 return false;
5230 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5231 if (!AT)
5232 return Error(OOE);
5233 CurrentType = AT->getElementType();
5234 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5235 Result += IdxResult.getSExtValue() * ElementSize;
5236 break;
5237 }
5238
5239 case OffsetOfExpr::OffsetOfNode::Field: {
5240 FieldDecl *MemberDecl = ON.getField();
5241 const RecordType *RT = CurrentType->getAs<RecordType>();
5242 if (!RT)
5243 return Error(OOE);
5244 RecordDecl *RD = RT->getDecl();
5245 if (RD->isInvalidDecl()) return false;
5246 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5247 unsigned i = MemberDecl->getFieldIndex();
5248 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
5249 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
5250 CurrentType = MemberDecl->getType().getNonReferenceType();
5251 break;
5252 }
5253
5254 case OffsetOfExpr::OffsetOfNode::Identifier:
5255 llvm_unreachable("dependent __builtin_offsetof");
5256
5257 case OffsetOfExpr::OffsetOfNode::Base: {
5258 CXXBaseSpecifier *BaseSpec = ON.getBase();
5259 if (BaseSpec->isVirtual())
5260 return Error(OOE);
5261
5262 // Find the layout of the class whose base we are looking into.
5263 const RecordType *RT = CurrentType->getAs<RecordType>();
5264 if (!RT)
5265 return Error(OOE);
5266 RecordDecl *RD = RT->getDecl();
5267 if (RD->isInvalidDecl()) return false;
5268 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5269
5270 // Find the base class itself.
5271 CurrentType = BaseSpec->getType();
5272 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5273 if (!BaseRT)
5274 return Error(OOE);
5275
5276 // Add the offset to the base.
5277 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
5278 break;
5279 }
5280 }
5281 }
5282 return Success(Result, OOE);
5283 }
5284
VisitUnaryOperator(const UnaryOperator * E)5285 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5286 switch (E->getOpcode()) {
5287 default:
5288 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5289 // See C99 6.6p3.
5290 return Error(E);
5291 case UO_Extension:
5292 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5293 // If so, we could clear the diagnostic ID.
5294 return Visit(E->getSubExpr());
5295 case UO_Plus:
5296 // The result is just the value.
5297 return Visit(E->getSubExpr());
5298 case UO_Minus: {
5299 if (!Visit(E->getSubExpr()))
5300 return false;
5301 if (!Result.isInt()) return Error(E);
5302 const APSInt &Value = Result.getInt();
5303 if (Value.isSigned() && Value.isMinSignedValue())
5304 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5305 E->getType());
5306 return Success(-Value, E);
5307 }
5308 case UO_Not: {
5309 if (!Visit(E->getSubExpr()))
5310 return false;
5311 if (!Result.isInt()) return Error(E);
5312 return Success(~Result.getInt(), E);
5313 }
5314 case UO_LNot: {
5315 bool bres;
5316 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
5317 return false;
5318 return Success(!bres, E);
5319 }
5320 }
5321 }
5322
5323 /// HandleCast - This is used to evaluate implicit or explicit casts where the
5324 /// result type is integer.
VisitCastExpr(const CastExpr * E)5325 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5326 const Expr *SubExpr = E->getSubExpr();
5327 QualType DestType = E->getType();
5328 QualType SrcType = SubExpr->getType();
5329
5330 switch (E->getCastKind()) {
5331 case CK_BaseToDerived:
5332 case CK_DerivedToBase:
5333 case CK_UncheckedDerivedToBase:
5334 case CK_Dynamic:
5335 case CK_ToUnion:
5336 case CK_ArrayToPointerDecay:
5337 case CK_FunctionToPointerDecay:
5338 case CK_NullToPointer:
5339 case CK_NullToMemberPointer:
5340 case CK_BaseToDerivedMemberPointer:
5341 case CK_DerivedToBaseMemberPointer:
5342 case CK_ReinterpretMemberPointer:
5343 case CK_ConstructorConversion:
5344 case CK_IntegralToPointer:
5345 case CK_ToVoid:
5346 case CK_VectorSplat:
5347 case CK_IntegralToFloating:
5348 case CK_FloatingCast:
5349 case CK_CPointerToObjCPointerCast:
5350 case CK_BlockPointerToObjCPointerCast:
5351 case CK_AnyPointerToBlockPointerCast:
5352 case CK_ObjCObjectLValueCast:
5353 case CK_FloatingRealToComplex:
5354 case CK_FloatingComplexToReal:
5355 case CK_FloatingComplexCast:
5356 case CK_FloatingComplexToIntegralComplex:
5357 case CK_IntegralRealToComplex:
5358 case CK_IntegralComplexCast:
5359 case CK_IntegralComplexToFloatingComplex:
5360 case CK_BuiltinFnToFnPtr:
5361 llvm_unreachable("invalid cast kind for integral value");
5362
5363 case CK_BitCast:
5364 case CK_Dependent:
5365 case CK_LValueBitCast:
5366 case CK_ARCProduceObject:
5367 case CK_ARCConsumeObject:
5368 case CK_ARCReclaimReturnedObject:
5369 case CK_ARCExtendBlockObject:
5370 case CK_CopyAndAutoreleaseBlockObject:
5371 return Error(E);
5372
5373 case CK_UserDefinedConversion:
5374 case CK_LValueToRValue:
5375 case CK_AtomicToNonAtomic:
5376 case CK_NonAtomicToAtomic:
5377 case CK_NoOp:
5378 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5379
5380 case CK_MemberPointerToBoolean:
5381 case CK_PointerToBoolean:
5382 case CK_IntegralToBoolean:
5383 case CK_FloatingToBoolean:
5384 case CK_FloatingComplexToBoolean:
5385 case CK_IntegralComplexToBoolean: {
5386 bool BoolResult;
5387 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
5388 return false;
5389 return Success(BoolResult, E);
5390 }
5391
5392 case CK_IntegralCast: {
5393 if (!Visit(SubExpr))
5394 return false;
5395
5396 if (!Result.isInt()) {
5397 // Allow casts of address-of-label differences if they are no-ops
5398 // or narrowing. (The narrowing case isn't actually guaranteed to
5399 // be constant-evaluatable except in some narrow cases which are hard
5400 // to detect here. We let it through on the assumption the user knows
5401 // what they are doing.)
5402 if (Result.isAddrLabelDiff())
5403 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
5404 // Only allow casts of lvalues if they are lossless.
5405 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5406 }
5407
5408 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5409 Result.getInt()), E);
5410 }
5411
5412 case CK_PointerToIntegral: {
5413 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5414
5415 LValue LV;
5416 if (!EvaluatePointer(SubExpr, LV, Info))
5417 return false;
5418
5419 if (LV.getLValueBase()) {
5420 // Only allow based lvalue casts if they are lossless.
5421 // FIXME: Allow a larger integer size than the pointer size, and allow
5422 // narrowing back down to pointer width in subsequent integral casts.
5423 // FIXME: Check integer type's active bits, not its type size.
5424 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
5425 return Error(E);
5426
5427 LV.Designator.setInvalid();
5428 LV.moveInto(Result);
5429 return true;
5430 }
5431
5432 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5433 SrcType);
5434 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
5435 }
5436
5437 case CK_IntegralComplexToReal: {
5438 ComplexValue C;
5439 if (!EvaluateComplex(SubExpr, C, Info))
5440 return false;
5441 return Success(C.getComplexIntReal(), E);
5442 }
5443
5444 case CK_FloatingToIntegral: {
5445 APFloat F(0.0);
5446 if (!EvaluateFloat(SubExpr, F, Info))
5447 return false;
5448
5449 APSInt Value;
5450 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5451 return false;
5452 return Success(Value, E);
5453 }
5454 }
5455
5456 llvm_unreachable("unknown cast resulting in integral value");
5457 }
5458
VisitUnaryReal(const UnaryOperator * E)5459 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5460 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5461 ComplexValue LV;
5462 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5463 return false;
5464 if (!LV.isComplexInt())
5465 return Error(E);
5466 return Success(LV.getComplexIntReal(), E);
5467 }
5468
5469 return Visit(E->getSubExpr());
5470 }
5471
VisitUnaryImag(const UnaryOperator * E)5472 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5473 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
5474 ComplexValue LV;
5475 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5476 return false;
5477 if (!LV.isComplexInt())
5478 return Error(E);
5479 return Success(LV.getComplexIntImag(), E);
5480 }
5481
5482 VisitIgnoredValue(E->getSubExpr());
5483 return Success(0, E);
5484 }
5485
VisitSizeOfPackExpr(const SizeOfPackExpr * E)5486 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5487 return Success(E->getPackLength(), E);
5488 }
5489
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)5490 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5491 return Success(E->getValue(), E);
5492 }
5493
5494 //===----------------------------------------------------------------------===//
5495 // Float Evaluation
5496 //===----------------------------------------------------------------------===//
5497
5498 namespace {
5499 class FloatExprEvaluator
5500 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
5501 APFloat &Result;
5502 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)5503 FloatExprEvaluator(EvalInfo &info, APFloat &result)
5504 : ExprEvaluatorBaseTy(info), Result(result) {}
5505
Success(const APValue & V,const Expr * e)5506 bool Success(const APValue &V, const Expr *e) {
5507 Result = V.getFloat();
5508 return true;
5509 }
5510
ZeroInitialization(const Expr * E)5511 bool ZeroInitialization(const Expr *E) {
5512 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5513 return true;
5514 }
5515
5516 bool VisitCallExpr(const CallExpr *E);
5517
5518 bool VisitUnaryOperator(const UnaryOperator *E);
5519 bool VisitBinaryOperator(const BinaryOperator *E);
5520 bool VisitFloatingLiteral(const FloatingLiteral *E);
5521 bool VisitCastExpr(const CastExpr *E);
5522
5523 bool VisitUnaryReal(const UnaryOperator *E);
5524 bool VisitUnaryImag(const UnaryOperator *E);
5525
5526 // FIXME: Missing: array subscript of vector, member of vector
5527 };
5528 } // end anonymous namespace
5529
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)5530 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
5531 assert(E->isRValue() && E->getType()->isRealFloatingType());
5532 return FloatExprEvaluator(Info, Result).Visit(E);
5533 }
5534
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)5535 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
5536 QualType ResultTy,
5537 const Expr *Arg,
5538 bool SNaN,
5539 llvm::APFloat &Result) {
5540 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5541 if (!S) return false;
5542
5543 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5544
5545 llvm::APInt fill;
5546
5547 // Treat empty strings as if they were zero.
5548 if (S->getString().empty())
5549 fill = llvm::APInt(32, 0);
5550 else if (S->getString().getAsInteger(0, fill))
5551 return false;
5552
5553 if (SNaN)
5554 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5555 else
5556 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5557 return true;
5558 }
5559
VisitCallExpr(const CallExpr * E)5560 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
5561 switch (E->isBuiltinCall()) {
5562 default:
5563 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5564
5565 case Builtin::BI__builtin_huge_val:
5566 case Builtin::BI__builtin_huge_valf:
5567 case Builtin::BI__builtin_huge_vall:
5568 case Builtin::BI__builtin_inf:
5569 case Builtin::BI__builtin_inff:
5570 case Builtin::BI__builtin_infl: {
5571 const llvm::fltSemantics &Sem =
5572 Info.Ctx.getFloatTypeSemantics(E->getType());
5573 Result = llvm::APFloat::getInf(Sem);
5574 return true;
5575 }
5576
5577 case Builtin::BI__builtin_nans:
5578 case Builtin::BI__builtin_nansf:
5579 case Builtin::BI__builtin_nansl:
5580 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5581 true, Result))
5582 return Error(E);
5583 return true;
5584
5585 case Builtin::BI__builtin_nan:
5586 case Builtin::BI__builtin_nanf:
5587 case Builtin::BI__builtin_nanl:
5588 // If this is __builtin_nan() turn this into a nan, otherwise we
5589 // can't constant fold it.
5590 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5591 false, Result))
5592 return Error(E);
5593 return true;
5594
5595 case Builtin::BI__builtin_fabs:
5596 case Builtin::BI__builtin_fabsf:
5597 case Builtin::BI__builtin_fabsl:
5598 if (!EvaluateFloat(E->getArg(0), Result, Info))
5599 return false;
5600
5601 if (Result.isNegative())
5602 Result.changeSign();
5603 return true;
5604
5605 case Builtin::BI__builtin_copysign:
5606 case Builtin::BI__builtin_copysignf:
5607 case Builtin::BI__builtin_copysignl: {
5608 APFloat RHS(0.);
5609 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5610 !EvaluateFloat(E->getArg(1), RHS, Info))
5611 return false;
5612 Result.copySign(RHS);
5613 return true;
5614 }
5615 }
5616 }
5617
VisitUnaryReal(const UnaryOperator * E)5618 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5619 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5620 ComplexValue CV;
5621 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5622 return false;
5623 Result = CV.FloatReal;
5624 return true;
5625 }
5626
5627 return Visit(E->getSubExpr());
5628 }
5629
VisitUnaryImag(const UnaryOperator * E)5630 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5631 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5632 ComplexValue CV;
5633 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5634 return false;
5635 Result = CV.FloatImag;
5636 return true;
5637 }
5638
5639 VisitIgnoredValue(E->getSubExpr());
5640 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5641 Result = llvm::APFloat::getZero(Sem);
5642 return true;
5643 }
5644
VisitUnaryOperator(const UnaryOperator * E)5645 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5646 switch (E->getOpcode()) {
5647 default: return Error(E);
5648 case UO_Plus:
5649 return EvaluateFloat(E->getSubExpr(), Result, Info);
5650 case UO_Minus:
5651 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5652 return false;
5653 Result.changeSign();
5654 return true;
5655 }
5656 }
5657
VisitBinaryOperator(const BinaryOperator * E)5658 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5659 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5660 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5661
5662 APFloat RHS(0.0);
5663 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5664 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5665 return false;
5666 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
5667 return false;
5668
5669 switch (E->getOpcode()) {
5670 default: return Error(E);
5671 case BO_Mul:
5672 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5673 break;
5674 case BO_Add:
5675 Result.add(RHS, APFloat::rmNearestTiesToEven);
5676 break;
5677 case BO_Sub:
5678 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5679 break;
5680 case BO_Div:
5681 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5682 break;
5683 }
5684
5685 if (Result.isInfinity() || Result.isNaN())
5686 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5687 return true;
5688 }
5689
VisitFloatingLiteral(const FloatingLiteral * E)5690 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5691 Result = E->getValue();
5692 return true;
5693 }
5694
VisitCastExpr(const CastExpr * E)5695 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5696 const Expr* SubExpr = E->getSubExpr();
5697
5698 switch (E->getCastKind()) {
5699 default:
5700 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5701
5702 case CK_IntegralToFloating: {
5703 APSInt IntResult;
5704 return EvaluateInteger(SubExpr, IntResult, Info) &&
5705 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5706 E->getType(), Result);
5707 }
5708
5709 case CK_FloatingCast: {
5710 if (!Visit(SubExpr))
5711 return false;
5712 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5713 Result);
5714 }
5715
5716 case CK_FloatingComplexToReal: {
5717 ComplexValue V;
5718 if (!EvaluateComplex(SubExpr, V, Info))
5719 return false;
5720 Result = V.getComplexFloatReal();
5721 return true;
5722 }
5723 }
5724 }
5725
5726 //===----------------------------------------------------------------------===//
5727 // Complex Evaluation (for float and integer)
5728 //===----------------------------------------------------------------------===//
5729
5730 namespace {
5731 class ComplexExprEvaluator
5732 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5733 ComplexValue &Result;
5734
5735 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)5736 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5737 : ExprEvaluatorBaseTy(info), Result(Result) {}
5738
Success(const APValue & V,const Expr * e)5739 bool Success(const APValue &V, const Expr *e) {
5740 Result.setFrom(V);
5741 return true;
5742 }
5743
5744 bool ZeroInitialization(const Expr *E);
5745
5746 //===--------------------------------------------------------------------===//
5747 // Visitor Methods
5748 //===--------------------------------------------------------------------===//
5749
5750 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5751 bool VisitCastExpr(const CastExpr *E);
5752 bool VisitBinaryOperator(const BinaryOperator *E);
5753 bool VisitUnaryOperator(const UnaryOperator *E);
5754 bool VisitInitListExpr(const InitListExpr *E);
5755 };
5756 } // end anonymous namespace
5757
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)5758 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5759 EvalInfo &Info) {
5760 assert(E->isRValue() && E->getType()->isAnyComplexType());
5761 return ComplexExprEvaluator(Info, Result).Visit(E);
5762 }
5763
ZeroInitialization(const Expr * E)5764 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5765 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
5766 if (ElemTy->isRealFloatingType()) {
5767 Result.makeComplexFloat();
5768 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5769 Result.FloatReal = Zero;
5770 Result.FloatImag = Zero;
5771 } else {
5772 Result.makeComplexInt();
5773 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5774 Result.IntReal = Zero;
5775 Result.IntImag = Zero;
5776 }
5777 return true;
5778 }
5779
VisitImaginaryLiteral(const ImaginaryLiteral * E)5780 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5781 const Expr* SubExpr = E->getSubExpr();
5782
5783 if (SubExpr->getType()->isRealFloatingType()) {
5784 Result.makeComplexFloat();
5785 APFloat &Imag = Result.FloatImag;
5786 if (!EvaluateFloat(SubExpr, Imag, Info))
5787 return false;
5788
5789 Result.FloatReal = APFloat(Imag.getSemantics());
5790 return true;
5791 } else {
5792 assert(SubExpr->getType()->isIntegerType() &&
5793 "Unexpected imaginary literal.");
5794
5795 Result.makeComplexInt();
5796 APSInt &Imag = Result.IntImag;
5797 if (!EvaluateInteger(SubExpr, Imag, Info))
5798 return false;
5799
5800 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5801 return true;
5802 }
5803 }
5804
VisitCastExpr(const CastExpr * E)5805 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5806
5807 switch (E->getCastKind()) {
5808 case CK_BitCast:
5809 case CK_BaseToDerived:
5810 case CK_DerivedToBase:
5811 case CK_UncheckedDerivedToBase:
5812 case CK_Dynamic:
5813 case CK_ToUnion:
5814 case CK_ArrayToPointerDecay:
5815 case CK_FunctionToPointerDecay:
5816 case CK_NullToPointer:
5817 case CK_NullToMemberPointer:
5818 case CK_BaseToDerivedMemberPointer:
5819 case CK_DerivedToBaseMemberPointer:
5820 case CK_MemberPointerToBoolean:
5821 case CK_ReinterpretMemberPointer:
5822 case CK_ConstructorConversion:
5823 case CK_IntegralToPointer:
5824 case CK_PointerToIntegral:
5825 case CK_PointerToBoolean:
5826 case CK_ToVoid:
5827 case CK_VectorSplat:
5828 case CK_IntegralCast:
5829 case CK_IntegralToBoolean:
5830 case CK_IntegralToFloating:
5831 case CK_FloatingToIntegral:
5832 case CK_FloatingToBoolean:
5833 case CK_FloatingCast:
5834 case CK_CPointerToObjCPointerCast:
5835 case CK_BlockPointerToObjCPointerCast:
5836 case CK_AnyPointerToBlockPointerCast:
5837 case CK_ObjCObjectLValueCast:
5838 case CK_FloatingComplexToReal:
5839 case CK_FloatingComplexToBoolean:
5840 case CK_IntegralComplexToReal:
5841 case CK_IntegralComplexToBoolean:
5842 case CK_ARCProduceObject:
5843 case CK_ARCConsumeObject:
5844 case CK_ARCReclaimReturnedObject:
5845 case CK_ARCExtendBlockObject:
5846 case CK_CopyAndAutoreleaseBlockObject:
5847 case CK_BuiltinFnToFnPtr:
5848 llvm_unreachable("invalid cast kind for complex value");
5849
5850 case CK_LValueToRValue:
5851 case CK_AtomicToNonAtomic:
5852 case CK_NonAtomicToAtomic:
5853 case CK_NoOp:
5854 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5855
5856 case CK_Dependent:
5857 case CK_LValueBitCast:
5858 case CK_UserDefinedConversion:
5859 return Error(E);
5860
5861 case CK_FloatingRealToComplex: {
5862 APFloat &Real = Result.FloatReal;
5863 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5864 return false;
5865
5866 Result.makeComplexFloat();
5867 Result.FloatImag = APFloat(Real.getSemantics());
5868 return true;
5869 }
5870
5871 case CK_FloatingComplexCast: {
5872 if (!Visit(E->getSubExpr()))
5873 return false;
5874
5875 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5876 QualType From
5877 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5878
5879 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5880 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5881 }
5882
5883 case CK_FloatingComplexToIntegralComplex: {
5884 if (!Visit(E->getSubExpr()))
5885 return false;
5886
5887 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5888 QualType From
5889 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5890 Result.makeComplexInt();
5891 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5892 To, Result.IntReal) &&
5893 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5894 To, Result.IntImag);
5895 }
5896
5897 case CK_IntegralRealToComplex: {
5898 APSInt &Real = Result.IntReal;
5899 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5900 return false;
5901
5902 Result.makeComplexInt();
5903 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5904 return true;
5905 }
5906
5907 case CK_IntegralComplexCast: {
5908 if (!Visit(E->getSubExpr()))
5909 return false;
5910
5911 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5912 QualType From
5913 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5914
5915 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5916 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
5917 return true;
5918 }
5919
5920 case CK_IntegralComplexToFloatingComplex: {
5921 if (!Visit(E->getSubExpr()))
5922 return false;
5923
5924 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
5925 QualType From
5926 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
5927 Result.makeComplexFloat();
5928 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5929 To, Result.FloatReal) &&
5930 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5931 To, Result.FloatImag);
5932 }
5933 }
5934
5935 llvm_unreachable("unknown cast resulting in complex value");
5936 }
5937
VisitBinaryOperator(const BinaryOperator * E)5938 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5939 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5940 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5941
5942 bool LHSOK = Visit(E->getLHS());
5943 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5944 return false;
5945
5946 ComplexValue RHS;
5947 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5948 return false;
5949
5950 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5951 "Invalid operands to binary operator.");
5952 switch (E->getOpcode()) {
5953 default: return Error(E);
5954 case BO_Add:
5955 if (Result.isComplexFloat()) {
5956 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5957 APFloat::rmNearestTiesToEven);
5958 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5959 APFloat::rmNearestTiesToEven);
5960 } else {
5961 Result.getComplexIntReal() += RHS.getComplexIntReal();
5962 Result.getComplexIntImag() += RHS.getComplexIntImag();
5963 }
5964 break;
5965 case BO_Sub:
5966 if (Result.isComplexFloat()) {
5967 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5968 APFloat::rmNearestTiesToEven);
5969 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5970 APFloat::rmNearestTiesToEven);
5971 } else {
5972 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5973 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5974 }
5975 break;
5976 case BO_Mul:
5977 if (Result.isComplexFloat()) {
5978 ComplexValue LHS = Result;
5979 APFloat &LHS_r = LHS.getComplexFloatReal();
5980 APFloat &LHS_i = LHS.getComplexFloatImag();
5981 APFloat &RHS_r = RHS.getComplexFloatReal();
5982 APFloat &RHS_i = RHS.getComplexFloatImag();
5983
5984 APFloat Tmp = LHS_r;
5985 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5986 Result.getComplexFloatReal() = Tmp;
5987 Tmp = LHS_i;
5988 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5989 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5990
5991 Tmp = LHS_r;
5992 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5993 Result.getComplexFloatImag() = Tmp;
5994 Tmp = LHS_i;
5995 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5996 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5997 } else {
5998 ComplexValue LHS = Result;
5999 Result.getComplexIntReal() =
6000 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6001 LHS.getComplexIntImag() * RHS.getComplexIntImag());
6002 Result.getComplexIntImag() =
6003 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6004 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6005 }
6006 break;
6007 case BO_Div:
6008 if (Result.isComplexFloat()) {
6009 ComplexValue LHS = Result;
6010 APFloat &LHS_r = LHS.getComplexFloatReal();
6011 APFloat &LHS_i = LHS.getComplexFloatImag();
6012 APFloat &RHS_r = RHS.getComplexFloatReal();
6013 APFloat &RHS_i = RHS.getComplexFloatImag();
6014 APFloat &Res_r = Result.getComplexFloatReal();
6015 APFloat &Res_i = Result.getComplexFloatImag();
6016
6017 APFloat Den = RHS_r;
6018 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6019 APFloat Tmp = RHS_i;
6020 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6021 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6022
6023 Res_r = LHS_r;
6024 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6025 Tmp = LHS_i;
6026 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6027 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6028 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6029
6030 Res_i = LHS_i;
6031 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6032 Tmp = LHS_r;
6033 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6034 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6035 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6036 } else {
6037 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6038 return Error(E, diag::note_expr_divide_by_zero);
6039
6040 ComplexValue LHS = Result;
6041 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6042 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6043 Result.getComplexIntReal() =
6044 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6045 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6046 Result.getComplexIntImag() =
6047 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6048 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6049 }
6050 break;
6051 }
6052
6053 return true;
6054 }
6055
VisitUnaryOperator(const UnaryOperator * E)6056 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6057 // Get the operand value into 'Result'.
6058 if (!Visit(E->getSubExpr()))
6059 return false;
6060
6061 switch (E->getOpcode()) {
6062 default:
6063 return Error(E);
6064 case UO_Extension:
6065 return true;
6066 case UO_Plus:
6067 // The result is always just the subexpr.
6068 return true;
6069 case UO_Minus:
6070 if (Result.isComplexFloat()) {
6071 Result.getComplexFloatReal().changeSign();
6072 Result.getComplexFloatImag().changeSign();
6073 }
6074 else {
6075 Result.getComplexIntReal() = -Result.getComplexIntReal();
6076 Result.getComplexIntImag() = -Result.getComplexIntImag();
6077 }
6078 return true;
6079 case UO_Not:
6080 if (Result.isComplexFloat())
6081 Result.getComplexFloatImag().changeSign();
6082 else
6083 Result.getComplexIntImag() = -Result.getComplexIntImag();
6084 return true;
6085 }
6086 }
6087
VisitInitListExpr(const InitListExpr * E)6088 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6089 if (E->getNumInits() == 2) {
6090 if (E->getType()->isComplexType()) {
6091 Result.makeComplexFloat();
6092 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6093 return false;
6094 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6095 return false;
6096 } else {
6097 Result.makeComplexInt();
6098 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6099 return false;
6100 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6101 return false;
6102 }
6103 return true;
6104 }
6105 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6106 }
6107
6108 //===----------------------------------------------------------------------===//
6109 // Void expression evaluation, primarily for a cast to void on the LHS of a
6110 // comma operator
6111 //===----------------------------------------------------------------------===//
6112
6113 namespace {
6114 class VoidExprEvaluator
6115 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6116 public:
VoidExprEvaluator(EvalInfo & Info)6117 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6118
Success(const APValue & V,const Expr * e)6119 bool Success(const APValue &V, const Expr *e) { return true; }
6120
VisitCastExpr(const CastExpr * E)6121 bool VisitCastExpr(const CastExpr *E) {
6122 switch (E->getCastKind()) {
6123 default:
6124 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6125 case CK_ToVoid:
6126 VisitIgnoredValue(E->getSubExpr());
6127 return true;
6128 }
6129 }
6130 };
6131 } // end anonymous namespace
6132
EvaluateVoid(const Expr * E,EvalInfo & Info)6133 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6134 assert(E->isRValue() && E->getType()->isVoidType());
6135 return VoidExprEvaluator(Info).Visit(E);
6136 }
6137
6138 //===----------------------------------------------------------------------===//
6139 // Top level Expr::EvaluateAsRValue method.
6140 //===----------------------------------------------------------------------===//
6141
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)6142 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
6143 // In C, function designators are not lvalues, but we evaluate them as if they
6144 // are.
6145 if (E->isGLValue() || E->getType()->isFunctionType()) {
6146 LValue LV;
6147 if (!EvaluateLValue(E, LV, Info))
6148 return false;
6149 LV.moveInto(Result);
6150 } else if (E->getType()->isVectorType()) {
6151 if (!EvaluateVector(E, Result, Info))
6152 return false;
6153 } else if (E->getType()->isIntegralOrEnumerationType()) {
6154 if (!IntExprEvaluator(Info, Result).Visit(E))
6155 return false;
6156 } else if (E->getType()->hasPointerRepresentation()) {
6157 LValue LV;
6158 if (!EvaluatePointer(E, LV, Info))
6159 return false;
6160 LV.moveInto(Result);
6161 } else if (E->getType()->isRealFloatingType()) {
6162 llvm::APFloat F(0.0);
6163 if (!EvaluateFloat(E, F, Info))
6164 return false;
6165 Result = APValue(F);
6166 } else if (E->getType()->isAnyComplexType()) {
6167 ComplexValue C;
6168 if (!EvaluateComplex(E, C, Info))
6169 return false;
6170 C.moveInto(Result);
6171 } else if (E->getType()->isMemberPointerType()) {
6172 MemberPtr P;
6173 if (!EvaluateMemberPointer(E, P, Info))
6174 return false;
6175 P.moveInto(Result);
6176 return true;
6177 } else if (E->getType()->isArrayType()) {
6178 LValue LV;
6179 LV.set(E, Info.CurrentCall->Index);
6180 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
6181 return false;
6182 Result = Info.CurrentCall->Temporaries[E];
6183 } else if (E->getType()->isRecordType()) {
6184 LValue LV;
6185 LV.set(E, Info.CurrentCall->Index);
6186 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6187 return false;
6188 Result = Info.CurrentCall->Temporaries[E];
6189 } else if (E->getType()->isVoidType()) {
6190 if (Info.getLangOpts().CPlusPlus0x)
6191 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
6192 << E->getType();
6193 else
6194 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6195 if (!EvaluateVoid(E, Info))
6196 return false;
6197 } else if (Info.getLangOpts().CPlusPlus0x) {
6198 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
6199 return false;
6200 } else {
6201 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6202 return false;
6203 }
6204
6205 return true;
6206 }
6207
6208 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6209 /// cases, the in-place evaluation is essential, since later initializers for
6210 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,CheckConstantExpressionKind CCEK,bool AllowNonLiteralTypes)6211 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6212 const Expr *E, CheckConstantExpressionKind CCEK,
6213 bool AllowNonLiteralTypes) {
6214 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
6215 return false;
6216
6217 if (E->isRValue()) {
6218 // Evaluate arrays and record types in-place, so that later initializers can
6219 // refer to earlier-initialized members of the object.
6220 if (E->getType()->isArrayType())
6221 return EvaluateArray(E, This, Result, Info);
6222 else if (E->getType()->isRecordType())
6223 return EvaluateRecord(E, This, Result, Info);
6224 }
6225
6226 // For any other type, in-place evaluation is unimportant.
6227 return Evaluate(Result, Info, E);
6228 }
6229
6230 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6231 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)6232 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
6233 if (!CheckLiteralType(Info, E))
6234 return false;
6235
6236 if (!::Evaluate(Result, Info, E))
6237 return false;
6238
6239 if (E->isGLValue()) {
6240 LValue LV;
6241 LV.setFrom(Info.Ctx, Result);
6242 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
6243 return false;
6244 }
6245
6246 // Check this core constant expression is a constant expression.
6247 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
6248 }
6249
6250 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
6251 /// any crazy technique (that has nothing to do with language standards) that
6252 /// we want to. If this function returns true, it returns the folded constant
6253 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6254 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx) const6255 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
6256 // Fast-path evaluations of integer literals, since we sometimes see files
6257 // containing vast quantities of these.
6258 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6259 Result.Val = APValue(APSInt(L->getValue(),
6260 L->getType()->isUnsignedIntegerType()));
6261 return true;
6262 }
6263
6264 // FIXME: Evaluating values of large array and record types can cause
6265 // performance problems. Only do so in C++11 for now.
6266 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6267 !Ctx.getLangOpts().CPlusPlus0x)
6268 return false;
6269
6270 EvalInfo Info(Ctx, Result);
6271 return ::EvaluateAsRValue(Info, this, Result.Val);
6272 }
6273
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx) const6274 bool Expr::EvaluateAsBooleanCondition(bool &Result,
6275 const ASTContext &Ctx) const {
6276 EvalResult Scratch;
6277 return EvaluateAsRValue(Scratch, Ctx) &&
6278 HandleConversionToBool(Scratch.Val, Result);
6279 }
6280
EvaluateAsInt(APSInt & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects) const6281 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6282 SideEffectsKind AllowSideEffects) const {
6283 if (!getType()->isIntegralOrEnumerationType())
6284 return false;
6285
6286 EvalResult ExprResult;
6287 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6288 (!AllowSideEffects && ExprResult.HasSideEffects))
6289 return false;
6290
6291 Result = ExprResult.Val.getInt();
6292 return true;
6293 }
6294
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx) const6295 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
6296 EvalInfo Info(Ctx, Result);
6297
6298 LValue LV;
6299 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6300 !CheckLValueConstantExpression(Info, getExprLoc(),
6301 Ctx.getLValueReferenceType(getType()), LV))
6302 return false;
6303
6304 LV.moveInto(Result.Val);
6305 return true;
6306 }
6307
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,llvm::SmallVectorImpl<PartialDiagnosticAt> & Notes) const6308 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6309 const VarDecl *VD,
6310 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
6311 // FIXME: Evaluating initializers for large array and record types can cause
6312 // performance problems. Only do so in C++11 for now.
6313 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6314 !Ctx.getLangOpts().CPlusPlus0x)
6315 return false;
6316
6317 Expr::EvalStatus EStatus;
6318 EStatus.Diag = &Notes;
6319
6320 EvalInfo InitInfo(Ctx, EStatus);
6321 InitInfo.setEvaluatingDecl(VD, Value);
6322
6323 LValue LVal;
6324 LVal.set(VD);
6325
6326 // C++11 [basic.start.init]p2:
6327 // Variables with static storage duration or thread storage duration shall be
6328 // zero-initialized before any other initialization takes place.
6329 // This behavior is not present in C.
6330 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
6331 !VD->getType()->isReferenceType()) {
6332 ImplicitValueInitExpr VIE(VD->getType());
6333 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6334 /*AllowNonLiteralTypes=*/true))
6335 return false;
6336 }
6337
6338 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6339 /*AllowNonLiteralTypes=*/true) ||
6340 EStatus.HasSideEffects)
6341 return false;
6342
6343 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6344 Value);
6345 }
6346
6347 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6348 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx) const6349 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
6350 EvalResult Result;
6351 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
6352 }
6353
EvaluateKnownConstInt(const ASTContext & Ctx) const6354 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
6355 EvalResult EvalResult;
6356 bool Result = EvaluateAsRValue(EvalResult, Ctx);
6357 (void)Result;
6358 assert(Result && "Could not evaluate expression");
6359 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
6360
6361 return EvalResult.Val.getInt();
6362 }
6363
isGlobalLValue() const6364 bool Expr::EvalResult::isGlobalLValue() const {
6365 assert(Val.isLValue());
6366 return IsGlobalLValue(Val.getLValueBase());
6367 }
6368
6369
6370 /// isIntegerConstantExpr - this recursive routine will test if an expression is
6371 /// an integer constant expression.
6372
6373 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6374 /// comma, etc
6375 ///
6376 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6377 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6378 /// cast+dereference.
6379
6380 // CheckICE - This function does the fundamental ICE checking: the returned
6381 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6382 // Note that to reduce code duplication, this helper does no evaluation
6383 // itself; the caller checks whether the expression is evaluatable, and
6384 // in the rare cases where CheckICE actually cares about the evaluated
6385 // value, it calls into Evalute.
6386 //
6387 // Meanings of Val:
6388 // 0: This expression is an ICE.
6389 // 1: This expression is not an ICE, but if it isn't evaluated, it's
6390 // a legal subexpression for an ICE. This return value is used to handle
6391 // the comma operator in C99 mode.
6392 // 2: This expression is not an ICE, and is not a legal subexpression for one.
6393
6394 namespace {
6395
6396 struct ICEDiag {
6397 unsigned Val;
6398 SourceLocation Loc;
6399
6400 public:
ICEDiag__anon39b33ae21411::ICEDiag6401 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
ICEDiag__anon39b33ae21411::ICEDiag6402 ICEDiag() : Val(0) {}
6403 };
6404
6405 }
6406
NoDiag()6407 static ICEDiag NoDiag() { return ICEDiag(); }
6408
CheckEvalInICE(const Expr * E,ASTContext & Ctx)6409 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6410 Expr::EvalResult EVResult;
6411 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
6412 !EVResult.Val.isInt()) {
6413 return ICEDiag(2, E->getLocStart());
6414 }
6415 return NoDiag();
6416 }
6417
CheckICE(const Expr * E,ASTContext & Ctx)6418 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6419 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
6420 if (!E->getType()->isIntegralOrEnumerationType()) {
6421 return ICEDiag(2, E->getLocStart());
6422 }
6423
6424 switch (E->getStmtClass()) {
6425 #define ABSTRACT_STMT(Node)
6426 #define STMT(Node, Base) case Expr::Node##Class:
6427 #define EXPR(Node, Base)
6428 #include "clang/AST/StmtNodes.inc"
6429 case Expr::PredefinedExprClass:
6430 case Expr::FloatingLiteralClass:
6431 case Expr::ImaginaryLiteralClass:
6432 case Expr::StringLiteralClass:
6433 case Expr::ArraySubscriptExprClass:
6434 case Expr::MemberExprClass:
6435 case Expr::CompoundAssignOperatorClass:
6436 case Expr::CompoundLiteralExprClass:
6437 case Expr::ExtVectorElementExprClass:
6438 case Expr::DesignatedInitExprClass:
6439 case Expr::ImplicitValueInitExprClass:
6440 case Expr::ParenListExprClass:
6441 case Expr::VAArgExprClass:
6442 case Expr::AddrLabelExprClass:
6443 case Expr::StmtExprClass:
6444 case Expr::CXXMemberCallExprClass:
6445 case Expr::CUDAKernelCallExprClass:
6446 case Expr::CXXDynamicCastExprClass:
6447 case Expr::CXXTypeidExprClass:
6448 case Expr::CXXUuidofExprClass:
6449 case Expr::CXXNullPtrLiteralExprClass:
6450 case Expr::UserDefinedLiteralClass:
6451 case Expr::CXXThisExprClass:
6452 case Expr::CXXThrowExprClass:
6453 case Expr::CXXNewExprClass:
6454 case Expr::CXXDeleteExprClass:
6455 case Expr::CXXPseudoDestructorExprClass:
6456 case Expr::UnresolvedLookupExprClass:
6457 case Expr::DependentScopeDeclRefExprClass:
6458 case Expr::CXXConstructExprClass:
6459 case Expr::CXXBindTemporaryExprClass:
6460 case Expr::ExprWithCleanupsClass:
6461 case Expr::CXXTemporaryObjectExprClass:
6462 case Expr::CXXUnresolvedConstructExprClass:
6463 case Expr::CXXDependentScopeMemberExprClass:
6464 case Expr::UnresolvedMemberExprClass:
6465 case Expr::ObjCStringLiteralClass:
6466 case Expr::ObjCBoxedExprClass:
6467 case Expr::ObjCArrayLiteralClass:
6468 case Expr::ObjCDictionaryLiteralClass:
6469 case Expr::ObjCEncodeExprClass:
6470 case Expr::ObjCMessageExprClass:
6471 case Expr::ObjCSelectorExprClass:
6472 case Expr::ObjCProtocolExprClass:
6473 case Expr::ObjCIvarRefExprClass:
6474 case Expr::ObjCPropertyRefExprClass:
6475 case Expr::ObjCSubscriptRefExprClass:
6476 case Expr::ObjCIsaExprClass:
6477 case Expr::ShuffleVectorExprClass:
6478 case Expr::BlockExprClass:
6479 case Expr::NoStmtClass:
6480 case Expr::OpaqueValueExprClass:
6481 case Expr::PackExpansionExprClass:
6482 case Expr::SubstNonTypeTemplateParmPackExprClass:
6483 case Expr::AsTypeExprClass:
6484 case Expr::ObjCIndirectCopyRestoreExprClass:
6485 case Expr::MaterializeTemporaryExprClass:
6486 case Expr::PseudoObjectExprClass:
6487 case Expr::AtomicExprClass:
6488 case Expr::InitListExprClass:
6489 case Expr::LambdaExprClass:
6490 return ICEDiag(2, E->getLocStart());
6491
6492 case Expr::SizeOfPackExprClass:
6493 case Expr::GNUNullExprClass:
6494 // GCC considers the GNU __null value to be an integral constant expression.
6495 return NoDiag();
6496
6497 case Expr::SubstNonTypeTemplateParmExprClass:
6498 return
6499 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6500
6501 case Expr::ParenExprClass:
6502 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
6503 case Expr::GenericSelectionExprClass:
6504 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
6505 case Expr::IntegerLiteralClass:
6506 case Expr::CharacterLiteralClass:
6507 case Expr::ObjCBoolLiteralExprClass:
6508 case Expr::CXXBoolLiteralExprClass:
6509 case Expr::CXXScalarValueInitExprClass:
6510 case Expr::UnaryTypeTraitExprClass:
6511 case Expr::BinaryTypeTraitExprClass:
6512 case Expr::TypeTraitExprClass:
6513 case Expr::ArrayTypeTraitExprClass:
6514 case Expr::ExpressionTraitExprClass:
6515 case Expr::CXXNoexceptExprClass:
6516 return NoDiag();
6517 case Expr::CallExprClass:
6518 case Expr::CXXOperatorCallExprClass: {
6519 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6520 // constant expressions, but they can never be ICEs because an ICE cannot
6521 // contain an operand of (pointer to) function type.
6522 const CallExpr *CE = cast<CallExpr>(E);
6523 if (CE->isBuiltinCall())
6524 return CheckEvalInICE(E, Ctx);
6525 return ICEDiag(2, E->getLocStart());
6526 }
6527 case Expr::DeclRefExprClass: {
6528 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6529 return NoDiag();
6530 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6531 if (Ctx.getLangOpts().CPlusPlus &&
6532 D && IsConstNonVolatile(D->getType())) {
6533 // Parameter variables are never constants. Without this check,
6534 // getAnyInitializer() can find a default argument, which leads
6535 // to chaos.
6536 if (isa<ParmVarDecl>(D))
6537 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6538
6539 // C++ 7.1.5.1p2
6540 // A variable of non-volatile const-qualified integral or enumeration
6541 // type initialized by an ICE can be used in ICEs.
6542 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
6543 if (!Dcl->getType()->isIntegralOrEnumerationType())
6544 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6545
6546 const VarDecl *VD;
6547 // Look for a declaration of this variable that has an initializer, and
6548 // check whether it is an ICE.
6549 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6550 return NoDiag();
6551 else
6552 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6553 }
6554 }
6555 return ICEDiag(2, E->getLocStart());
6556 }
6557 case Expr::UnaryOperatorClass: {
6558 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6559 switch (Exp->getOpcode()) {
6560 case UO_PostInc:
6561 case UO_PostDec:
6562 case UO_PreInc:
6563 case UO_PreDec:
6564 case UO_AddrOf:
6565 case UO_Deref:
6566 // C99 6.6/3 allows increment and decrement within unevaluated
6567 // subexpressions of constant expressions, but they can never be ICEs
6568 // because an ICE cannot contain an lvalue operand.
6569 return ICEDiag(2, E->getLocStart());
6570 case UO_Extension:
6571 case UO_LNot:
6572 case UO_Plus:
6573 case UO_Minus:
6574 case UO_Not:
6575 case UO_Real:
6576 case UO_Imag:
6577 return CheckICE(Exp->getSubExpr(), Ctx);
6578 }
6579
6580 // OffsetOf falls through here.
6581 }
6582 case Expr::OffsetOfExprClass: {
6583 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6584 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6585 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6586 // compliance: we should warn earlier for offsetof expressions with
6587 // array subscripts that aren't ICEs, and if the array subscripts
6588 // are ICEs, the value of the offsetof must be an integer constant.
6589 return CheckEvalInICE(E, Ctx);
6590 }
6591 case Expr::UnaryExprOrTypeTraitExprClass: {
6592 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6593 if ((Exp->getKind() == UETT_SizeOf) &&
6594 Exp->getTypeOfArgument()->isVariableArrayType())
6595 return ICEDiag(2, E->getLocStart());
6596 return NoDiag();
6597 }
6598 case Expr::BinaryOperatorClass: {
6599 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6600 switch (Exp->getOpcode()) {
6601 case BO_PtrMemD:
6602 case BO_PtrMemI:
6603 case BO_Assign:
6604 case BO_MulAssign:
6605 case BO_DivAssign:
6606 case BO_RemAssign:
6607 case BO_AddAssign:
6608 case BO_SubAssign:
6609 case BO_ShlAssign:
6610 case BO_ShrAssign:
6611 case BO_AndAssign:
6612 case BO_XorAssign:
6613 case BO_OrAssign:
6614 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6615 // constant expressions, but they can never be ICEs because an ICE cannot
6616 // contain an lvalue operand.
6617 return ICEDiag(2, E->getLocStart());
6618
6619 case BO_Mul:
6620 case BO_Div:
6621 case BO_Rem:
6622 case BO_Add:
6623 case BO_Sub:
6624 case BO_Shl:
6625 case BO_Shr:
6626 case BO_LT:
6627 case BO_GT:
6628 case BO_LE:
6629 case BO_GE:
6630 case BO_EQ:
6631 case BO_NE:
6632 case BO_And:
6633 case BO_Xor:
6634 case BO_Or:
6635 case BO_Comma: {
6636 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6637 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6638 if (Exp->getOpcode() == BO_Div ||
6639 Exp->getOpcode() == BO_Rem) {
6640 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
6641 // we don't evaluate one.
6642 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
6643 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
6644 if (REval == 0)
6645 return ICEDiag(1, E->getLocStart());
6646 if (REval.isSigned() && REval.isAllOnesValue()) {
6647 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
6648 if (LEval.isMinSignedValue())
6649 return ICEDiag(1, E->getLocStart());
6650 }
6651 }
6652 }
6653 if (Exp->getOpcode() == BO_Comma) {
6654 if (Ctx.getLangOpts().C99) {
6655 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6656 // if it isn't evaluated.
6657 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6658 return ICEDiag(1, E->getLocStart());
6659 } else {
6660 // In both C89 and C++, commas in ICEs are illegal.
6661 return ICEDiag(2, E->getLocStart());
6662 }
6663 }
6664 if (LHSResult.Val >= RHSResult.Val)
6665 return LHSResult;
6666 return RHSResult;
6667 }
6668 case BO_LAnd:
6669 case BO_LOr: {
6670 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6671 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6672 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6673 // Rare case where the RHS has a comma "side-effect"; we need
6674 // to actually check the condition to see whether the side
6675 // with the comma is evaluated.
6676 if ((Exp->getOpcode() == BO_LAnd) !=
6677 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
6678 return RHSResult;
6679 return NoDiag();
6680 }
6681
6682 if (LHSResult.Val >= RHSResult.Val)
6683 return LHSResult;
6684 return RHSResult;
6685 }
6686 }
6687 }
6688 case Expr::ImplicitCastExprClass:
6689 case Expr::CStyleCastExprClass:
6690 case Expr::CXXFunctionalCastExprClass:
6691 case Expr::CXXStaticCastExprClass:
6692 case Expr::CXXReinterpretCastExprClass:
6693 case Expr::CXXConstCastExprClass:
6694 case Expr::ObjCBridgedCastExprClass: {
6695 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
6696 if (isa<ExplicitCastExpr>(E)) {
6697 if (const FloatingLiteral *FL
6698 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6699 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6700 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6701 APSInt IgnoredVal(DestWidth, !DestSigned);
6702 bool Ignored;
6703 // If the value does not fit in the destination type, the behavior is
6704 // undefined, so we are not required to treat it as a constant
6705 // expression.
6706 if (FL->getValue().convertToInteger(IgnoredVal,
6707 llvm::APFloat::rmTowardZero,
6708 &Ignored) & APFloat::opInvalidOp)
6709 return ICEDiag(2, E->getLocStart());
6710 return NoDiag();
6711 }
6712 }
6713 switch (cast<CastExpr>(E)->getCastKind()) {
6714 case CK_LValueToRValue:
6715 case CK_AtomicToNonAtomic:
6716 case CK_NonAtomicToAtomic:
6717 case CK_NoOp:
6718 case CK_IntegralToBoolean:
6719 case CK_IntegralCast:
6720 return CheckICE(SubExpr, Ctx);
6721 default:
6722 return ICEDiag(2, E->getLocStart());
6723 }
6724 }
6725 case Expr::BinaryConditionalOperatorClass: {
6726 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6727 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6728 if (CommonResult.Val == 2) return CommonResult;
6729 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6730 if (FalseResult.Val == 2) return FalseResult;
6731 if (CommonResult.Val == 1) return CommonResult;
6732 if (FalseResult.Val == 1 &&
6733 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6734 return FalseResult;
6735 }
6736 case Expr::ConditionalOperatorClass: {
6737 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6738 // If the condition (ignoring parens) is a __builtin_constant_p call,
6739 // then only the true side is actually considered in an integer constant
6740 // expression, and it is fully evaluated. This is an important GNU
6741 // extension. See GCC PR38377 for discussion.
6742 if (const CallExpr *CallCE
6743 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6744 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6745 return CheckEvalInICE(E, Ctx);
6746 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6747 if (CondResult.Val == 2)
6748 return CondResult;
6749
6750 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6751 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6752
6753 if (TrueResult.Val == 2)
6754 return TrueResult;
6755 if (FalseResult.Val == 2)
6756 return FalseResult;
6757 if (CondResult.Val == 1)
6758 return CondResult;
6759 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6760 return NoDiag();
6761 // Rare case where the diagnostics depend on which side is evaluated
6762 // Note that if we get here, CondResult is 0, and at least one of
6763 // TrueResult and FalseResult is non-zero.
6764 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6765 return FalseResult;
6766 }
6767 return TrueResult;
6768 }
6769 case Expr::CXXDefaultArgExprClass:
6770 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6771 case Expr::ChooseExprClass: {
6772 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6773 }
6774 }
6775
6776 llvm_unreachable("Invalid StmtClass!");
6777 }
6778
6779 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)6780 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6781 const Expr *E,
6782 llvm::APSInt *Value,
6783 SourceLocation *Loc) {
6784 if (!E->getType()->isIntegralOrEnumerationType()) {
6785 if (Loc) *Loc = E->getExprLoc();
6786 return false;
6787 }
6788
6789 APValue Result;
6790 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6791 return false;
6792
6793 assert(Result.isInt() && "pointer cast to int is not an ICE");
6794 if (Value) *Value = Result.getInt();
6795 return true;
6796 }
6797
isIntegerConstantExpr(ASTContext & Ctx,SourceLocation * Loc) const6798 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6799 if (Ctx.getLangOpts().CPlusPlus0x)
6800 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6801
6802 ICEDiag d = CheckICE(this, Ctx);
6803 if (d.Val != 0) {
6804 if (Loc) *Loc = d.Loc;
6805 return false;
6806 }
6807 return true;
6808 }
6809
isIntegerConstantExpr(llvm::APSInt & Value,ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const6810 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6811 SourceLocation *Loc, bool isEvaluated) const {
6812 if (Ctx.getLangOpts().CPlusPlus0x)
6813 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6814
6815 if (!isIntegerConstantExpr(Ctx, Loc))
6816 return false;
6817 if (!EvaluateAsInt(Value, Ctx))
6818 llvm_unreachable("ICE cannot be evaluated!");
6819 return true;
6820 }
6821
isCXX98IntegralConstantExpr(ASTContext & Ctx) const6822 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6823 return CheckICE(this, Ctx).Val == 0;
6824 }
6825
isCXX11ConstantExpr(ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const6826 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6827 SourceLocation *Loc) const {
6828 // We support this checking in C++98 mode in order to diagnose compatibility
6829 // issues.
6830 assert(Ctx.getLangOpts().CPlusPlus);
6831
6832 // Build evaluation settings.
6833 Expr::EvalStatus Status;
6834 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6835 Status.Diag = &Diags;
6836 EvalInfo Info(Ctx, Status);
6837
6838 APValue Scratch;
6839 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6840
6841 if (!Diags.empty()) {
6842 IsConstExpr = false;
6843 if (Loc) *Loc = Diags[0].first;
6844 } else if (!IsConstExpr) {
6845 // FIXME: This shouldn't happen.
6846 if (Loc) *Loc = getExprLoc();
6847 }
6848
6849 return IsConstExpr;
6850 }
6851
isPotentialConstantExpr(const FunctionDecl * FD,llvm::SmallVectorImpl<PartialDiagnosticAt> & Diags)6852 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6853 llvm::SmallVectorImpl<
6854 PartialDiagnosticAt> &Diags) {
6855 // FIXME: It would be useful to check constexpr function templates, but at the
6856 // moment the constant expression evaluator cannot cope with the non-rigorous
6857 // ASTs which we build for dependent expressions.
6858 if (FD->isDependentContext())
6859 return true;
6860
6861 Expr::EvalStatus Status;
6862 Status.Diag = &Diags;
6863
6864 EvalInfo Info(FD->getASTContext(), Status);
6865 Info.CheckingPotentialConstantExpression = true;
6866
6867 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6868 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6869
6870 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6871 // is a temporary being used as the 'this' pointer.
6872 LValue This;
6873 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6874 This.set(&VIE, Info.CurrentCall->Index);
6875
6876 ArrayRef<const Expr*> Args;
6877
6878 SourceLocation Loc = FD->getLocation();
6879
6880 APValue Scratch;
6881 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
6882 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6883 else
6884 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6885 Args, FD->getBody(), Info, Scratch);
6886
6887 return Diags.empty();
6888 }
6889